src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); void run(); void run(boolean noDBOpenRetry); @VisibleForTesting void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdition); void run(final LegacyKVStoreProvider storeProvider); static void main(String[] args); static final Comparator<Version> UPGRADE_VERSION_ORDERING; } | @Test public void testMaxTaskVersion() { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); final Optional<Version> tasksGreatestMaxVersion = upgrade.getUpgradeTasks().stream() .filter((v) -> v instanceof LegacyUpgradeTask) .map((v) -> ((LegacyUpgradeTask)v).getMaxVersion() ) .max(UPGRADE_VERSION_ORDERING); assertTrue( String.format("One task has a newer version (%s) than the current server version (%s)", tasksGreatestMaxVersion.get(), VERSION), UPGRADE_VERSION_ORDERING.compare(tasksGreatestMaxVersion.get(), VERSION) <= 0); }
@Test public void testTasksOrder() { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks(); boolean isMapr = Boolean.valueOf(System.getProperty("dremio.mapr.profile")); boolean containsS3Task = false; int s3TaskIndex = 0; boolean containsDatasetSplitTask = false; int datasetSplitTaskIndex = 0; for (int i = 0; i < tasks.size(); i++) { String taskName = tasks.get(i).getClass().getName(); if ("com.dremio.dac.cmd.upgrade.UpdateS3CredentialType".equals(taskName)) { containsS3Task = true; s3TaskIndex = i; } else if ("com.dremio.dac.cmd.upgrade.UpdateDatasetSplitIdTask".equals(taskName)) { containsDatasetSplitTask = true; datasetSplitTaskIndex = i; } } if (isMapr) { assertFalse(containsS3Task); } else { assertTrue(containsDatasetSplitTask); assertTrue(containsS3Task); assertTrue(s3TaskIndex > datasetSplitTaskIndex); tasks.remove(s3TaskIndex); } assertThat(tasks, contains( instanceOf(DatasetConfigUpgrade.class), instanceOf(ReIndexAllStores.class), instanceOf(UpdateDatasetSplitIdTask.class), instanceOf(DeleteHistoryOfRenamedDatasets.class), instanceOf(DeleteHive121BasedInputSplits.class), instanceOf(MinimizeJobResultsMetadata.class), instanceOf(UpdateExternalReflectionHash.class), instanceOf(DeleteSysMaterializationsMetadata.class), instanceOf(SetTableauDefaults.class), instanceOf(TopPriorityTask.class), instanceOf(LowPriorityTask.class) )); }
@Test public void testTasksWithoutUUID() throws Exception { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks(); tasks.forEach(task -> assertNotNull( String.format( "Need to add UUID to task: '%s'. For example: %s", task.getTaskName(), UUID.randomUUID().toString()), task.getTaskUUID())); }
@Test public void testNoDuplicateUUID() throws Exception { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks(); Set<String> uuidToCount = new HashSet<>(); tasks.forEach(task -> assertTrue( String.format( "Task %s has duplicate UUID. Use some other UUID. For example: %s", task.getTaskName(), UUID.randomUUID().toString()), uuidToCount.add(task.getTaskUUID()))); }
@Test public void testDependenciesResolver() throws Exception { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); List<? extends UpgradeTask> tasks = upgrade.getUpgradeTasks(); boolean isMapr = Boolean.valueOf(System.getProperty("dremio.mapr.profile")); boolean containsS3Task = false; int s3TaskIndex = 0; boolean containsDatasetSplitTask = false; int datasetSplitTaskIndex = 0; for (int i = 0; i < tasks.size(); i++) { String taskName = tasks.get(i).getClass().getName(); if ("com.dremio.dac.cmd.upgrade.UpdateS3CredentialType".equals(taskName)) { containsS3Task = true; s3TaskIndex = i; } else if ("com.dremio.dac.cmd.upgrade.UpdateDatasetSplitIdTask".equals(taskName)) { containsDatasetSplitTask = true; datasetSplitTaskIndex = i; } } if (isMapr) { assertFalse(containsS3Task); } else { assertTrue(containsDatasetSplitTask); assertTrue(containsS3Task); assertTrue(s3TaskIndex > datasetSplitTaskIndex); tasks.remove(s3TaskIndex); } Collections.shuffle(tasks); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver(tasks); List<UpgradeTask> resolvedTasks = upgradeTaskDependencyResolver.topologicalTasksSort(); assertThat(resolvedTasks, contains( instanceOf(DatasetConfigUpgrade.class), instanceOf(ReIndexAllStores.class), instanceOf(UpdateDatasetSplitIdTask.class), instanceOf(DeleteHistoryOfRenamedDatasets.class), instanceOf(DeleteHive121BasedInputSplits.class), instanceOf(MinimizeJobResultsMetadata.class), instanceOf(UpdateExternalReflectionHash.class), instanceOf(DeleteSysMaterializationsMetadata.class), instanceOf(SetTableauDefaults.class), instanceOf(TopPriorityTask.class), instanceOf(LowPriorityTask.class) )); } |
ReflectionResource { @POST public Reflection createReflection(Reflection reflection) { ReflectionGoal newReflection = reflectionServiceHelper.createReflection(reflection.toReflectionGoal()); String id = newReflection.getId().getId(); return new Reflection(newReflection, reflectionServiceHelper.getStatusForReflection(id), reflectionServiceHelper.getCurrentSize(id), reflectionServiceHelper.getTotalSize(id)); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{id}") Reflection getReflection(@PathParam("id") String id); @POST Reflection createReflection(Reflection reflection); @PUT @Path("/{id}") Reflection editReflection(@PathParam("id") String id, Reflection reflection); @DELETE @Path("/{id}") Response deleteReflection(@PathParam("id") String id); } | @Test public void testUpdateReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); String betterName = "much better name"; response.setName(betterName); Reflection response2 = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildPut(Entity.entity(response, JSON)), Reflection.class); assertEquals(response2.getId(), response.getId()); assertEquals(response2.getName(), betterName); assertEquals(response2.getType(), response.getType()); assertEquals(response2.getCreatedAt(), response.getCreatedAt()); assertTrue(response2.getUpdatedAt() > response.getUpdatedAt()); assertNotEquals(response2.getTag(), response.getTag()); assertEquals(response2.getDisplayFields(), response.getDisplayFields()); assertEquals(response2.getDimensionFields(), response.getDimensionFields()); assertEquals(response2.getDistributionFields(), response.getDistributionFields()); assertEquals(response2.getMeasureFields(), response.getMeasureFields()); assertEquals(response2.getPartitionFields(), response.getPartitionFields()); assertEquals(response2.getSortFields(), response.getSortFields()); assertEquals(response2.getPartitionDistributionStrategy(), response.getPartitionDistributionStrategy()); newReflectionServiceHelper().removeReflection(response2.getId()); }
@Test public void testBoostToggleOnRawReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); assertFalse(response.isArrowCachingEnabled()); response.setArrowCachingEnabled(true); response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildPut(Entity.entity(response, JSON)), Reflection.class); assertTrue(response.isArrowCachingEnabled()); }
@Test public void testCreateReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); assertEquals(response.getDatasetId(), newReflection.getDatasetId()); assertEquals(response.getName(), newReflection.getName()); assertEquals(response.getType(), newReflection.getType()); assertEquals(response.isEnabled(), newReflection.isEnabled()); assertNotNull(response.getCreatedAt()); assertNotNull(response.getUpdatedAt()); assertNotNull(response.getStatus()); assertNotNull(response.getTag()); assertNotNull(response.getId()); assertEquals(response.getDisplayFields(), newReflection.getDisplayFields()); assertNull(response.getDimensionFields()); assertNull(response.getDistributionFields()); assertNull(response.getMeasureFields()); assertNull(response.getPartitionFields()); assertNull(response.getSortFields()); assertEquals(response.getPartitionDistributionStrategy(), newReflection.getPartitionDistributionStrategy()); newReflectionServiceHelper().removeReflection(response.getId()); } |
ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{id}") Reflection getReflection(@PathParam("id") String id); @POST Reflection createReflection(Reflection reflection); @PUT @Path("/{id}") Reflection editReflection(@PathParam("id") String id, Reflection reflection); @DELETE @Path("/{id}") Response deleteReflection(@PathParam("id") String id); } | @Test public void testDeleteReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildDelete()); assertFalse(newReflectionServiceHelper().getReflectionById(response.getId()).isPresent()); } |
SourceResource { @GET @RolesAllowed({"admin", "user"}) public ResponseList<Source> getSources() { final ResponseList<Source> sources = new ResponseList<>(); final List<SourceConfig> sourceConfigs = sourceService.getSources(); for (SourceConfig sourceConfig : sourceConfigs) { Source source = fromSourceConfig(sourceConfig); sources.add(source); } return sources; } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testListSources() throws Exception { ResponseList<SourceResource.SourceDeprecated> sources = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH)).buildGet(), new GenericType<ResponseList<SourceResource.SourceDeprecated>>() {}); assertEquals(sources.getData().size(), newSourceService().getSources().size()); } |
SourceResource { @POST @RolesAllowed({"admin"}) public SourceDeprecated addSource(SourceDeprecated source) { try { SourceConfig newSourceConfig = sourceService.createSource(source.toSourceConfig()); return fromSourceConfig(newSourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw new ServerErrorException(e); } } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testAddSource() throws Exception { SourceResource.SourceDeprecated newSource = new SourceResource.SourceDeprecated(); newSource.setName("Foopy"); newSource.setType("NAS"); NASConf config = new NASConf(); config.path = "/"; newSource.setConfig(config); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH)).buildPost(Entity.entity(newSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals(source.getName(), newSource.getName()); assertNotNull(source.getState()); deleteSource(source.getName()); } |
SourceResource { @PUT @RolesAllowed({"admin"}) @Path("/{id}") public SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source) { SourceConfig sourceConfig; try { sourceConfig = sourceService.updateSource(id, source.toSourceConfig()); return fromSourceConfig(sourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw new ServerErrorException(e); } } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testUpdateSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy2"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); final AccelerationSettings settings = new AccelerationSettings() .setMethod(RefreshMethod.FULL) .setRefreshPeriod(TimeUnit.HOURS.toMillis(2)) .setGracePeriod(TimeUnit.HOURS.toMillis(6)); SourceResource.SourceDeprecated updatedSource = new SourceResource.SourceDeprecated(createdSourceConfig, settings, reader, null); updatedSource.setDescription("Desc"); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals("Desc", source.getDescription()); assertNotNull(source.getState()); assertNotNull(source.getTag()); deleteSource(source.getName()); } |
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testUpdateSourceErrors() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy5"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); final AccelerationSettings settings = new AccelerationSettings() .setMethod(RefreshMethod.FULL) .setRefreshPeriod(TimeUnit.HOURS.toMillis(2)) .setGracePeriod(TimeUnit.HOURS.toMillis(6)); SourceResource.SourceDeprecated updatedSource = new SourceResource.SourceDeprecated(createdSourceConfig, settings, reader, null); expectStatus(Response.Status.NOT_FOUND, getBuilder(getPublicAPI(3).path(SOURCES_PATH).path("badid")).buildPut(Entity.entity(updatedSource, JSON))); updatedSource.setTag("badtag"); expectStatus(Response.Status.CONFLICT, getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON))); deleteSource(updatedSource.getName()); }
@Test public void testUpdateSourceBoundaryValues() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy2"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); final AccelerationSettings settings = new AccelerationSettings() .setMethod(RefreshMethod.FULL) .setRefreshPeriod(TimeUnit.HOURS.toMillis(2)) .setGracePeriod(TimeUnit.HOURS.toMillis(6)); SourceResource.SourceDeprecated updatedSource = new SourceResource.SourceDeprecated(createdSourceConfig, settings, reader, null); updatedSource.getMetadataPolicy().setDatasetRefreshAfterMs(MetadataPolicy.ONE_MINUTE_IN_MS); updatedSource.getMetadataPolicy().setAuthTTLMs(MetadataPolicy.ONE_MINUTE_IN_MS); updatedSource.getMetadataPolicy().setNamesRefreshMs(MetadataPolicy.ONE_MINUTE_IN_MS); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals(source.getMetadataPolicy().getAuthTTLMs(), updatedSource.getMetadataPolicy().getAuthTTLMs()); assertEquals(source.getMetadataPolicy().getDatasetRefreshAfterMs(), updatedSource.getMetadataPolicy().getDatasetRefreshAfterMs()); assertEquals(source.getMetadataPolicy().getNamesRefreshMs(), updatedSource.getMetadataPolicy().getNamesRefreshMs()); deleteSource(createdSourceConfig.getName()); }
@Test public void testDeleteSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy3"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildDelete()); } |
SourceResource { @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testGetSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy4"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildGet(), SourceResource.SourceDeprecated.class); assertEquals(source.getName(), sourceConfig.getName()); assertNotNull(source.getState()); } |
SetTableauDefaults extends UpgradeTask { @VisibleForTesting static boolean updateOptionsIfNeeded(Version previousVersion, Supplier<SystemOptionManager> optionManagerSupplier, boolean isOptionManagerOpen) throws Exception { if (Upgrade.UPGRADE_VERSION_ORDERING.compare(previousVersion, VERSION_460) >= 0) { return false; } final SystemOptionManager optionManager = optionManagerSupplier.get(); try { if (!isOptionManagerOpen) { optionManager.start(); } final OptionValue regularTableauDefault = TableauResource.CLIENT_TOOLS_TABLEAU.getDefault(); final OptionValue tableauEnable = OptionValue.createBoolean(regularTableauDefault.getType(), regularTableauDefault.getName(), true); if (!optionManager.isSet(TableauResource.CLIENT_TOOLS_TABLEAU.getOptionName())) { optionManager.setOption(tableauEnable); return true; } return false; } finally { if (!isOptionManagerOpen) { optionManager.close(); } } } SetTableauDefaults(); @Override String getTaskUUID(); @Override void upgrade(UpgradeContext context); } | @Test public void testPost460Version() throws Exception { final Version version = new Version("4.6.1", 4, 6, 1, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@Test public void testPost4x0Version() throws Exception { final Version version = new Version("5.2.0", 5, 2, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@Test public void testPre460VersionAndKeyExists() throws Exception { final Version version = new Version("5.1.0", 5, 2, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertFalse(optionManager.isSet(TableauResource.CLIENT_TOOLS_TABLEAU.getOptionName())); }
@Test public void testPre4x0Version() throws Exception { final Version version = new Version("3.9.0", 3, 9, 0, 0, ""); assertTrue(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertTrue(optionManager.getOption(TableauResource.CLIENT_TOOLS_TABLEAU)); }
@Test public void testPre460Version() throws Exception { final Version version = new Version("4.5.9", 4, 5, 9, 0, ""); assertTrue(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertTrue(optionManager.getOption(TableauResource.CLIENT_TOOLS_TABLEAU)); }
@Test public void test460Version() throws Exception { final Version version = new Version("4.6.0", 4, 6, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); } |
SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); } | @Test public void testRemovingSensitiveFields() throws Exception { SourceConfig config = new SourceConfig(); config.setName("Foopy"); config.setId(new EntityId("id")); config.setTag("0"); config.setAccelerationGracePeriod(0L); config.setAccelerationRefreshPeriod(0L); APrivateSource priv = new APrivateSource(); priv.password = "hello"; config.setConnectionConf(priv); SourceResource sourceResource = new SourceResource(newSourceService(), null); SourceResource.SourceDeprecated source = sourceResource.fromSourceConfig(config); APrivateSource newConfig = (APrivateSource) source.getConfig(); assertEquals(newConfig.password, ConnectionConf.USE_EXISTING_SECRET_VALUE); } |
JobResource extends BaseResourceWithAllocator { @POST @Path("/{id}/cancel") public void cancelJob(@PathParam("id") String id) throws JobException { final String username = securityContext.getUserPrincipal().getName(); try { jobs.cancel(CancelJobRequest.newBuilder() .setUsername(username) .setJobId(JobsProtoUtil.toBuf(new JobId(id))) .setReason(String.format("Query cancelled by user '%s'", username)) .build()); } catch (JobNotFoundException e) { throw new NotFoundException(String.format("Could not find a job with id [%s]", id)); } } @Inject JobResource(JobsService jobs, SecurityContext securityContext, BufferAllocatorFactory allocatorFactory); @GET @Path("/{id}") JobStatus getJobStatus(@PathParam("id") String id); @GET @Path("/{id}/results") JobResourceData getQueryResults(@PathParam("id") String id, @QueryParam("offset") @DefaultValue("0") Integer offset, @Valid @QueryParam("limit") @DefaultValue("100") Integer limit); @POST @Path("/{id}/cancel") void cancelJob(@PathParam("id") String id); @GET @Path("/{id}/reflection/{reflectionId}") JobStatus getReflectionJobStatus(@PathParam("id") String id,
@PathParam("reflectionId") String reflectionId); @POST @Path("/{id}/reflection/{reflectionId}/cancel") void cancelReflectionJob(@PathParam("id") String id,
@PathParam("reflectionId") String reflectionId); } | @Test public void testCancelJob() throws InterruptedException { JobsService jobs = l(JobsService.class); SqlQuery query = new SqlQuery("select * from sys.version", Collections.emptyList(), SystemUser.SYSTEM_USERNAME); final String id = submitAndWaitUntilSubmitted( JobRequest.newBuilder() .setSqlQuery(query) .setQueryType(QueryType.REST) .build() ).getId(); expectSuccess(getBuilder(getPublicAPI(3).path(JOB_PATH).path(id).path("cancel")).buildPost(null)); String cancelReason = "Query cancelled by user 'dremio'"; while (true) { JobStatus status = expectSuccess(getBuilder(getPublicAPI(3).path(JOB_PATH).path(id)).buildGet(), JobStatus.class); JobState jobState = status.getJobState(); Assert.assertTrue("expected job to cancel successfully", Arrays .asList(JobState.PLANNING, JobState.RUNNING, JobState.STARTING, JobState.CANCELED, JobState.PENDING, JobState.METADATA_RETRIEVAL, JobState.QUEUED, JobState.ENGINE_START, JobState.EXECUTION_PLANNING, JobState.FAILED) .contains(jobState)); if (jobState == JobState.CANCELED) { expectStatus(Response.Status.BAD_REQUEST, getBuilder(getPublicAPI(3).path(JOB_PATH).path(id).path("results").queryParam("limit", 1000)).buildGet()); assertEquals(cancelReason, status.getCancellationReason()); break; } else if (jobState == JobState.COMPLETED) { break; } else if (jobState == JobState.FAILED) { assertEquals(cancelReason, status.getErrorMessage()); break; } else { Thread.sleep(TimeUnit.MILLISECONDS.toMillis(100)); } } } |
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } } @Inject UserStatsResource(JobsService jobsService, EditionProvider editionProvider); @GET UserStats getActiveUserStats(); } | @Test public void testActiveUserStats() { EditionProvider editionProvider = mock(EditionProvider.class); when(editionProvider.getEdition()).thenReturn("oss-test"); LocalDate now = LocalDate.now(); List<JobSummary> testJobResults = new ArrayList<>(); testJobResults.add(newJob("testuser1", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, now)); testJobResults.add(newJob("testuser2", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); JobsService jobsService = mock(JobsService.class); when(jobsService.searchJobs(any(SearchJobsRequest.class))).thenReturn(testJobResults); UserStatsResource resource = new UserStatsResource(jobsService, editionProvider); UserStats stats = resource.getActiveUserStats(); List<Map<String, Object>> statsByDate = stats.getUserStatsByDate(); Map<String, Object> firstDateEntry = fetchDateEntry("date", now.toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI_PREVIEW")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("date", DateUtils.getLastSundayDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI_PREVIEW")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); Map<String, Object> weekDateEntry = fetchDateEntry("week", DateUtils.getLastSundayDate(now).toString(), stats.getUserStatsByWeek()); assertEquals(1, weekDateEntry.get("UI_PREVIEW")); assertEquals(2, weekDateEntry.get("ODBC")); assertEquals(2, weekDateEntry.get("total")); Map<String, Object> monthDateEntry = fetchDateEntry("month", DateUtils.getMonthStartDate(now).toString(), stats.getUserStatsByMonth()); assertEquals(1, monthDateEntry.get("UI_PREVIEW")); assertEquals(2, monthDateEntry.get("ODBC")); assertEquals(2, monthDateEntry.get("total")); Map<String, Object> lastMonthEntry = fetchDateEntry("month", DateUtils.getMonthStartDate(now.minusMonths(1)).toString(), stats.getUserStatsByMonth()); assertEquals(1, lastMonthEntry.get("UI_PREVIEW")); assertEquals(2, lastMonthEntry.get("ODBC")); assertEquals(2, lastMonthEntry.get("total")); } |
ClusterStatsResource { @VisibleForTesting public static Stats getSources(List<SourceConfig> allSources, SabotContext context){ final Stats resource = new Stats(); for (SourceConfig sourceConfig : allSources) { int pdsCount = -1; String type = sourceConfig.getType(); if(type == null && sourceConfig.getLegacySourceTypeEnum() != null) { type = sourceConfig.getLegacySourceTypeEnum().name(); } if("S3".equals(type) && sourceConfig.getName().startsWith("Samples")) { type = "SamplesS3"; } SourceStats source = new SourceStats(sourceConfig.getId(), type, pdsCount); resource.addVdsQuery(SearchQueryUtils.newTermQuery(DATASET_SOURCES, sourceConfig.getName())); resource.addSource(source); } return resource; } @Inject ClusterStatsResource(
Provider<SabotContext> context,
SourceService sourceService,
NamespaceService namespaceService,
JobsService jobsService,
ReflectionServiceHelper reflectionServiceHelper,
EditionProvider editionProvider
); @GET @RolesAllowed({"admin", "user"}) ClusterStats getStats(@DefaultValue("false") @QueryParam("showCompactStats") final boolean showCompactStats); @VisibleForTesting static Stats getSources(List<SourceConfig> allSources, SabotContext context); } | @Test public void testListSources() throws Exception { ClusterStatsResource.ClusterStats stats = expectSuccess(getBuilder(getPublicAPI(3).path(PATH)).buildGet(), ClusterStatsResource.ClusterStats.class); assertNotNull(stats); assertEquals(stats.getSources().size(), newSourceService().getSources().size()); }
@Test public void testSamplesS3() throws Exception{ List<SourceConfig> sources = new ArrayList(); SourceConfig configS3Samples = new SourceConfig(); configS3Samples.setMetadataPolicy(DEFAULT_METADATA_POLICY_WITH_AUTO_PROMOTE); configS3Samples.setName("Samples"); configS3Samples.setType("S3"); SourceConfig configS3 = new SourceConfig(); configS3.setMetadataPolicy(DEFAULT_METADATA_POLICY_WITH_AUTO_PROMOTE); configS3.setName("SourceS3"); configS3.setType("S3"); sources.add(configS3Samples); sources.add(configS3); ClusterStatsResource.Stats result = ClusterStatsResource.getSources(sources,getSabotContext()); assertTrue("Type is incorrect", "SamplesS3".equals(result.getAllSources().get(0).getType())); assertTrue("Type is incorrect", "S3".equals(result.getAllSources().get(1).getType())); } |
CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } @Inject CatalogResource(CatalogServiceHelper catalogServiceHelper); @GET ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include); @GET @Path("/{id}") CatalogEntity getCatalogItem(@PathParam("id") String id,
@QueryParam("include") final List<String> include); @POST CatalogEntity createCatalogItem(CatalogEntity entity); @POST @Path("/{id}") Dataset promoteToDataset(Dataset dataset, @PathParam("id") String id); @PUT @Path("/{id}") CatalogEntity updateCatalogItem(CatalogEntity entity, @PathParam("id") String id); @DELETE @Path("/{id}") void deleteCatalogItem(@PathParam("id") String id, @QueryParam("tag") String tag); @POST @Path("/{id}/refresh") void refreshCatalogItem(@PathParam("id") String id); @POST @Path("/{id}/metadata/refresh") MetadataRefreshResponse refreshCatalogItemMetadata(@PathParam("id") String id,
@QueryParam("deleteWhenMissing") Boolean delete,
@QueryParam("forceUpdate") Boolean force,
@QueryParam("autoPromotion") Boolean promotion); @GET @Path("/by-path/{segment:.*}") CatalogEntity getCatalogItemByPath(@PathParam("segment") List<PathSegment> segments); @GET @Path("/search") ResponseList<CatalogItem> search(@QueryParam("query") String query); } | @Test public void testListTopLevelCatalog() throws Exception { int topLevelCount = newSourceService().getSources().size() + newNamespaceService().getSpaces().size() + 1; ResponseList<CatalogItem> items = getRootEntities(null); assertEquals(items.getData().size(), topLevelCount); int homeCount = 0; int spaceCount = 0; int sourceCount = 0; for (CatalogItem item : items.getData()) { if (item.getType() == CatalogItem.CatalogItemType.CONTAINER) { if (item.getContainerType() == CatalogItem.ContainerSubType.HOME) { homeCount++; } if (item.getContainerType() == CatalogItem.ContainerSubType.SPACE) { spaceCount++; } if (item.getContainerType() == CatalogItem.ContainerSubType.SOURCE) { sourceCount++; } } } assertEquals(homeCount, 1); assertEquals(spaceCount, newNamespaceService().getSpaces().size()); assertEquals(sourceCount, 1); } |
UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); } | @Test public void testGetUserById() throws Exception { final UserService userService = l(UserService.class); com.dremio.service.users.User user1 = userService.getUser("user1"); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(user1.getUID().getId())).buildGet(), User.class); assertEquals(user.getId(), user1.getUID().getId()); assertEquals(user.getName(), user1.getUserName()); }
@Test public void testGetUserDetails() throws Exception { final UserService userService = l(UserService.class); com.dremio.service.users.User user1 = userService.getUser("user1"); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(user1.getUID().getId())) .buildGet(), User.class); assertEquals(user.getId(), user1.getUID().getId()); assertEquals(user.getName(), user1.getUserName()); assertEquals(user.getFirstName(), user1.getFirstName()); assertEquals(user.getLastName(), user1.getLastName()); assertEquals(user.getEmail(), user1.getEmail()); assertEquals(user.getTag(), user1.getVersion()); assertNull("Password should not be sent to a data consumer", user.getPassword()); } |
UserResource { @RolesAllowed({"admin"}) @POST public User createUser(User user) throws IOException { final com.dremio.service.users.User userConfig = UserResource.addUser(of(user, Optional.empty()), user.getPassword(), userGroupService, namespaceService); return User.fromUser(userConfig); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); } | @Test public void testCreateUser() throws Exception { UserInfoRequest userInfo = new UserInfoRequest(null, "test_new_user", "test", "new user", "[email protected]", "0", "123some_password", null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH)) .buildPost(Entity.json(userInfo)), User.class); assertNotNull(savedUser.getId()); assertEquals(savedUser.getName(), userInfo.getName()); assertEquals(savedUser.getFirstName(), userInfo.getFirstName()); assertEquals(savedUser.getLastName(), userInfo.getLastName()); assertEquals(savedUser.getEmail(), userInfo.getEmail()); assertNull("Password should not be sent to a data consumer", savedUser.getPassword()); assertNotNull(savedUser.getTag()); final UserService userService = l(UserService.class); userService.deleteUser(savedUser.getName(), savedUser.getTag()); } |
UserResource { @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") public User updateUser(User user, @PathParam("id") String id) throws UserNotFoundException, IOException, DACUnauthorizedException { if (Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("No user id provided"); } final com.dremio.service.users.User savedUser = userGroupService.getUser(new UID(id)); if (!securityContext.isUserInRole("admin") && !securityContext.getUserPrincipal().getName().equals(savedUser.getUserName())) { throw new DACUnauthorizedException(format("User %s is not allowed to update user %s", securityContext.getUserPrincipal().getName(), savedUser.getUserName())); } if (!savedUser.getUserName().equals(user.getName())) { throw new NotSupportedException("Changing of user name is not supported"); } final com.dremio.service.users.User userConfig = userGroupService.updateUser(of(user, Optional.of(id)), user.getPassword()); return User.fromUser(userConfig); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); } | @Test public void testUpdateUser() { UserInfoRequest userInfo = new UserInfoRequest(createdUser.getUID().getId(), createdUser.getUserName(), "a new firstName", " a new last name", "[email protected]", createdUser.getVersion(), null, null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(createdUser.getUID().getId())) .buildPut(Entity.json(userInfo)), User.class); assertEquals(createdUser.getUID().getId(), savedUser.getId()); assertEquals(savedUser.getName(), userInfo.getName()); assertEquals(savedUser.getFirstName(), userInfo.getFirstName()); assertEquals(savedUser.getLastName(), userInfo.getLastName()); assertEquals(savedUser.getEmail(), userInfo.getEmail()); assertNotEquals("version should be changed", savedUser.getTag(), userInfo.getTag()); assertNull("Password should not be sent to a data consumer", savedUser.getPassword()); createdUser = SimpleUser.newBuilder() .setUID(new UID(savedUser.getId())) .setUserName(savedUser.getName()) .setVersion(savedUser.getTag()).build(); } |
UserResource { @GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); } | @Test public void testGetUserByName() throws Exception { final UserService userService = l(UserService.class); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path("by-name").path(createdUser.getUserName())).buildGet(), User.class); assertEquals(user.getId(), createdUser.getUID().getId()); assertEquals(user.getName(), createdUser.getUserName()); } |
UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetEdition() { UserStats.Builder stats = new UserStats.Builder(); stats.setEdition("oss"); String expected = "dremio-oss-" + DremioVersionInfo.getVersion(); assertEquals(expected, stats.build().getEdition()); } |
UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByDate() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusDays(11)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); UserStats stats = statsBuilder.build(); List<Map<String, Object>> statsByDate = stats.getUserStatsByDate(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("date", now.minusDays(9).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("date", now.toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByWeek() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(3)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); UserStats stats = statsBuilder.build(); List<Map<String, Object>> statsByDate = stats.getUserStatsByWeek(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("week", getLastSundayDate(now.minusWeeks(1)).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("week", getLastSundayDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); } | @Test public void testGetStatsByMonth() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); List<Map<String, Object>> statsByDate = statsBuilder.build().getUserStatsByMonth(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("month", getMonthStartDate(now.minusMonths(1)).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("month", getMonthStartDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
MediaTypeFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { final UriInfo info = requestContext.getUriInfo(); MultivaluedMap<String, String> parameters = info.getQueryParameters(); String format = parameters.getFirst("format"); if (format == null) { return; } requestContext.getHeaders().putSingle(HttpHeaders.ACCEPT, format); } @Override void filter(ContainerRequestContext requestContext); } | @Test public void testHeaderChange() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("unit", "test"), request.getAcceptableMediaTypes().get(0)); }
@Test public void testHeaderIsUntouched() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("random", "media"), request.getAcceptableMediaTypes().get(0)); } |
ClasspathHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { logger.debug("Checking jars {}", necessaryJarFoldersSet.size()); for(String jarFolderPath : necessaryJarFoldersSet) { File jarFolder = new File(jarFolderPath); boolean folderAccessible = false; try { folderAccessible = Files.isExecutable(jarFolder.toPath()); } catch (SecurityException se) { logger.error("SecurityException while checking folder: {}", jarFolderPath, se); } if (!folderAccessible) { logger.error("Jar: {} does not exist or it is not readable!", jarFolderPath); return false; } } logger.debug("All necessary jars exist and are readable."); return true; } ClasspathHealthMonitor(); ClasspathHealthMonitor(Set<String> classpath); @Override boolean isHealthy(); } | @Test public void testIsHealthy() { assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(false); assertFalse(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(true); assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).delete(); assertFalse(classpathHealthMonitor.isHealthy()); } |
JSONJobDataFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (!APPLICATION_JSON_TYPE.equals(responseContext.getMediaType()) || !WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_SUPPORTED_VALUE .equals(requestContext.getHeaderString(WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS))) { return; } ObjectWriterInjector.set(new NumberAsStringWriter(ObjectWriterInjector.getAndClear())); } @Override void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext); } | @Test public void testJSONGeneratorUntouched() throws IOException { JSONJobDataFilter filter = new JSONJobDataFilter(); ContainerRequestBuilder request = ContainerRequestBuilder.from("http: if (testData.getHeaderKey() != null) { request.header(testData.getHeaderKey(), testData.getHeaderValue()); } ContainerResponse response = new ContainerResponse(request.build(), Response.ok().type(testData.getMediaType()).build()); filter.filter(request.build(), response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); if (testData.isExpectedToBeTouched()) { assertNotNull(modifier); ObjectWriter writer = mock(ObjectWriter.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), writer, mock(JsonGenerator.class)); verify(writer).withAttribute(DataJsonOutput.DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_ATTRIBUTE, true); } else { assertNull(modifier); } } |
JSONPrettyPrintFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } ObjectWriterInjector.set(new PrettyPrintWriter(ObjectWriterInjector.getAndClear())); } @Override void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext); } | @Test public void testJSONGeneratorConfigured() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNotNull(modifier); JsonGenerator g = mock(JsonGenerator.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), mock(ObjectWriter.class), g); verify(g).useDefaultPrettyPrinter(); }
@Test public void testJSONGeneratorUntouched() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNull(modifier); } |
Doc { void generateDoc(String linkPrefix, PrintStream out) throws JsonMappingException, JsonProcessingException { Set<Class<?>> classes = new TreeSet<>(new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { return o1.getName().compareTo(o2.getName()); } }); classes.addAll(this.classes); for (Class<?> c : classes) { Provider provider = c.getAnnotation(Provider.class); if (provider != null) { ProviderClass providerClass = new ProviderClass(c); providers.add(providerClass); } else if (ContainerResponseFilter.class.isAssignableFrom(c)) { others.add(c); } else if (ContainerRequestFilter.class.isAssignableFrom(c)) { others.add(c); } else if (MessageBodyReader.class.isAssignableFrom(c)) { others.add(c); } else if (MessageBodyWriter.class.isAssignableFrom(c)) { others.add(c); } else if (Feature.class.isAssignableFrom(c)) { others.add(c); } else if (ExceptionMapper.class.isAssignableFrom(c)) { others.add(c); } else if (RolesAllowedDynamicFeature.class.isAssignableFrom(c)) { others.add(c); } else { Resources resources = new Resources(c); roots.add(resources); } } Collections.sort(roots, new Comparator<Resources>() { @Override public int compare(Resources o1, Resources o2) { if (o1.basePath == null && o2.basePath == null) { return 0; } else if (o1.basePath == null) { return -1; } else if (o2.basePath == null) { return 1; } return o1.basePath.value().compareTo(o2.basePath.value()); } }); out.println("# TOC"); out.println(" - [Resources](#"+linkPrefix.toLowerCase()+"-resources)"); out.println(" - [JobData](#"+linkPrefix.toLowerCase()+"-data)"); out.println(" - [Others](#"+linkPrefix.toLowerCase()+"-others)"); out.println(); out.println("#"+linkPrefix+" Resources: "); for (Resources resources : roots) { out.println(resources); out.println(); } out.println(); ObjectMapper om = JSONUtil.prettyMapper(); om.enable(SerializationFeature.INDENT_OUTPUT); out.println("#"+linkPrefix+" JobData"); for (final Class<?> type : rawDataTypes) { out.println("## `" + type + "`"); try { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); om.acceptJsonFormatVisitor(om.constructType(type), visitor); JsonSchema schema = visitor.finalSchema(); out.println("- Example:"); out.println("```"); out.println(example(schema)); out.println("```"); } catch (RuntimeException e) { throw new RuntimeException("Error generating schema for " + type, e); } out.println(); } out.println(); out.println("#"+linkPrefix+" Others: "); for (Class<?> other : others) { out.println("## " + other); } } Doc(Collection<? extends Class<?>> classes); static void main(String[] args); } | @Test public void test() throws Exception { Doc docv2 = new Doc(asList(DatasetVersionResource.class)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); docv2.generateDoc("V2", out); assertTrue(baos.toString(), baos.toString().contains(DatasetVersionResource.class.getName())); } |
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet) { if (hostProcessingRateSet == null || hostProcessingRateSet.isEmpty()) { return new TreeSet<>(); } Table<String, String, BigInteger> hostToColumnToValueTable = HashBasedTable.create(); buildPhaseHostMetrics(major, hostProcessingRateSet, hostToColumnToValueTable); return constructHostProcessingRateSet(major, hostToColumnToValueTable); } static BigDecimal computeRecordProcessingRate(BigInteger maxRecords, BigInteger processNanos); static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major,
List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops,
Table<Integer, Integer, String> majorMinorHostTable); static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet); } | @Test public void testComputeRecordProcRateAtPhaseHostLevel() { int major = 1; String hostname1 = "hostname1"; String hostname2 = "hostname2"; HostProcessingRate hpr1 = new HostProcessingRate(major, hostname1, BigInteger.valueOf(5), BigInteger.valueOf(5_000_000_000L), BigInteger.valueOf(1)); HostProcessingRate hpr2 = new HostProcessingRate(major, hostname1, BigInteger.valueOf(40), BigInteger.valueOf(10_000_000_000L), BigInteger.valueOf(2)); HostProcessingRate hpr3 = new HostProcessingRate(major, hostname2, BigInteger.valueOf(80), BigInteger.valueOf(20_000_000_000L), BigInteger.valueOf(3)); HostProcessingRate hpr4 = new HostProcessingRate(major+1, hostname1, BigInteger.valueOf(70), BigInteger.valueOf(20), BigInteger.valueOf(3)); Set<HostProcessingRate> unAggregatedHostProcessingRate = Sets.newHashSet(hpr1, hpr2, hpr3, hpr4); Map<String, BigDecimal> expectedRecordProcRate = new HashMap<>(); expectedRecordProcRate.put(hostname1, BigDecimal.valueOf(3)); expectedRecordProcRate.put(hostname2, BigDecimal.valueOf(4)); Map<String, BigInteger> expectedNumThreads = new HashMap<>(); expectedNumThreads.put(hostname1, BigInteger.valueOf(3)); expectedNumThreads.put(hostname2, BigInteger.valueOf(3)); Set<HostProcessingRate> aggregatedHostProcessingRate = HostProcessingRateUtil .computeRecordProcRateAtPhaseHostLevel(major,unAggregatedHostProcessingRate); verifyAggreatedRecordProcessingRates(major, expectedRecordProcRate, expectedNumThreads, aggregatedHostProcessingRate); } |
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major, List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops, Table<Integer, Integer, String> majorMinorHostTable) { Table<String, String, BigInteger> hostToColumnToValueTable = HashBasedTable.create(); buildOperatorHostMetrics(major, ops, majorMinorHostTable, hostToColumnToValueTable); return constructHostProcessingRateSet(major, hostToColumnToValueTable); } static BigDecimal computeRecordProcessingRate(BigInteger maxRecords, BigInteger processNanos); static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major,
List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops,
Table<Integer, Integer, String> majorMinorHostTable); static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet); } | @Test public void testComputeRecordProcRateAtPhaseOperatorHostLevel() { int major = 1; int minor1 = 1; int minor2 = 2; int minor3 = 3; String hostname1 = "hostname1"; String hostname2 = "hostname2"; Table<Integer, Integer, String> majorMinorHostTable = HashBasedTable.create(); majorMinorHostTable.put(major, minor1, hostname1); majorMinorHostTable.put(major, minor2, hostname2); majorMinorHostTable.put(major, minor3, hostname1); StreamProfile streamProfile1 = StreamProfile.newBuilder().setRecords(40).build(); StreamProfile streamProfile2 = StreamProfile.newBuilder().setRecords(20).build(); StreamProfile streamProfile3 = StreamProfile.newBuilder().setRecords(60).build(); OperatorProfile op1 = OperatorProfile.newBuilder().addInputProfile(streamProfile1) .setProcessNanos(10_000_000_000L).build(); OperatorProfile op2 = OperatorProfile.newBuilder().addInputProfile(streamProfile2) .setProcessNanos(20_000_000_000L).build(); OperatorProfile op3 = OperatorProfile.newBuilder().addInputProfile(streamProfile3) .setProcessNanos(30_000_000_000L).build(); ImmutablePair<OperatorProfile, Integer> ip1 = ImmutablePair.of(op1, minor1); ImmutablePair<OperatorProfile, Integer> ip2 = ImmutablePair.of(op2, minor2); ImmutablePair<OperatorProfile, Integer> ip3 = ImmutablePair.of(op3, minor3); List<ImmutablePair<OperatorProfile, Integer>> ops = Lists.newArrayList(ip1, ip2, ip3); Map<String, BigDecimal> expectedRecordProcRate = new HashMap<>(); expectedRecordProcRate.put(hostname1, BigDecimal.valueOf(2.5)); expectedRecordProcRate.put(hostname2, BigDecimal.valueOf(1)); Map<String, BigInteger> expectedNumThreads = new HashMap<>(); expectedNumThreads.put(hostname1, BigInteger.valueOf(2)); expectedNumThreads.put(hostname2, BigInteger.valueOf(1)); Set<HostProcessingRate> aggregatedHostProcessingRate = computeRecordProcRateAtPhaseOperatorHostLevel(major, ops, majorMinorHostTable); verifyAggreatedRecordProcessingRates(major, expectedRecordProcRate, expectedNumThreads, aggregatedHostProcessingRate); } |
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); } OperatorWrapper(int major,
List<ImmutablePair<OperatorProfile, Integer>> ops,
CoreOperatorTypeMetricsMap coreOperatorTypeMetricsMap,
Table<Integer, Integer, String> majorMinorHostTable,
Set<HostProcessingRate> hostProcessingRateSet); String getDisplayName(); String getId(); void addSummary(TableBuilder tb); void addOperator(JsonGenerator generator); void addInfo(JsonGenerator generator); void addMetrics(JsonGenerator generator); void addDetails(JsonGenerator generator); static final String[] OPERATOR_COLUMNS; static final String[] OPERATORS_OVERVIEW_COLUMNS; static final String[] SPLIT_INFO_COLUMNS; static final String[] HOST_METRICS_COLUMNS; static final String[] SLOW_IO_INFO_COLUMNS; } | @Test public void testGetMetricsTableHandlesNotRegisteredMetrics() throws IOException { OperatorProfile op = OperatorProfile .newBuilder().addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(1) .setDoubleValue(200)) .addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(3) .setDoubleValue(21)) .setOperatorId(UserBitShared.CoreOperatorType.PARQUET_ROW_GROUP_SCAN.getNumber()) .build(); ImmutablePair<OperatorProfile, Integer> pair = new ImmutablePair<>(op, 1); OperatorWrapper ow = new OperatorWrapper(1, ImmutableList.of(pair), OperatorMetricRegistry.getCoreOperatorTypeMetricsMap(), HashBasedTable.create(), new HashSet<>()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputStream); jsonGenerator.writeStartObject(); ow.addMetrics(jsonGenerator); jsonGenerator.writeEndObject(); jsonGenerator.flush(); final JsonElement element = new JsonParser().parse(outputStream.toString()); final int size = element.getAsJsonObject().get("metrics").getAsJsonObject().get("data").getAsJsonArray().get(0).getAsJsonArray().size(); assertEquals(2, size); } |
SimpleDurationFormat { static String formatNanos(long durationInNanos) { if (durationInNanos < 1) { return "0s"; } final long days = TimeUnit.NANOSECONDS.toDays(durationInNanos); final long hours = TimeUnit.NANOSECONDS.toHours(durationInNanos) - TimeUnit.DAYS.toHours(TimeUnit.NANOSECONDS.toDays(durationInNanos)); final long minutes = TimeUnit.NANOSECONDS.toMinutes(durationInNanos) - TimeUnit.HOURS.toMinutes(TimeUnit.NANOSECONDS.toHours(durationInNanos)); final long seconds = TimeUnit.NANOSECONDS.toSeconds(durationInNanos) - TimeUnit.MINUTES.toSeconds(TimeUnit.NANOSECONDS.toMinutes(durationInNanos)); final long milliSeconds = TimeUnit.NANOSECONDS.toMillis(durationInNanos) - TimeUnit.SECONDS.toMillis(TimeUnit.NANOSECONDS.toSeconds(durationInNanos)); final long microSeconds = TimeUnit.NANOSECONDS.toMicros(durationInNanos) - TimeUnit.MILLISECONDS.toMicros(TimeUnit.NANOSECONDS.toMillis(durationInNanos)); final long nanoSeconds = durationInNanos - TimeUnit.MICROSECONDS.toNanos(TimeUnit.NANOSECONDS.toMicros(durationInNanos)); if (days >= 1) { return days + "d" + hours + "h" + minutes + "m"; } else if (hours >= 1) { return hours + "h" + minutes + "m"; } else if (minutes >= 1) { return minutes + "m" + seconds + "s"; } else if (seconds >= 1) { return String.format("%.3fs", seconds + milliSeconds/1000.0); } else if (milliSeconds >= 1) { return milliSeconds + "ms"; } else if (microSeconds >= 1) { return microSeconds + "us"; } else { return nanoSeconds + "ns"; } } } | @Test public void testFormatNanos() { assertEquals("123us", SimpleDurationFormat.formatNanos(123456)); assertEquals("456ns", SimpleDurationFormat.formatNanos(456)); assertEquals("825ms", SimpleDurationFormat.formatNanos(825435267)); assertEquals("1.825s", SimpleDurationFormat.formatNanos(1825435267)); assertEquals("30m45s", SimpleDurationFormat.formatNanos(1845825435267L)); assertEquals("1h20m", SimpleDurationFormat.formatNanos(4845825435267L)); } |
JobResultToLogEntryConverter implements Function<Job, LoggedQuery> { @Override public LoggedQuery apply(Job job) { final JobInfo info = job.getJobAttempt().getInfo(); final List<String> contextList = info.getContextList(); String outcomeReason = null; switch(job.getJobAttempt().getState()) { case CANCELED: outcomeReason = info.getCancellationInfo().getMessage(); break; case FAILED: outcomeReason = info.getFailureInfo(); break; default: break; } return new LoggedQuery( job.getJobId().getId(), contextList == null ? null : contextList.toString(), info.getSql(), info.getStartTime(), info.getFinishTime(), job.getJobAttempt().getState(), outcomeReason, info.getUser() ); } @Override LoggedQuery apply(Job job); } | @Test public void testOutcomeReasonCancelled() throws Exception { JobResultToLogEntryConverter converter = new JobResultToLogEntryConverter(); Job job = mock(Job.class); JobAttempt jobAttempt = new JobAttempt(); JobInfo jobInfo = new JobInfo(); JobId jobId = new JobId(); jobId.setId("testId"); final String cancelReason = "this is the cancel reason"; JobCancellationInfo jobCancellationInfo = new JobCancellationInfo(); jobCancellationInfo.setMessage(cancelReason); when(job.getJobId()).thenReturn(jobId); jobAttempt.setState(JobState.CANCELED); jobAttempt.setInfo(jobInfo); jobInfo.setCancellationInfo(jobCancellationInfo); when(job.getJobAttempt()).thenReturn(jobAttempt); assertEquals(cancelReason, converter.apply(job).getOutcomeReason()); }
@Test public void testOutcomeReasonFailed() throws Exception { JobResultToLogEntryConverter converter = new JobResultToLogEntryConverter(); Job job = mock(Job.class); JobAttempt jobAttempt = new JobAttempt(); JobInfo jobInfo = new JobInfo(); JobId jobId = new JobId(); jobId.setId("testId"); final String failureReason = "this is the failure reason"; when(job.getJobId()).thenReturn(jobId); jobAttempt.setState(JobState.FAILED); jobAttempt.setInfo(jobInfo); jobInfo.setFailureInfo(failureReason); when(job.getJobAttempt()).thenReturn(jobAttempt); assertEquals(failureReason, converter.apply(job).getOutcomeReason()); } |
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } } private JobsProtoUtil(); static JobAttempt getLastAttempt(com.dremio.service.job.JobDetails jobDetails); static JobProtobuf.JobAttempt toBuf(JobAttempt attempt); static JobAttempt toStuff(JobProtobuf.JobAttempt attempt); static JobProtobuf.JobId toBuf(JobId jobId); static DatasetCommonProtobuf.ViewFieldType toBuf(ViewFieldType viewFieldType); static List<DatasetCommonProtobuf.ViewFieldType> toBuf(List<ViewFieldType> viewFieldTypes); static ViewFieldType toStuff(DatasetCommonProtobuf.ViewFieldType viewFieldType); static List<ViewFieldType> toStuff(List<DatasetCommonProtobuf.ViewFieldType> fieldTypes); static JobId toStuff(JobProtobuf.JobId jobId); static JobProtobuf.JobFailureInfo toBuf(JobFailureInfo jobFailureInfo); static JobFailureInfo toStuff(JobProtobuf.JobFailureInfo jobFailureInfo); static JobResult toStuff(JobProtobuf.JobResult jobResult); static QueryMetadata toBuf(com.dremio.service.jobs.metadata.QueryMetadata queryMetadata); static JobCancellationInfo toStuff(JobProtobuf.JobCancellationInfo jobCancellationInfo); static JobProtobuf.MaterializationSummary toBuf(MaterializationSummary materializationSummary); static com.dremio.service.job.JobState toBuf(JobState jobState); static com.dremio.service.job.AttemptEvent.State toBuf(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.UserBitShared.AttemptEvent.State toBuf2(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.service.job.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.exec.proto.UserBitShared.AttemptEvent.State attemptState); static List<AttemptEvent> toStuff2(List<com.dremio.exec.proto.beans.AttemptEvent> stateList); static JobState toStuff(com.dremio.service.job.JobState jobState); static com.dremio.service.job.QueryType toBuf(com.dremio.service.job.proto.QueryType queryType); static com.dremio.service.job.RequestType toBuf(RequestType requestType); static RequestType toStuff(com.dremio.service.job.RequestType requestType); static DatasetType toStuff(DatasetCommonProtobuf.DatasetType datasetType); static SearchTypes.SortOrder toStoreSortOrder(SearchJobsRequest.SortOrder order); static com.dremio.exec.work.user.SubstitutionSettings toPojo(SubstitutionSettings substitutionSettings); static SubstitutionSettings toBuf(com.dremio.exec.work.user.SubstitutionSettings substitutionSettings); static com.dremio.service.job.proto.QueryType toStuff(QueryType queryType); static MaterializationSummary toStuff(JobProtobuf.MaterializationSummary materializationSummary); static SqlQuery toBuf(com.dremio.service.jobs.SqlQuery sqlQuery); } | @Test public void testToBuf() { JobProtobuf.JobAttempt resultJobAttempt = toBuf(jobAttemptProtostuff); assertEquals(resultJobAttempt, jobAttemptProtobuf); JobProtobuf.JobFailureInfo jobFailureInfo = toBuf(jobFailureInfoProtoStuff); assertEquals(jobFailureInfoProtoBuf, jobFailureInfo); JobProtobuf.JobCancellationInfo jobCancellationInfo = toBuf(jobCancellationInfoProtoStuff); assertNotEquals(jobCancellationInfoProtobuf, jobCancellationInfo); } |
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> T toStuff(Schema<T> protostuffSchema, M protobuf) { T message = protostuffSchema.newMessage(); ProtobufIOUtil.mergeFrom(protobuf.toByteArray(), message, protostuffSchema); return message; } private JobsProtoUtil(); static JobAttempt getLastAttempt(com.dremio.service.job.JobDetails jobDetails); static JobProtobuf.JobAttempt toBuf(JobAttempt attempt); static JobAttempt toStuff(JobProtobuf.JobAttempt attempt); static JobProtobuf.JobId toBuf(JobId jobId); static DatasetCommonProtobuf.ViewFieldType toBuf(ViewFieldType viewFieldType); static List<DatasetCommonProtobuf.ViewFieldType> toBuf(List<ViewFieldType> viewFieldTypes); static ViewFieldType toStuff(DatasetCommonProtobuf.ViewFieldType viewFieldType); static List<ViewFieldType> toStuff(List<DatasetCommonProtobuf.ViewFieldType> fieldTypes); static JobId toStuff(JobProtobuf.JobId jobId); static JobProtobuf.JobFailureInfo toBuf(JobFailureInfo jobFailureInfo); static JobFailureInfo toStuff(JobProtobuf.JobFailureInfo jobFailureInfo); static JobResult toStuff(JobProtobuf.JobResult jobResult); static QueryMetadata toBuf(com.dremio.service.jobs.metadata.QueryMetadata queryMetadata); static JobCancellationInfo toStuff(JobProtobuf.JobCancellationInfo jobCancellationInfo); static JobProtobuf.MaterializationSummary toBuf(MaterializationSummary materializationSummary); static com.dremio.service.job.JobState toBuf(JobState jobState); static com.dremio.service.job.AttemptEvent.State toBuf(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.UserBitShared.AttemptEvent.State toBuf2(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.service.job.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.exec.proto.UserBitShared.AttemptEvent.State attemptState); static List<AttemptEvent> toStuff2(List<com.dremio.exec.proto.beans.AttemptEvent> stateList); static JobState toStuff(com.dremio.service.job.JobState jobState); static com.dremio.service.job.QueryType toBuf(com.dremio.service.job.proto.QueryType queryType); static com.dremio.service.job.RequestType toBuf(RequestType requestType); static RequestType toStuff(com.dremio.service.job.RequestType requestType); static DatasetType toStuff(DatasetCommonProtobuf.DatasetType datasetType); static SearchTypes.SortOrder toStoreSortOrder(SearchJobsRequest.SortOrder order); static com.dremio.exec.work.user.SubstitutionSettings toPojo(SubstitutionSettings substitutionSettings); static SubstitutionSettings toBuf(com.dremio.exec.work.user.SubstitutionSettings substitutionSettings); static com.dremio.service.job.proto.QueryType toStuff(QueryType queryType); static MaterializationSummary toStuff(JobProtobuf.MaterializationSummary materializationSummary); static SqlQuery toBuf(com.dremio.service.jobs.SqlQuery sqlQuery); } | @Test public void testToStuff() { JobAttempt resultJobAttempt = toStuff(jobAttemptProtobuf); assertEquals(resultJobAttempt, jobAttemptProtostuff); JobFailureInfo jobFailureInfo = toStuff(jobFailureInfoProtoBuf); assertEquals(jobFailureInfoProtoStuff, jobFailureInfo); JobCancellationInfo jobCancellationInfo = toStuff(jobCancellationInfoProtobuf); assertNotEquals(jobCancellationInfoProtoStuff, jobCancellationInfo); } |
DatasetConfigUpgrade extends UpgradeTask implements LegacyUpgradeTask { @VisibleForTesting byte[] convertFromOldSchema(OldSchema oldSchema) { FlatBufferBuilder builder = new FlatBufferBuilder(); int[] fieldOffsets = new int[oldSchema.fieldsLength()]; for (int i = 0; i < oldSchema.fieldsLength(); i++) { fieldOffsets[i] = convertFromOldField(oldSchema.fields(i), builder); } int fieldsOffset = org.apache.arrow.flatbuf.Schema.createFieldsVector(builder, fieldOffsets); int[] metadataOffsets = new int[oldSchema.customMetadataLength()]; for (int i = 0; i < metadataOffsets.length; i++) { int keyOffset = builder.createString(oldSchema.customMetadata(i).key()); int valueOffset = builder.createString(oldSchema.customMetadata(i).value()); KeyValue.startKeyValue(builder); KeyValue.addKey(builder, keyOffset); KeyValue.addValue(builder, valueOffset); metadataOffsets[i] = KeyValue.endKeyValue(builder); } int metadataOffset = org.apache.arrow.flatbuf.Field.createCustomMetadataVector(builder, metadataOffsets); org.apache.arrow.flatbuf.Schema.startSchema(builder); org.apache.arrow.flatbuf.Schema.addFields(builder, fieldsOffset); org.apache.arrow.flatbuf.Schema.addCustomMetadata(builder, metadataOffset); builder.finish(org.apache.arrow.flatbuf.Schema.endSchema(builder)); return builder.sizedByteArray(); } DatasetConfigUpgrade(); @Override Version getMaxVersion(); @Override String getTaskUUID(); @Override void upgrade(UpgradeContext context); @Override String toString(); } | @Test public void testArrowSchemaConversion() { byte[] schema = Base64.getDecoder().decode(OLD_SCHEMA); try { BatchSchema.deserialize(schema); fail("Should not be able to process old Schema"); } catch (IndexOutOfBoundsException e) { } ByteString schemaBytes = ByteString.copyFrom(schema); DatasetConfigUpgrade datasetConfigUpgrade = new DatasetConfigUpgrade(); OldSchema oldSchema = OldSchema.getRootAsOldSchema(schemaBytes.asReadOnlyByteBuffer()); byte[] newschemaBytes = datasetConfigUpgrade.convertFromOldSchema(oldSchema); BatchSchema batchSchema = BatchSchema.deserialize(newschemaBytes); int fieldCount = batchSchema.getFieldCount(); assertEquals(4, fieldCount); List<String> expected = ImmutableList.of( "R_REGIONKEY", "R_NAME", "R_COMMENT", "$_dremio_$_update_$"); List<String> actual = Lists.newArrayList(); for (int i = 0; i < fieldCount; i++) { Field field = batchSchema.getColumn(i); actual.add(field.getName()); } assertTrue(Objects.equals(expected, actual)); } |
AttemptsHelper { public static long getLegacyEnqueuedTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final ResourceSchedulingInfo schedulingInfo = jobInfo.getResourceSchedulingInfo(); if (schedulingInfo == null) { return 0; } final Long schedulingStart = schedulingInfo.getResourceSchedulingStart(); Long schedulingEnd = schedulingInfo.getResourceSchedulingEnd(); if (schedulingStart == null || schedulingEnd == null) { return 0; } if (jobAttempt.getState() == JobState.ENQUEUED) { schedulingEnd = System.currentTimeMillis(); } else { schedulingEnd = Math.max(schedulingStart, schedulingEnd); } return schedulingEnd - schedulingStart; } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetEnqueuedTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED); assertTrue("Enqueued job has wrong enqueued time", AttemptsHelper.getLegacyEnqueuedTime(attempt) >= TimeUnit.HOURS.toMillis(3)); }
@Test public void testGetEnqueuedTimeFailedJob() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.FAILED); assertEquals(0L, AttemptsHelper.getLegacyEnqueuedTime(attempt)); } |
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetPlanningTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED) .setDetails(new JobDetails()); assertEquals(0L, AttemptsHelper.getLegacyPlanningTime(attempt)); }
@Test public void testPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getPlanningTime()); assertTrue(1L == attemptsHelper.getPlanningTime()); } |
AttemptsHelper { public static long getLegacyExecutionTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final JobDetails jobDetails = jobAttempt.getDetails(); if (jobDetails == null) { return 0; } final long startTime = Optional.ofNullable(jobInfo.getStartTime()).orElse(0L); final long finishTime = Optional.ofNullable(jobInfo.getFinishTime()).orElse(startTime); final long planningScheduling = Optional.ofNullable(jobDetails.getTimeSpentInPlanning()).orElse(0L); return finishTime - startTime - planningScheduling; } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetExecutionTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED) .setDetails(new JobDetails()); assertEquals(0L, AttemptsHelper.getLegacyExecutionTime(attempt)); } |
AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetPendingTime() { Preconditions.checkNotNull(attemptsHelper.getPendingTime()); assertTrue(1L == attemptsHelper.getPendingTime()); } |
AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetMetadataRetrievalTime() { Preconditions.checkNotNull(attemptsHelper.getMetadataRetrievalTime()); assertTrue(1L == attemptsHelper.getMetadataRetrievalTime()); } |
AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetEngineStartTime() { Preconditions.checkNotNull(attemptsHelper.getEngineStartTime()); assertTrue(1L == attemptsHelper.getEngineStartTime()); } |
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetQueuedTime() { Preconditions.checkNotNull(attemptsHelper.getQueuedTime()); assertTrue(1L == attemptsHelper.getQueuedTime()); } |
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetExecutionPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getExecutionPlanningTime()); assertTrue(1L == attemptsHelper.getExecutionPlanningTime()); } |
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); } | @Test public void testDependencySort() throws Exception { UpgradeTask1 upgradeTask1 = new UpgradeTask1(ImmutableList.of()); UpgradeTask2 upgradeTask2 = new UpgradeTask2(ImmutableList.of(upgradeTask1.getTaskUUID())); UpgradeTask3 upgradeTask3 = new UpgradeTask3(ImmutableList.of(upgradeTask1.getTaskUUID(), upgradeTask2.getTaskUUID())); UpgradeTask4 upgradeTask4 = new UpgradeTask4(ImmutableList.of(upgradeTask3.getTaskUUID())); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver( ImmutableList.of(upgradeTask1, upgradeTask2, upgradeTask3, upgradeTask4) ); List<UpgradeTask> sortedUpgradeTasks = upgradeTaskDependencyResolver.topologicalTasksSort(); assertThat(sortedUpgradeTasks, contains( instanceOf(UpgradeTask1.class), instanceOf(UpgradeTask2.class), instanceOf(UpgradeTask3.class), instanceOf(UpgradeTask4.class) )); }
@Test public void testDependencySortLargeTasksNumber() throws Exception { UpgradeTaskAny upgradeTaskAny1 = new UpgradeTaskAny("upgradeTaskAny1","5", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny2 = new UpgradeTaskAny("upgradeTaskAny2", "7", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny3 = new UpgradeTaskAny("upgradeTaskAny3","3", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny4 = new UpgradeTaskAny("upgradeTaskAny4", "11", ImmutableList.of(upgradeTaskAny1.getTaskUUID(), upgradeTaskAny2.getTaskUUID())); UpgradeTaskAny upgradeTaskAny5 = new UpgradeTaskAny("upgradeTaskAny5", "8", ImmutableList.of(upgradeTaskAny2.getTaskUUID(), upgradeTaskAny3.getTaskUUID())); UpgradeTaskAny upgradeTaskAny6 = new UpgradeTaskAny("upgradeTaskAny6","2", ImmutableList.of (upgradeTaskAny4.getTaskUUID())); UpgradeTaskAny upgradeTaskAny7 = new UpgradeTaskAny("upgradeTaskAny7","9", ImmutableList.of(upgradeTaskAny4.getTaskUUID(), upgradeTaskAny5.getTaskUUID())); UpgradeTaskAny upgradeTaskAny8 = new UpgradeTaskAny("upgradeTaskAny8", "10", ImmutableList.of(upgradeTaskAny4.getTaskUUID(), upgradeTaskAny3.getTaskUUID())); List<UpgradeTask> upgradeTasks = new ArrayList<>(); upgradeTasks.add(upgradeTaskAny1); upgradeTasks.add(upgradeTaskAny2); upgradeTasks.add(upgradeTaskAny3); upgradeTasks.add(upgradeTaskAny4); upgradeTasks.add(upgradeTaskAny5); upgradeTasks.add(upgradeTaskAny6); upgradeTasks.add(upgradeTaskAny7); upgradeTasks.add(upgradeTaskAny8); Collections.shuffle(upgradeTasks); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver(upgradeTasks); List<UpgradeTask> sortedUpgradeTasks = upgradeTaskDependencyResolver.topologicalTasksSort(); Map<String, Integer> nameToIndexMap = Maps.newHashMap(); int i = 0; for (UpgradeTask upgradeTask : sortedUpgradeTasks) { nameToIndexMap.put(upgradeTask.getDescription(), i); i++; } assertTrue(nameToIndexMap.get("upgradeTaskAny8") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny8") > nameToIndexMap.get("upgradeTaskAny3")); assertTrue(nameToIndexMap.get("upgradeTaskAny7") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny7") > nameToIndexMap.get("upgradeTaskAny5")); assertTrue(nameToIndexMap.get("upgradeTaskAny5") > nameToIndexMap.get("upgradeTaskAny2")); assertTrue(nameToIndexMap.get("upgradeTaskAny5") > nameToIndexMap.get("upgradeTaskAny3")); assertTrue(nameToIndexMap.get("upgradeTaskAny6") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny4") > nameToIndexMap.get("upgradeTaskAny1")); assertTrue(nameToIndexMap.get("upgradeTaskAny4") > nameToIndexMap.get("upgradeTaskAny2")); }
@Test public void detectLoopTest() throws Exception { UpgradeTask1 upgradeTask1 = new UpgradeTask1(ImmutableList.of()); UpgradeTask2 upgradeTask2 = new UpgradeTask2(ImmutableList.of("UpgradeTask4")); UpgradeTask3 upgradeTask3 = new UpgradeTask3(ImmutableList.of(upgradeTask1.getTaskUUID(), upgradeTask2.getTaskUUID())); UpgradeTask4 upgradeTask4 = new UpgradeTask4(ImmutableList.of(upgradeTask3.getTaskUUID())); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver( ImmutableList.of(upgradeTask1, upgradeTask2, upgradeTask3, upgradeTask4) ); thrown.expect(IllegalStateException.class); thrown.expectMessage("Dependencies loop detected: UpgradeTask2"); upgradeTaskDependencyResolver.topologicalTasksSort(); } |
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetStartingTime() { Preconditions.checkNotNull(attemptsHelper.getStartingTime()); assertTrue(1L == attemptsHelper.getStartingTime()); } |
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); } | @Test public void testGetRunningTime() { Preconditions.checkNotNull(attemptsHelper.getRunningTime()); assertTrue(1L == attemptsHelper.getRunningTime()); } |
SimpleUserService implements UserService { @Override public Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order, Integer limit) throws IOException { limit = limit == null ? 10000 : limit; if (searchTerm == null || searchTerm.isEmpty()) { return getAllUsers(limit); } final SearchQuery query = SearchQueryUtils.or( SearchQueryUtils.newContainsTerm(UserIndexKeys.NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.FIRST_NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.LAST_NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.EMAIL, searchTerm)); final LegacyFindByCondition conditon = new LegacyFindByCondition() .setCondition(query) .setLimit(limit) .addSorting(buildSorter(sortColumn, order)); return Lists.transform(Lists.newArrayList(KVUtil.values(userStore.find(conditon))), infoConfigTransformer); } @Inject SimpleUserService(Provider<LegacyKVStoreProvider> kvStoreProvider); @Override User getUser(String userName); @Override User getUser(UID uid); @Override User createUser(final User userConfig, final String authKey); @Override User updateUser(final User userGroup, final String authKey); @Override User updateUserName(final String oldUserName, final String newUserName, final User userGroup, final String authKey); @Override void authenticate(String userName, String password); @Override Iterable<? extends User> getAllUsers(Integer limit); @Override boolean hasAnyUser(); @Override Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order,
Integer limit); @Override void deleteUser(final String userName, String version); void setPassword(String userName, String password); @VisibleForTesting static void validatePassword(String input); @VisibleForTesting
static final String USER_STORE; } | @Test public void testSearch() throws Exception { try(final LegacyKVStoreProvider kvstore = LegacyKVStoreProviderAdapter.inMemory(DremioTest.CLASSPATH_SCAN_RESULT)) { kvstore.start(); final SimpleUserService userGroupService = new SimpleUserService(() -> kvstore); initUserStore(kvstore, userGroupService); assertEquals(2, Iterables.size(userGroupService.searchUsers("David", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("Johnson", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("Mark", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("avi", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("k.j", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("@dremio", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("rkda", null, null, null))); assertEquals(3, Iterables.size(userGroupService.searchUsers("a", null, null, null))); } } |
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); } | @Test public void testCombine() { CoordExecRPC.QueryProgressMetrics metrics1 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(100) .build(); CoordExecRPC.QueryProgressMetrics metrics2 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(120) .build(); assertEquals(0, MetricsCombiner.combine(Stream.empty()).getRowsProcessed()); assertEquals(100, MetricsCombiner.combine(Stream.of(metrics1)).getRowsProcessed()); assertEquals(220, MetricsCombiner.combine(Stream.of(metrics1, metrics2)).getRowsProcessed()); } |
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile,
Stream<ExecutorQueryProfile> executorProfiles); } | @Test public void testMergeWithOnlyPlanningProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.COMPLETED) .addStateList(AttemptEvent.newBuilder() .setState(State.COMPLETED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = planningProfile.toBuilder() .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.empty())); }
@Test public void testMergeWithOnlyPlanningAndTailProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile tailProfile = UserBitShared.QueryProfile.newBuilder() .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, tailProfile, Stream.empty())); }
@Test public void testMergeWithOnlyPlanningAndExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); }
@Test public void testMergeWithOnlyThreeParts() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .build(); final UserBitShared.QueryProfile tailProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, tailProfile, Stream.of(executorQueryProfile))); }
@Test public void testMergeWithMultipleExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint1 = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.66") .build(); final CoordinationProtos.NodeEndpoint nodeEndPoint2 = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.67") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus node1Phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(10) .build(); CoordExecRPC.NodePhaseStatus node1Phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(11) .build(); CoordExecRPC.FragmentStatus node1Frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(116) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus node1Frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(117).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile1 = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(node1Phase0) .addPhaseStatus(node1Phase1) .build() ) .addFragments(node1Frag0) .addFragments(node1Frag1) .build(); CoordExecRPC.NodePhaseStatus node2Phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.NodePhaseStatus node2Phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(21) .build(); CoordExecRPC.FragmentStatus node2Frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus node2Frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(217).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile2 = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666667) .setTimeEnqueuedBeforeSubmitMs(3) .addPhaseStatus(node2Phase0) .addPhaseStatus(node2Phase1) .build() ) .addFragments(node2Frag0) .addFragments(node2Frag1) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(666667) .setTimeEnqueuedBeforeSubmitMs(3) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(node1Phase0.getMaxMemoryUsed()) .build() ) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(node2Phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(node1Frag0.getProfile()) .addMinorFragmentProfile(node2Frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(node1Phase1.getMaxMemoryUsed()) .build() ) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(node2Phase1.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(node1Frag1.getProfile()) .addMinorFragmentProfile(node2Frag1.getProfile()) .build() ) .setTotalFragments(4) .setFinishedFragments(2) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile1, executorQueryProfile2))); }
@Test public void testFragmentCountFromPlanningProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.COMPLETED) .setTotalFragments(5) .build(); final UserBitShared.QueryProfile expectedMergedProfile = planningProfile.toBuilder() .setTotalFragments(5) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.empty())); }
@Test public void testMergeWithInconsistentExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.FragmentStatus frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(phase0) .build() ) .addFragments(frag0) .addFragments(frag1) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addMinorFragmentProfile(frag1.getProfile()) .build() ) .setTotalFragments(2) .setFinishedFragments(2) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); }
@Test public void testMergeWithInconsistentExecutorProfiles2() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.NodePhaseStatus phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(30) .build(); CoordExecRPC.FragmentStatus frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(phase0) .addPhaseStatus(phase1) .build() ) .addFragments(frag0) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase1.getMaxMemoryUsed()) .build() ) .build() ) .setTotalFragments(1) .setFinishedFragments(1) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); } |
ReconnectingConnection implements Closeable { public <R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> void runCommand(C cmd) { if (closed.get()) { cmd.connectionFailed(FailureType.CONNECTION, new IOException("Connection has been closed: " + toString())); } ConnectionRunner r = new ConnectionRunner(); connector.execute(r); r.executeCommand(cmd); } ReconnectingConnection(String name, OUTBOUND_HANDSHAKE handshake, String host, int port); ReconnectingConnection(String name, OUTBOUND_HANDSHAKE handshake, String host, int port, long lostConnectionReattemptMS, long connectionSuccessTimeoutMS, long timeBetweenAttemptMS); void runCommand(C cmd); CloseHandlerCreator getCloseHandlerCreator(); void addExternalConnection(CONNECTION_TYPE connection); @Override void close(); String toString(); } | @Test public void ensureDirectFailureOnRpcException() { conn().runCommand(Cmd.expectFail()); }
@Test public void ensureSecondSuccess() { conn( r -> r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()), r -> r.connectionSucceeded(newRemoteConnection()) ).runCommand(Cmd.expectSucceed()); }
@Test public void ensureTimeoutFailAndRecover() { TestReConnection c = conn(200,100,1, r -> { wt(100); r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); c.runCommand(Cmd.expectFail()); wt(200); c.runCommand(Cmd.expectSucceed()); }
@Test public void ensureSuccessThenAvailable() { TestReConnection c = conn(r -> r.connectionSucceeded(newRemoteConnection())); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectAvailable()); }
@Test public void ensureInActiveCausesReconnection() { TestReConnection c = conn( 100, 100, 1, r -> r.connectionSucceeded(newBadConnection()), r -> { wt(200); r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectFail()); wt(300); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectAvailable()); }
@Test public void ensureFirstFailsWaiting() throws InterruptedException, ExecutionException { CountDownLatch latch = new CountDownLatch(1); TestReConnection c = conn( 100000, 100, 100, r -> { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); CompletableFuture<Void> first = CompletableFuture.runAsync(() -> c.runCommand(Cmd.expectFail())); CompletableFuture<Void> rest = CompletableFuture.allOf(IntStream.range(0, 10).mapToObj(i -> CompletableFuture.runAsync(() -> { c.runCommand(Cmd.expectFail()); })).collect(Collectors.toList()).toArray(new CompletableFuture[0])); try { rest.get(0, TimeUnit.SECONDS); Assert.fail(); } catch (TimeoutException e) { } latch.countDown(); first.get(); rest.get(); } |
RpcException extends IOException { public static <T extends Throwable> void propagateIfPossible(@Nullable RpcException e, Class<T> clazz) throws T { if (e == null) { return; } Throwable cause = e.getCause(); if (!(cause instanceof UserRemoteException)) { return; } UserRemoteException ure = (UserRemoteException) e.getCause(); DremioPBError remoteError = ure.getOrCreatePBError(false); ExceptionWrapper ew = remoteError.getException(); Class<? extends Throwable> exceptionClazz; do { try { exceptionClazz = Class.forName(ew.getExceptionClass()).asSubclass(Throwable.class); } catch (ClassNotFoundException cnfe) { logger.info("Cannot deserialize exception " + ew.getExceptionClass(), cnfe); return; } if (UserRpcException.class.isAssignableFrom(exceptionClazz)) { ew = ew.getCause(); continue; } break; } while(true); Throwable t; try { Constructor<? extends Throwable> constructor = exceptionClazz.getConstructor(String.class, Throwable.class); t = constructor.newInstance(ew.getMessage(), e); } catch(ReflectiveOperationException nsme) { Constructor<? extends Throwable> constructor; try { constructor = exceptionClazz.getConstructor(String.class); t = constructor.newInstance(ew.getMessage()).initCause(e); } catch (ReflectiveOperationException rfe) { logger.info("Cannot deserialize exception " + ew.getExceptionClass(), rfe); return; } } Throwables.propagateIfPossible(t, clazz); } RpcException(); RpcException(String message, Throwable cause); RpcException(String errMsg, String status, String errorId, Throwable cause); RpcException(String errMsg, String status, String errorId); RpcException(String message); RpcException(Throwable cause); static RpcException mapException(Throwable t); static RpcException mapException(String message, Throwable t); boolean isRemote(); DremioPBError getRemoteError(); static void propagateIfPossible(@Nullable RpcException e, Class<T> clazz); String getStatus(); String getErrorId(); } | @Test public void testNullException() throws Exception { RpcException.propagateIfPossible(null, Exception.class); }
@Test public void testNonRemoteException() throws Exception { RpcException e = new RpcException("Test message", new Exception()); RpcException.propagateIfPossible(e, Exception.class); }
@Test public void testRemoteTestException() throws Exception { UserRemoteException ure = UserRemoteException.create(UserException .unsupportedError(new UserRpcException(null, "user rpc exception", new TestException("test message"))) .build(logger).getOrCreatePBError(false)); exception.expect(TestException.class); exception.expectMessage("test message"); RpcException.propagateIfPossible(new RpcException(ure), TestException.class); }
@Test public void testRemoteRuntimeException() throws Exception { UserRemoteException ure = UserRemoteException.create(UserException .unsupportedError(new UserRpcException(null, "user rpc exception", new RuntimeException("test message"))) .build(logger).getOrCreatePBError(false)); exception.expect(RuntimeException.class); exception.expectMessage("test message"); RpcException.propagateIfPossible(new RpcException(ure), TestException.class); } |
KeyPair extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2> KeyPair<K1, K2> of(List<Object> list) { checkArgument(list.size() == 2, "list should be of size 2, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); return new KeyPair<>(value1, value2); } KeyPair(K1 key1, K2 key2); @SuppressWarnings("unchecked") static KeyPair<K1, K2> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } KeyPair<String, String> keyPair = KeyPair.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values, keyPair); } |
KeyUtils { public static boolean equals(Object left, Object right) { if (left instanceof byte[] && right instanceof byte[]) { return Arrays.equals((byte[]) left, (byte[]) right); } return Objects.equals(left, right); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); } | @Test public void testEqualsReturnsFalseAllNull() { assertTrue(KeyUtils.equals(null, null)); }
@Test public void testEqualsReturnsFalseLeftNull() { assertFalse(KeyUtils.equals(null, Boolean.TRUE)); }
@Test public void testEqualsReturnsFalseRightNull() { assertFalse(KeyUtils.equals(Boolean.TRUE, null)); }
@Test public void testEqualsReturnsTrueWithBooleanTrueTrue() { assertTrue(KeyUtils.equals(Boolean.TRUE, Boolean.TRUE)); }
@Test public void testEqualsReturnsTrueWithBooleanFalseFalse() { assertTrue(KeyUtils.equals(Boolean.FALSE, Boolean.FALSE)); }
@Test public void testEqualsReturnsFalseWithBooleanTrueFalse() { assertFalse(KeyUtils.equals(Boolean.TRUE, Boolean.FALSE)); }
@Test public void testEqualsReturnsFalseWithBooleanFalseTrue() { assertFalse(KeyUtils.equals(Boolean.FALSE, Boolean.TRUE)); }
@Test public void testEqualsReturnsTrueWithByteArrays() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3, 4}; assertTrue(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsFalseWithByteArrays() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3, 5}; assertFalse(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsFalseWithByteArraysDifferentLength() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3}; assertFalse(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsTrueByteProtoObject() { assertTrue(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)))); }
@Test public void testEqualsReturnsFalseByteProtoObject() { assertFalse(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly".getBytes(UTF_8)))); }
@Test public void testEqualsReturnsFalseByteProtoObjectWithNull() { assertFalse(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), null))); }
@Test public void testEqualsReturnsFalseWithProtoObjectsDifferentUUID() { assertFalse(KeyUtils.equals( new KeyPair<>( PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>( "Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()))); }
@Test public void testEqualsReturnsFalseWithNestedProtoObjectsDifferentUUID() { assertFalse(KeyUtils.equals( new KeyTriple<>( new KeyPair<>(PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID())), new KeyTriple<>( new KeyPair<>(PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID())))); } |
Clean { public static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); final Options options = Options.parse(args); if(options.help) { return; } if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Cleanup should be run on master node"); } Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No KVStore detected."); return; } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); if (provider.getStores().size() == 0) { AdminLogger.log("No store stats available"); } if(options.hasActiveOperation()) { AdminLogger.log("Initial Store Status."); } else { AdminLogger.log("No operation requested. "); } for(StoreWithId<?, ?> id : provider) { KVAdmin admin = id.getStore().getAdmin(); AdminLogger.log(admin.getStats()); } if(options.deleteOrphans) { deleteSplitOrphans(provider.asLegacy()); deleteCollaborationOrphans(provider.asLegacy()); } if(options.maxJobDays < Integer.MAX_VALUE) { deleteOldJobsAndProfiles(provider.asLegacy(), options.maxJobDays); } if (options.deleteOrphanProfiles) { deleteOrphanProfiles(provider.asLegacy()); } if(options.reindexData) { reindexData(provider); } if(options.compactKvStore) { compactStore(provider); } if(options.hasActiveOperation()) { AdminLogger.log("\n\nFinal Store Status."); for(StoreWithId<?, ?> id : provider.unwrap(LocalKVStoreProvider.class)) { KVAdmin admin = id.getStore().getAdmin(); AdminLogger.log(admin.getStats()); } } return; } } static void go(String[] args); static void main(String[] args); } | @Test public void runWithOptions() throws Exception { getCurrentDremioDaemon().close(); Clean.go(new String[] {}); Clean.go(new String[] {"-o", "-i", "-c", "-j=30", "-p"}); Clean.go(new String[] {"-h"}); } |
KeyUtils { public static String toString(Object key) { if (null == key) { return null; } return (key instanceof byte[] ? Arrays.toString((byte[]) key) : key.toString()); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); } | @Test public void testToStringNull() { assertNull(KeyUtils.toString(null)); }
@Test public void testToStringBytes() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString(new byte[]{1, 2, 3, 4})); }
@Test public void testToStringString() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString("[1, 2, 3, 4]")); }
@Test public void testToStringProtoStringBytesKeyPair() { assertEquals("KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}", KeyUtils.toString( new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}))); }
@Test public void testToStringProtoByteKeyPairByteKeyTriple() { assertEquals("KeyTriple{ key1=[123, 127, 9, 0], key2=KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}, key3=[0, 0, 0, 0]}", KeyUtils.toString( new KeyTriple<>( new byte[]{123, 127, 9, 0}, new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}), new byte[]{0, 0, 0, 0}))); } |
AdminCommandRunner { static void runCommand(String commandName, Class<?> command, String[] commandArgs) throws Exception { final Method mainMethod = command.getMethod("main", String[].class); Preconditions.checkState(Modifier.isStatic(mainMethod.getModifiers()) && Modifier.isPublic(mainMethod.getModifiers()), "#main(String[]) must have public and static modifiers"); final Object[] objects = new Object[1]; objects[0] = commandArgs; try { mainMethod.invoke(null, objects); } catch (final ReflectiveOperationException e) { final Throwable cause = e.getCause() != null ? e.getCause() : e; Throwables.throwIfUnchecked(cause); throw new RuntimeException(String.format("Failed to run '%s' command", commandName), e); } } static void main(String[] args); } | @Test public void runCommand() throws Exception { assertFalse(TestCommand.invokedCorrectly); AdminCommandRunner.runCommand("test-command", TestCommand.class, new String[]{"arg0", "arg1"}); assertTrue(TestCommand.invokedCorrectly); } |
KeyUtils { public static int hash(Object... keys) { if (null == keys) { return 0; } int result = 1; for (Object key : keys) { result = 31 * result + hashCode(key); } return result; } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); } | @Test public void testHashBytes() { assertEquals(918073283, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6})); }
@Test public void testHashBytesAndString() { assertEquals(214780274, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string")); }
@Test public void testHashBytesAndStringAndNull() { assertEquals(-1931746098, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string", null)); }
@Test public void testHashString() { assertEquals(1819279604, KeyUtils.hash("test hash string")); }
@Test public void testHashNull() { assertEquals(0, KeyUtils.hash(null)); } |
KeyTriple extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2, K3> KeyTriple<K1, K2, K3> of(List<Object> list) { checkArgument(list.size() == 3, "list should be of size 3, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); final K3 value3 = (K3) list.get(2); return new KeyTriple<>(value1, value2, value3); } KeyTriple(K1 key1, K2 key2, K3 key3); @SuppressWarnings("unchecked") static KeyTriple<K1, K2, K3> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); K3 getKey3(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } final KeyTriple<String, String, String> keyPair = KeyTriple.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values.get(2), keyPair.getKey3()); assertEquals(values, keyPair); } |
ReIndexer implements ReplayHandler { @Override public void put(String tableName, byte[] key, byte[] value) { if (!isIndexed(tableName)) { logger.trace("Ignoring put: {} on table '{}'", key, tableName); return; } final KVStoreTuple<?> keyTuple = keyTuple(tableName, key); final Document document = toDoc(tableName, keyTuple, valueTuple(tableName, value)); if (document != null) { indexManager.getIndex(tableName) .update(keyAsTerm(keyTuple), document); metrics(tableName).puts++; } } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); } | @Test public void add() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] added = {false}; doAnswer(invocation -> { added[0] = true; return null; }).when(index).update(any(Term.class), any(Document.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.put(storeName, one, two); assertTrue(added[0]); } |
ExportProfiles { private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig) throws Exception { Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No database found. Profiles are not exported"); return; } try (LocalKVStoreProvider kvStoreProvider = providerOptional.get()) { kvStoreProvider.start(); exportOffline(options, kvStoreProvider.asLegacy()); } } static void main(String[] args); } | @Test public void testOffline() throws Exception { final String tmpPath = folder0.newFolder("testOffline").getAbsolutePath(); final LegacyKVStoreProvider localKVStoreProvider = l(LegacyKVStoreProvider.class); final LegacyKVStoreProvider spy = spy(localKVStoreProvider); Mockito.doNothing().when(spy).close(); final String[] args = {"-o", "--output", tmpPath, "--format", "JSON", "--write-mode", "FAIL_IF_EXISTS"}; final ExportProfiles.ExportProfilesOptions options = getExportOptions(args); ExportProfiles.exportOffline(options, spy); verifyResult(tmpPath, queryProfile, String.join(" ", args)); } |
ReIndexer implements ReplayHandler { @Override public void delete(String tableName, byte[] key) { if (!isIndexed(tableName)) { logger.trace("Ignoring delete: {} on table '{}'", key, tableName); return; } indexManager.getIndex(tableName) .deleteDocuments(keyAsTerm(keyTuple(tableName, key))); metrics(tableName).deletes++; } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); } | @Test public void delete() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] deleted = {false}; doAnswer(invocation -> { deleted[0] = true; return null; }).when(index).deleteDocuments(any(Term.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.delete(storeName, one); assertTrue(deleted[0]); } |
TracingKVStore implements KVStore<K, V> { @Override public Document<K, V> get(K key, GetOption... options) { return trace("get", () -> delegate.get(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; } | @Test public void testTypedReturnMethod() { setupLegitParentSpan(); when(delegate.get("myKey")).thenReturn(new TestDocument("myKey","yourValue")); Document<String, String> ret = underTest.get("myKey"); assertEquals("yourValue", ret.getValue()); assertChildSpanMethod("get"); } |
TracingKVStore implements KVStore<K, V> { @Override public void delete(K key, DeleteOption... options) { trace("delete", () -> delegate.delete(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; } | @Test public void testVoidReturnMethod() { setupLegitParentSpan(); underTest.delete("byebye"); verify(delegate).delete("byebye"); assertChildSpanMethod("delete"); } |
KVStoreOptionUtility { public static void validateOptions(KVStore.KVStoreOption... options) { if (null == options || options.length <= 1) { return; } boolean foundVersion = false; boolean foundCreate = false; for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { if (foundCreate) { throw new IllegalArgumentException("Multiple CREATE PutOptions supplied."); } else { foundCreate = true; } } else if (option instanceof VersionOption) { if (foundVersion) { throw new IllegalArgumentException("Multiple Version PutOptions supplied."); } else { foundVersion = true; } } } if (foundCreate && foundVersion) { throw new IllegalArgumentException("Conflicting PutOptions supplied."); } } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); } | @Test public void testValidateOptionsNull() { KVStoreOptionUtility.validateOptions((KVStore.PutOption[]) null); }
@Test public void testValidateOptionsEmpty() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{}); }
@Test public void testValidateOptionsSingleCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, createOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleCreateWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, indexPutOption, createOption}); }
@Test public void testValidateOptionsCreateAndIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, indexPutOption}); }
@Test public void testValidateOptionsIndexAndCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, createOption}); }
@Test public void testValidateOptionsSingleVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleVersionWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, indexPutOption, versionOption}); }
@Test public void testValidateOptionsVersionAndIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, indexPutOption}); }
@Test public void testValidateOptionsIndexAndVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsConflict() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsConflictWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, createOption, versionOption}); } |
ResetCatalogSearch { static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); parse(args); if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Reset catalog search should be run on master node"); } final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("Failed to complete catalog search reset. No KVStore detected."); return; } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); AdminLogger.log("Resetting catalog search..."); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); configStore.delete(CONFIG_KEY); AdminLogger.log("Catalog search reset will be completed in 1 minute after Dremio starts."); } } static void main(String[] args); } | @Test public void testResetCatalogSearchCommand() throws Exception { getCurrentDremioDaemon().close(); ResetCatalogSearch.go(new String[] {}); final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(getDACConfig().getConfig()); if (!providerOptional.isPresent()) { throw new Exception("No KVStore detected."); } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); final ConfigurationEntry configurationEntry = configStore.get(CONFIG_KEY); assertEquals(configurationEntry, null); } } |
KVStoreOptionUtility { public static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options) { if (null == options || options.length == 0) { return; } for (KVStore.KVStoreOption option : options) { if (option instanceof IndexPutOption) { throw new IllegalArgumentException("IndexPutOption not supported."); } } } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); } | @Test public void testIndexPutOptionNotSupportedNull() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(); }
@Test public void testIndexPutOptionNotSupportedEmpty() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{}); }
@Test public void testIndexPutOptionNotSupportedSingleCreate() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption}); }
@Test public void testIndexPutOptionNotSupportedSingleVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{versionOption}); }
@Test public void testIndexPutOptionNotSupportedCreateAndVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFound() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{indexPutOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFoundAmongMany() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, indexPutOption, versionOption}); } |
SystemStoragePluginInitializer implements Initializer<Void> { @VisibleForTesting void createOrUpdateSystemSource(final CatalogService catalogService, final NamespaceService ns, final SourceConfig config) throws Exception { try { config.setAllowCrossSourceSelection(true); final boolean isCreated = catalogService.createSourceIfMissingWithThrow(config); if (isCreated) { return; } } catch (ConcurrentModificationException ex) { logger.info("Two source creations occurred simultaneously, ignoring the failed one.", ex); } final NamespaceKey nsKey = new NamespaceKey(config.getName()); final SourceConfig oldConfig = ns.getSource(nsKey); final SourceConfig updatedConfig = config; updatedConfig .setId(oldConfig.getId()) .setCtime(oldConfig.getCtime()) .setTag(oldConfig.getTag()) .setConfigOrdinal(oldConfig.getConfigOrdinal()); if (oldConfig.equals(updatedConfig)) { return; } ((CatalogServiceImpl) catalogService).getSystemUserCatalog().updateSource(updatedConfig); } @Override Void initialize(BindingProvider provider); } | @Test public void refreshSystemPluginsTest() throws Exception { SystemStoragePluginInitializer systemInitializer = new SystemStoragePluginInitializer(); SourceConfig c = new SourceConfig(); InternalFileConf conf = new InternalFileConf(); conf.connection = "classpath: conf.path = "/"; conf.isInternal = false; conf.propertyList = ImmutableList.of(new Property("abc", "bcd"), new Property("def", "123")); c.setName("mytest"); c.setConnectionConf(conf); c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, c); final CatalogServiceImpl catalog = (CatalogServiceImpl) catalogService; SourceConfig updatedC = new SourceConfig(); InternalFileConf updatedCConf = new InternalFileConf(); updatedCConf.connection = "file: updatedCConf.path = "/"; updatedCConf.isInternal = true; updatedC.setName("mytest"); updatedC.setConnectionConf(updatedCConf); updatedC.setMetadataPolicy(CatalogService.DEFAULT_METADATA_POLICY); final SourceConfig config = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedConf = (InternalFileConf) reader.getConnectionConf(config); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, updatedC); final SourceConfig updatedConfig = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedUpdatedConfig = (InternalFileConf) reader.getConnectionConf(updatedConfig); assertNotNull(decryptedConf.getProperties()); assertEquals(2, decryptedConf.getProperties().size()); assertTrue(decryptedUpdatedConfig.getProperties().isEmpty()); assertNotEquals(config.getMetadataPolicy(), updatedConfig.getMetadataPolicy()); assertNotEquals(decryptedConf.getConnection(), decryptedUpdatedConfig.getConnection()); assertEquals("file: assertNotEquals(decryptedConf.isInternal, decryptedUpdatedConfig.isInternal); assertEquals(decryptedConf.path, decryptedUpdatedConfig.path); assertNotEquals(config.getTag(), updatedConfig.getTag()); SourceConfig updatedC2 = new SourceConfig(); InternalFileConf updatedCConf2 = new InternalFileConf(); updatedCConf2.connection = "file: updatedCConf2.path = "/"; updatedCConf2.isInternal = true; updatedC2.setName("mytest"); updatedC2.setConnectionConf(updatedCConf2); updatedC2.setMetadataPolicy(CatalogService.DEFAULT_METADATA_POLICY); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, updatedC2); final SourceConfig updatedConfig2 = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedConf2 = (InternalFileConf) reader.getConnectionConf(updatedConfig2); assertTrue(decryptedConf2.getProperties().isEmpty()); assertEquals(updatedConfig.getTag(), updatedConfig2.getTag()); catalog.deleteSource("mytest"); assertNull(catalog.getManagedSource("myTest")); } |
KVStoreOptionUtility { public static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options) { validateOptions(options); if (null == options || options.length == 0) { return Optional.empty(); } for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { return Optional.of((KVStore.PutOption) option); } else if (option instanceof VersionOption) { return Optional.of((VersionOption) option); } } return Optional.empty(); } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); } | @Test public void testGetCreateOrVersionOptionNull() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(); assertFalse(ret.isPresent()); }
@Test public void testGetCreateOrVersionOptionEmpty() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{}); assertFalse(ret.isPresent()); }
@Test public void testGetCreateOrVersionOptionSingleCreate() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption}); assertEquals(createOption, ret.get()); }
@Test public void testGetCreateOrVersionOptionSingleVersion() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{versionOption}); assertEquals(versionOption, ret.get()); }
@Test(expected = IllegalArgumentException.class) public void testGetCreateOrVersionOptionCreateAndVersion() { KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption, versionOption}); }
@Test public void testGetCreateOrVersionOptionIndexPutOptionFound() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{indexPutOption}); assertFalse(ret.isPresent()); }
@Test(expected = IllegalArgumentException.class) public void testGetCreateOrVersionOptionPutOptionFoundAmongMany() { KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption, indexPutOption, versionOption}); } |
DateUtils { public static long getStartOfLastMonth() { LocalDate now = LocalDate.now(); LocalDate targetDate = now.minusDays(now.getDayOfMonth() - 1).minusMonths(1); Instant instant = targetDate.atStartOfDay().toInstant(ZoneOffset.UTC); return instant.toEpochMilli(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); } | @Test public void testGetStartOfLastMonth() { LocalDate dateLastMonth = LocalDate.now().minusMonths(1); long startOfLastMonth = DateUtils.getStartOfLastMonth(); LocalDate dateStartOfLastMonth = DateUtils.fromEpochMillis(startOfLastMonth); assertEquals(dateLastMonth.getMonthValue(), dateStartOfLastMonth.getMonthValue()); assertEquals(dateLastMonth.getYear(), dateStartOfLastMonth.getYear()); assertEquals(1, dateStartOfLastMonth.getDayOfMonth()); } |
KVStoreOptionUtility { public static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options) { if (null == options) { return null; } return Arrays .stream(options) .filter(option -> !(option instanceof IndexPutOption)) .toArray(KVStore.PutOption[]::new); } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); } | @Test public void testRemoveIndexPutOption() { testRemoveIndexPutOptions( new KVStore.PutOption[]{indexPutOption}, new KVStore.PutOption[]{}); } |
LegacyProtobufSerializer extends ProtobufSerializer<T> { public static <M extends Message> M parseFrom(Parser<M> parser, ByteString bytes) throws InvalidProtocolBufferException { return rewriteProtostuff(parser.parseFrom(bytes)); } LegacyProtobufSerializer(Class<T> clazz, Parser<T> parser); @Override T revert(byte[] bytes); static M parseFrom(Parser<M> parser, ByteString bytes); static M parseFrom(Parser<M> parser, byte[] bytes); static M parseFrom(Parser<M> parser, ByteBuffer bytes); } | @Test public void testParse() throws InvalidProtocolBufferException { final UnknownFieldSet term1 = UnknownFieldSet.newBuilder() .addField(SearchQuery.Term.FIELD_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("foo")).build()) .addField(SearchQuery.Term.VALUE_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("bar")).build()) .build(); final UnknownFieldSet sq1 = UnknownFieldSet.newBuilder() .addField(SearchQuery.TYPE_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.Type.TERM_VALUE).build()) .addField(SearchQuery.TERM_FIELD_NUMBER, Field.newBuilder().addGroup(term1).build()) .build(); final UnknownFieldSet term2 = UnknownFieldSet.newBuilder() .addField(SearchQuery.Term.FIELD_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("foo")).build()) .addField(SearchQuery.Term.VALUE_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("baz")).build()) .build(); final UnknownFieldSet sq2 = UnknownFieldSet.newBuilder() .addField(SearchQuery.TYPE_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.Type.TERM_VALUE).build()) .addField(SearchQuery.TERM_FIELD_NUMBER, Field.newBuilder().addGroup(term2).build()) .build(); final UnknownFieldSet bool = UnknownFieldSet.newBuilder() .addField(SearchQuery.Boolean.OP_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.BooleanOp.AND_VALUE).build()) .addField(SearchQuery.Boolean.CLAUSES_FIELD_NUMBER, Field.newBuilder().addGroup(sq1).addGroup(sq2).build()) .build(); final SearchQuery query = SearchQuery.newBuilder() .setType(SearchQuery.Type.BOOLEAN) .setUnknownFields(UnknownFieldSet.newBuilder().addField(SearchQuery.BOOLEAN_FIELD_NUMBER, Field.newBuilder().addGroup(bool).build()).build()) .build(); final SearchQuery expected = SearchQuery.newBuilder() .setType(SearchQuery.Type.BOOLEAN) .setBoolean( SearchQuery.Boolean.newBuilder() .setOp(SearchQuery.BooleanOp.AND) .addClauses(SearchQuery.newBuilder() .setType(SearchQuery.Type.TERM).setTerm(Term.newBuilder().setField("foo").setValue("bar"))) .addClauses(SearchQuery.newBuilder() .setType(SearchQuery.Type.TERM).setTerm(Term.newBuilder().setField("foo").setValue("baz"))) ) .build(); assertThat(LegacyProtobufSerializer.parseFrom(SearchQuery.PARSER, query.toByteString()), is(equalTo(expected))); } |
ReflectionManager implements Runnable { @VisibleForTesting void handleGoal(ReflectionGoal goal) { final ReflectionEntry entry = reflectionStore.get(goal.getId()); if (entry == null) { if (goal.getState() == ReflectionGoalState.ENABLED) { reflectionStore.save(create(goal)); } } else if (reflectionGoalChecker.isEqual(goal, entry)) { return; } else if(reflectionGoalChecker.checkHash(goal, entry)){ updateThatHasChangedEntry(goal, entry); for (Materialization materialization : materializationStore.find(entry.getId())) { if (!Objects.equals(materialization.getArrowCachingEnabled(), goal.getArrowCachingEnabled())) { materializationStore.save( materialization .setArrowCachingEnabled(goal.getArrowCachingEnabled()) .setReflectionGoalVersion(goal.getTag()) ); } } } else { logger.debug("reflection goal {} updated. state {} -> {}", getId(goal), entry.getState(), goal.getState()); cancelRefreshJobIfAny(entry); final boolean enabled = goal.getState() == ReflectionGoalState.ENABLED; entry.setState(enabled ? UPDATE : DEPRECATE) .setArrowCachingEnabled(goal.getArrowCachingEnabled()) .setGoalVersion(goal.getTag()) .setName(goal.getName()) .setReflectionGoalHash(reflectionGoalChecker.calculateReflectionGoalVersion(goal)); reflectionStore.save(entry); } } ReflectionManager(SabotContext sabotContext, JobsService jobsService, NamespaceService namespaceService,
OptionManager optionManager, ReflectionGoalsStore userStore, ReflectionEntriesStore reflectionStore,
ExternalReflectionStore externalReflectionStore, MaterializationStore materializationStore,
DependencyManager dependencyManager, DescriptorCache descriptorCache,
Set<ReflectionId> reflectionsToUpdate, WakeUpCallback wakeUpCallback,
Supplier<ExpansionHelper> expansionHelper, BufferAllocator allocator, Path accelerationBasePath,
ReflectionGoalChecker reflectionGoalChecker, RefreshStartHandler refreshStartHandler); @Override void run(); long getLastWakeupTime(); } | @Test public void handleGoalWithNoEntry(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String dataSetId = "dataSetId"; String tag = "rgTag"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setId(reflectionId) .setArrowCachingEnabled(true) .setName(reflectionGoalName) .setTag(tag) .setType(ReflectionType.EXTERNAL) .setDatasetId(dataSetId); Subject subject = new Subject(); when(subject.reflectionStore.get(reflectionId)).thenReturn(null); when(subject.reflectionGoalChecker.calculateReflectionGoalVersion(reflectionGoal)).thenReturn(reflectionGoalHash); subject.reflectionManager.handleGoal(reflectionGoal); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionGoalChecker).calculateReflectionGoalVersion(reflectionGoal); verify(subject.reflectionStore).save( new ReflectionEntry() .setId(reflectionId) .setReflectionGoalHash(reflectionGoalHash) .setDatasetId(dataSetId) .setState(REFRESH) .setGoalVersion(tag) .setType(ReflectionType.EXTERNAL) .setName(reflectionGoalName) .setArrowCachingEnabled(true) ); verifyNoMoreInteractions(subject.reflectionStore); }
@Test public void handleGoalWithEntryButNothingHasChanged(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setId(reflectionId) .setArrowCachingEnabled(true) .setName(reflectionGoalName) .setType(ReflectionType.EXTERNAL) .setDatasetId(dataSetId) .setArrowCachingEnabled(true); ReflectionEntry reflectionEntry = new ReflectionEntry() .setArrowCachingEnabled(true) .setId(reflectionId) .setReflectionGoalHash(reflectionGoalHash); Subject subject = new Subject(); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionGoalChecker.isEqual(reflectionGoal, reflectionEntry)) .thenReturn(true); subject.reflectionManager.handleGoal(reflectionGoal); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionGoalChecker).isEqual(reflectionGoal, reflectionEntry); verifyNoMoreInteractions(subject.reflectionStore); }
@Test public void handleGoalWithEntryButHashHasNotChangedAndBoostHasChanged(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String goalTag = "goal_tag"; String reflectionGoalName = "name"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setArrowCachingEnabled(true) .setDatasetId(dataSetId) .setId(reflectionId) .setName(reflectionGoalName) .setTag(goalTag) .setType(ReflectionType.EXTERNAL); ReflectionEntry reflectionEntry = new ReflectionEntry() .setArrowCachingEnabled(false) .setId(reflectionId) .setName("oldName") .setGoalVersion("old_tag") .setReflectionGoalHash(reflectionGoalHash) .setState(ReflectionState.ACTIVE); Subject subject = new Subject(); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionGoalChecker.checkHash(reflectionGoal, reflectionEntry)) .thenReturn(true); when(subject.materializationStore.find(reflectionId)).thenReturn(Collections.emptyList()); subject.reflectionManager.handleGoal(reflectionGoal); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionGoalChecker).checkHash(reflectionGoal, reflectionEntry); verify(subject.reflectionStore).save(reflectionEntry); verifyNoMoreInteractions(subject.reflectionStore); assertEquals(ReflectionState.ACTIVE, reflectionEntry.getState()); assertEquals(true, reflectionEntry.getArrowCachingEnabled()); assertEquals(reflectionGoalName, reflectionEntry.getName()); assertEquals(goalTag, reflectionEntry.getGoalVersion()); }
@Test public void handleGoalTagChangedAndEntryIsInFailedState(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String goalTag = "goal_tag"; String reflectionGoalName = "name"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setArrowCachingEnabled(true) .setDatasetId(dataSetId) .setId(reflectionId) .setName(reflectionGoalName) .setTag(goalTag) .setState(ReflectionGoalState.ENABLED) .setType(ReflectionType.EXTERNAL); ReflectionEntry reflectionEntry = new ReflectionEntry() .setArrowCachingEnabled(false) .setId(reflectionId) .setName("oldName") .setGoalVersion("old_tag") .setReflectionGoalHash(reflectionGoalHash) .setState(ReflectionState.FAILED) .setNumFailures(3); Subject subject = new Subject(); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionGoalChecker.checkHash(reflectionGoal, reflectionEntry)) .thenReturn(true); when(subject.materializationStore.find(reflectionId)).thenReturn(Collections.emptyList()); subject.reflectionManager.handleGoal(reflectionGoal); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionGoalChecker).checkHash(reflectionGoal, reflectionEntry); verify(subject.reflectionStore).save(reflectionEntry); verifyNoMoreInteractions(subject.reflectionStore); assertEquals(ReflectionState.UPDATE, reflectionEntry.getState()); assertEquals(Integer.valueOf(0), reflectionEntry.getNumFailures()); assertEquals(true, reflectionEntry.getArrowCachingEnabled()); assertEquals(reflectionGoalName, reflectionEntry.getName()); assertEquals(goalTag, reflectionEntry.getGoalVersion()); }
@Test public void handleGoalWithEntryButHashHasChanged(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String goalTag = "goalTag"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setArrowCachingEnabled(true) .setDatasetId(dataSetId) .setId(reflectionId) .setName(reflectionGoalName) .setTag(goalTag) .setType(ReflectionType.EXTERNAL); ReflectionEntry reflectionEntry = new ReflectionEntry() .setArrowCachingEnabled(false) .setId(reflectionId) .setGoalVersion("old tag") .setReflectionGoalHash(new ReflectionGoalHash("xxx")) .setState(ReflectionState.ACTIVE); Subject subject = new Subject(); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionGoalChecker.isEqual(reflectionGoal, reflectionEntry)) .thenReturn(false); when(subject.reflectionGoalChecker.checkHash(reflectionGoal, reflectionEntry)) .thenReturn(false); when(subject.reflectionGoalChecker.calculateReflectionGoalVersion(reflectionGoal)).thenReturn(reflectionGoalHash); when(subject.materializationStore.find(reflectionId)).thenReturn(Collections.emptyList()); subject.reflectionManager.handleGoal(reflectionGoal); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionGoalChecker).checkHash(reflectionGoal, reflectionEntry); verify(subject.reflectionStore).save(reflectionEntry); verifyNoMoreInteractions(subject.reflectionStore); assertEquals(true, reflectionEntry.getArrowCachingEnabled()); assertEquals(goalTag, reflectionEntry.getGoalVersion()); assertEquals(reflectionGoalName, reflectionEntry.getName()); assertEquals(reflectionGoalHash, reflectionEntry.getReflectionGoalHash()); assertEquals(ReflectionState.UPDATE, reflectionEntry.getState()); } |
ReflectionManager implements Runnable { @VisibleForTesting void sync(){ long lastWakeupTime = System.currentTimeMillis(); final long previousLastWakeupTime = lastWakeupTime - WAKEUP_OVERLAP_MS; final long deletionGracePeriod = optionManager.getOption(REFLECTION_DELETION_GRACE_PERIOD) * 1000; final long deletionThreshold = System.currentTimeMillis() - deletionGracePeriod; final int numEntriesToDelete = (int) optionManager.getOption(REFLECTION_DELETION_NUM_ENTRIES); handleReflectionsToUpdate(); handleDeletedDatasets(); handleGoals(previousLastWakeupTime); handleEntries(); deleteDeprecatedMaterializations(deletionThreshold, numEntriesToDelete); deprecateMaterializations(); deleteDeprecatedGoals(deletionThreshold); this.lastWakeupTime = lastWakeupTime; } ReflectionManager(SabotContext sabotContext, JobsService jobsService, NamespaceService namespaceService,
OptionManager optionManager, ReflectionGoalsStore userStore, ReflectionEntriesStore reflectionStore,
ExternalReflectionStore externalReflectionStore, MaterializationStore materializationStore,
DependencyManager dependencyManager, DescriptorCache descriptorCache,
Set<ReflectionId> reflectionsToUpdate, WakeUpCallback wakeUpCallback,
Supplier<ExpansionHelper> expansionHelper, BufferAllocator allocator, Path accelerationBasePath,
ReflectionGoalChecker reflectionGoalChecker, RefreshStartHandler refreshStartHandler); @Override void run(); long getLastWakeupTime(); } | @Test public void testSyncDoesNotUpdateReflectionWhenOnlyBoostIsToggle(){ ReflectionId reflectionId = new ReflectionId("r_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); String reflectionGoalName = "name"; String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setId(reflectionId) .setArrowCachingEnabled(true) .setDatasetId(dataSetId) .setType(ReflectionType.EXTERNAL) .setState(ReflectionGoalState.ENABLED); ReflectionEntry reflectionEntry = new ReflectionEntry() .setId(reflectionId) .setReflectionGoalHash(reflectionGoalHash) .setArrowCachingEnabled(false) .setState(ReflectionState.ACTIVE); Materialization materialization = new Materialization() .setArrowCachingEnabled(false); DatasetConfig datasetConfig = new DatasetConfig(); Subject subject = new Subject(); when(subject.dependencyManager.shouldRefresh(reflectionEntry, 5555L)).thenReturn(false); when(subject.externalReflectionStore.getExternalReflections()).thenReturn(emptyList()); when(subject.materializationStore.find(reflectionId)).thenReturn(singletonList(materialization)); when(subject.materializationStore.getAllExpiredWhen(anyLong())).thenReturn(emptyList()); when(subject.materializationStore.getDeletableEntriesModifiedBefore(anyLong(), anyInt())).thenReturn(emptyList()); when(subject.namespaceService.findDatasetByUUID(dataSetId)).thenReturn(datasetConfig); when(subject.optionManager.getOption(ReflectionOptions.NO_DEPENDENCY_REFRESH_PERIOD_SECONDS)).thenReturn(5555L); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionStore.find()).thenReturn(singletonList(reflectionEntry)); when(subject.reflectionGoalChecker.isEqual(reflectionGoal, reflectionEntry)).thenReturn(false); when(subject.reflectionGoalChecker.checkHash(reflectionGoal,reflectionEntry)).thenReturn(true); when(subject.userStore.getAllNotDeleted()).thenReturn(singletonList(reflectionGoal)); when(subject.userStore.getDeletedBefore(anyLong())).thenReturn(emptyList()); when(subject.userStore.getModifiedOrCreatedSince(anyLong())).thenReturn(singletonList(reflectionGoal)); subject.reflectionManager.sync(); verify(subject.materializationStore).save(materialization); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionStore).find(); verify(subject.reflectionStore).save(reflectionEntry); verify(subject.reflectionGoalChecker).checkHash(reflectionGoal, reflectionEntry); verifyNoMoreInteractions(subject.reflectionStore); verifyNoMoreInteractions(subject.refreshStartHandler); assertEquals(reflectionGoalHash, reflectionEntry.getReflectionGoalHash()); assertEquals(true, reflectionEntry.getArrowCachingEnabled()); assertEquals(true, materialization.getArrowCachingEnabled()); assertEquals(ReflectionState.ACTIVE, reflectionEntry.getState()); }
@Test public void testSyncDoesUpdateReflectionWhenChanged(){ ReflectionId reflectionId = new ReflectionId("r_id"); MaterializationId materializationId = new MaterializationId("m_id"); ReflectionGoalHash reflectionGoalHash = new ReflectionGoalHash("MY_HASH"); JobId materializationJobId = new JobId("m_job_id"); String dataSetId = "dataSetId"; ReflectionGoal reflectionGoal = new ReflectionGoal() .setId(reflectionId) .setArrowCachingEnabled(true) .setDatasetId(dataSetId) .setType(ReflectionType.EXTERNAL) .setState(ReflectionGoalState.ENABLED); ReflectionEntry reflectionEntry = new ReflectionEntry() .setId(reflectionId) .setReflectionGoalHash(reflectionGoalHash) .setArrowCachingEnabled(false) .setState(ReflectionState.ACTIVE); Materialization materialization = new Materialization() .setId(materializationId) .setReflectionId(reflectionId) .setArrowCachingEnabled(false); DatasetConfig datasetConfig = new DatasetConfig(); Subject subject = new Subject(); when(subject.dependencyManager.shouldRefresh(reflectionEntry, 5555L)).thenReturn(false); when(subject.externalReflectionStore.getExternalReflections()).thenReturn(emptyList()); when(subject.materializationStore.find(reflectionId)).thenReturn(singletonList(materialization)); when(subject.materializationStore.getAllExpiredWhen(anyLong())).thenReturn(emptyList()); when(subject.materializationStore.getDeletableEntriesModifiedBefore(anyLong(), anyInt())).thenReturn(emptyList()); when(subject.materializationStore.getAllDone(reflectionId)).thenReturn(singletonList(materialization)); when(subject.namespaceService.findDatasetByUUID(dataSetId)).thenReturn(datasetConfig); when(subject.optionManager.getOption(ReflectionOptions.NO_DEPENDENCY_REFRESH_PERIOD_SECONDS)).thenReturn(5555L); when(subject.reflectionStore.get(reflectionId)).thenReturn(reflectionEntry); when(subject.reflectionStore.find()).thenReturn(singletonList(reflectionEntry)); when(subject.reflectionGoalChecker.isEqual(reflectionGoal, reflectionEntry)).thenReturn(false); when(subject.reflectionGoalChecker.checkHash(reflectionGoal,reflectionEntry)).thenReturn(false); when(subject.reflectionGoalChecker.calculateReflectionGoalVersion(reflectionGoal)).thenReturn(reflectionGoalHash); when(subject.refreshStartHandler.startJob(any(), anyLong())).thenReturn(materializationJobId); when(subject.sabotContext.getExecutors()).thenReturn(singletonList(null)); when(subject.userStore.getAllNotDeleted()).thenReturn(singletonList(reflectionGoal)); when(subject.userStore.getDeletedBefore(anyLong())).thenReturn(emptyList()); when(subject.userStore.getModifiedOrCreatedSince(anyLong())).thenReturn(singletonList(reflectionGoal)); subject.reflectionManager.sync(); verify(subject.reflectionStore).get(reflectionId); verify(subject.reflectionStore).find(); verify(subject.reflectionStore, times(2)).save(reflectionEntry); verify(subject.reflectionGoalChecker).checkHash(reflectionGoal, reflectionEntry); verify(subject.descriptorCache).invalidate(materializationId); verify(subject.refreshStartHandler).startJob(any(), anyLong()); verifyNoMoreInteractions(subject.reflectionStore); verifyNoMoreInteractions(subject.refreshStartHandler); assertEquals(reflectionGoalHash, reflectionEntry.getReflectionGoalHash()); assertEquals(true, reflectionEntry.getArrowCachingEnabled()); assertEquals(false, materialization.getArrowCachingEnabled()); assertEquals(0 , reflectionEntry.getNumFailures().intValue()); assertEquals(ReflectionState.REFRESHING, reflectionEntry.getState()); assertEquals(MaterializationState.DEPRECATED, materialization.getState()); } |
DateUtils { public static LocalDate getLastSundayDate(final LocalDate dateWithinWeek) { int dayOfWeek = dateWithinWeek.getDayOfWeek().getValue(); dayOfWeek = (dayOfWeek == 7) ? 0 : dayOfWeek; return dateWithinWeek.minusDays(dayOfWeek); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); } | @Test public void testGetLastSundayDate() { LocalDate testDate1 = LocalDate.parse("2020-03-29"); LocalDate date1LastSunday = DateUtils.getLastSundayDate(testDate1); assertEquals(testDate1, date1LastSunday); LocalDate testDate2 = LocalDate.parse("2020-03-28"); LocalDate date2LastSunday = DateUtils.getLastSundayDate(testDate2); assertEquals(LocalDate.parse("2020-03-22"), date2LastSunday); } |
DependencyGraph { public synchronized void loadFromStore() { for (Map.Entry<ReflectionId, ReflectionDependencies> entry : dependenciesStore.getAll()) { final List<ReflectionDependencyEntry> dependencies = entry.getValue().getEntryList(); if (dependencies == null || dependencies.isEmpty()) { continue; } try { setPredecessors(entry.getKey(), FluentIterable.from(dependencies) .transform(new Function<ReflectionDependencyEntry, DependencyEntry>() { @Override public DependencyEntry apply(ReflectionDependencyEntry entry) { return DependencyEntry.of(entry); } }).toSet()); } catch (DependencyException e) { logger.warn("Found a cyclic dependency while loading dependencies for {}, skipping", entry.getKey().getId(), e); } } } DependencyGraph(DependenciesStore dependenciesStore); synchronized void loadFromStore(); synchronized void setDependencies(final ReflectionId reflectionId, Set<DependencyEntry> dependencies); synchronized void delete(ReflectionId id); } | @Test public void testLoadFromStore() throws Exception { final DependenciesStore dependenciesStore = Mockito.mock(DependenciesStore.class); final DependencyGraph graph = new DependencyGraph(dependenciesStore); final Multimap<String, String> dependencyMap = MultimapBuilder.hashKeys().arrayListValues().build(); dependencyMap.put("raw1", "pds1"); dependencyMap.put("raw1", "tablefunction1"); dependencyMap.put("agg1", "raw1"); dependencyMap.put("raw2", "pds2"); dependencyMap.put("raw2", "tablefunction2"); dependencyMap.put("agg2", "raw2"); dependencyMap.put("agg3", "raw2"); dependencyMap.putAll("vds-raw", Lists.newArrayList("raw1", "raw2")); dependencyMap.put("vds-agg1", "vds-raw"); dependencyMap.putAll("vds-agg2", Lists.newArrayList("agg1", "agg2")); Mockito.when(dependenciesStore.getAll()).thenReturn(storeDependencies(dependencyMap).entrySet()); graph.loadFromStore(); for (String dependant : dependencyMap.keySet()) { for (String parent : dependencyMap.get(dependant)) { assertTrue(String.format("%s > %s", parent, dependant), isPredecessor(graph, parent, dependant)); if (dependencyByName.get(parent).getType() == DependencyType.REFLECTION) { assertTrue(String.format("%s < %s", dependant, parent), isSuccessor(graph, parent, dependant)); } } } } |
ReflectionGoalChecker { public static boolean checkGoal(ReflectionGoal goal, Materialization materialization) { return Instance.isEqual(goal, materialization.getReflectionGoalVersion()); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; } | @Test public void testMatchesTag() { final String testTag = "testTag"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag(testTag); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMatchesVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(Long.valueOf(testTag)); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNonNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(0L); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(null); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); } |
ReflectionGoalChecker { public boolean checkHash(ReflectionGoal goal, ReflectionEntry entry){ if(null == entry.getReflectionGoalHash()){ return false; } return entry.getReflectionGoalHash().equals(calculateReflectionGoalVersion(goal)); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; } | @Test public void testCheckHashAgainstHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry() .setReflectionGoalHash(new ReflectionGoalHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertTrue(ReflectionGoalChecker.Instance.checkHash(goal, entry)); }
@Test public void testCheckHashAgainstNullHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry(); assertFalse(ReflectionGoalChecker.Instance.checkHash(goal, entry)); } |
ReflectionGoalChecker { public ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal){ HasherOutput hasherOutput = new HasherOutput(); Output blackListedOutput = reflectionGoalMaterializationBlackLister.apply(hasherOutput); try { reflectionGoal.writeTo(blackListedOutput, reflectionGoal); return new ReflectionGoalHash() .setHash(hasherOutput.getHasher().hash().toString()); } catch (IOException ioException) { throw new RuntimeException(ioException); } } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; } | @Test public void testHashingEmptyGoal(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionGoalHash actual = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", actual.getHash()); }
@Test public void testHashingEmptyIfExcludingBlackListFieldsGoal(){ ReflectionGoal goal = new ReflectionGoal() .setTag(Long.toString(System.currentTimeMillis())) .setCreatedAt(System.currentTimeMillis()) .setModifiedAt(System.currentTimeMillis()) .setVersion(System.currentTimeMillis()) .setName("Name") .setArrowCachingEnabled(false); ReflectionGoalHash actual = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", actual.getHash()); }
@Test public void testHashingEmptyWithBoostEnabledGoal(){ ReflectionGoal goal = new ReflectionGoal() .setArrowCachingEnabled(true); ReflectionGoalHash actual = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal); assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", actual.getHash()); }
@Test public void testHashingWithUniqueIdGoal(){ ReflectionGoal goal = new ReflectionGoal() .setId(new ReflectionId("xxx")); ReflectionGoalHash actual = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal); assertEquals("a9171a2d1e967b50401388ba1271fba59386adac44078e0a0047f9111167f1a2", actual.getHash()); }
@Test public void testHashingWithDifferentDetails(){ ReflectionGoal goal1 = new ReflectionGoal() .setId(new ReflectionId("xxx")) .setDetails( new ReflectionDetails() .setDimensionFieldList(ImmutableList.of( new ReflectionDimensionField() .setName("field") .setGranularity(DimensionGranularity.NORMAL) )) ); ReflectionGoal goal2 = new ReflectionGoal() .setId(new ReflectionId("xxx")) .setDetails( new ReflectionDetails() .setDimensionFieldList(ImmutableList.of( new ReflectionDimensionField() .setName("field2") .setGranularity(DimensionGranularity.DATE) )) ); ReflectionGoalHash actual1 = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal1); ReflectionGoalHash actual2 = ReflectionGoalChecker.Instance.calculateReflectionGoalVersion(goal2); assertEquals( "We expect difrrent values for different details", "c5f4f595fb56e276b02a2e6fa6cb7fad1ca2afab691fee3a7e0465fc93fb1607", actual1.getHash() ); assertEquals( "We expect difrrent values for different details", "296a48c3f656ad3430da74353556d40fe4d0756952e2ce80cd7e6df58b064275", actual2.getHash() ); } |
DateUtils { public static LocalDate getMonthStartDate(final LocalDate dateWithinMonth) { int dayOfMonth = dateWithinMonth.getDayOfMonth(); return dateWithinMonth.minusDays((dayOfMonth - 1)); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); } | @Test public void testGetMonthStartDate() { LocalDate testDate1 = LocalDate.parse("2020-03-01"); LocalDate monthStartDate = DateUtils.getMonthStartDate(testDate1); assertEquals(testDate1, monthStartDate); LocalDate testDate2 = LocalDate.parse("2020-03-31"); LocalDate date2MonthStartDate = DateUtils.getMonthStartDate(testDate2); assertEquals(testDate1, date2MonthStartDate); } |
OptionList extends ArrayList<OptionValue> { public void mergeIfNotPresent(OptionList list) { final Set<OptionValue> options = Sets.newTreeSet(this); for (OptionValue optionValue : list) { if (options.add(optionValue)) { this.add(optionValue); } } } void merge(OptionList list); void mergeIfNotPresent(OptionList list); OptionList getSystemOptions(); OptionList getNonSystemOptions(); } | @Test public void testMergeOptionLists() { final OptionValue optionValue0 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", false); final OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option1", 2); final OptionValue optionValue2 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option2", 4); final OptionValue optionValue3 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", true); final OptionValue optionValue4 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option1", 2); final OptionList localList = new OptionList(); localList.add(optionValue0); localList.add(optionValue1); localList.add(optionValue2); final OptionList changedList = new OptionList(); changedList.add(optionValue3); changedList.add(optionValue4); final OptionList expectedList = new OptionList(); expectedList.add(optionValue3); expectedList.add(optionValue4); expectedList.add(optionValue1); expectedList.add(optionValue2); changedList.mergeIfNotPresent(localList); assert changedList.equals(expectedList) : String.format("OptionLists merge incorrectly.\n\nexpected: %s \n\n" + "returned: %s", expectedList, changedList); } |
BoundCommandPool implements CommandPool { @Override public <V> CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread) { final long time = System.currentTimeMillis(); final CommandWrapper<V> wrapper = new CommandWrapper<>(priority, descriptor, time, command); logger.debug("command {} created", descriptor); if (runInSameThread) { logger.debug("running command {} in the same calling thread", descriptor); wrapper.run(); } else { executorService.execute(wrapper); } return wrapper.getFuture(); } BoundCommandPool(final int poolSize, Tracer tracer); @Override CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread); @Override void start(); @Override void close(); } | @Test public void testSamePrioritySuppliers() throws Exception { final CommandPool pool = newTestCommandPool(); final BlockingCommand blocking = new BlockingCommand(); pool.submit(CommandPool.Priority.HIGH, "test", blocking, false); Future<Integer> future1 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); Thread.sleep(5); Future<Integer> future2 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); Thread.sleep(5); Future<Integer> future3 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); blocking.unblock(); Assert.assertEquals(0, (int) Futures.getUnchecked(future1)); Assert.assertEquals(1, (int) Futures.getUnchecked(future2)); Assert.assertEquals(2, (int) Futures.getUnchecked(future3)); }
@Test public void testDifferentPrioritySuppliers() { final CommandPool pool = newTestCommandPool(); final BlockingCommand blocking = new BlockingCommand(); pool.submit(CommandPool.Priority.HIGH, "test", blocking, false); Future<Integer> future1 = pool.submit(CommandPool.Priority.LOW, "test", (waitInMillis) -> counter.getAndIncrement(), false); Future<Integer> future2 = pool.submit(CommandPool.Priority.MEDIUM, "test", (waitInMillis) -> counter.getAndIncrement(), false); Future<Integer> future3 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); blocking.unblock(); Assert.assertEquals(2, (int) Futures.getUnchecked(future1)); Assert.assertEquals(1, (int) Futures.getUnchecked(future2)); Assert.assertEquals(0, (int) Futures.getUnchecked(future3)); } |
PartitionChunkId implements Comparable<PartitionChunkId> { @JsonCreator public static PartitionChunkId of(String partitionChunkId) { final String[] ids = partitionChunkId.split(DELIMITER, 3); Preconditions.checkArgument(ids.length == 3 && !ids[0].isEmpty() && !ids[1].isEmpty() && !ids[2].isEmpty(), "Invalid dataset split id %s", partitionChunkId); long version; try { version = Long.parseLong(ids[1]); } catch (NumberFormatException e) { version = Long.MIN_VALUE; } return new PartitionChunkId(partitionChunkId, unescape(ids[0]), version, ids[2]); } private PartitionChunkId(String compoundSplitId, String datasetId, long splitVersion, String splitKey); @JsonCreator static PartitionChunkId of(String partitionChunkId); static PartitionChunkId of(DatasetConfig config, PartitionChunk split, long splitVersion); static PartitionChunkId of(DatasetConfig config, PartitionChunkMetadata partitionChunkMetadata, long splitVersion); @JsonValue String getSplitId(); @JsonIgnore String getDatasetId(); @JsonIgnore long getSplitVersion(); @JsonIgnore String getSplitIdentifier(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(PartitionChunkId that); @Override String toString(); static SearchQuery getSplitsQuery(DatasetConfig datasetConfig); static SearchQuery getSplitsQuery(EntityId datasetId, long splitVersion); static Range<PartitionChunkId> getCurrentSplitRange(DatasetConfig datasetConfig); static Range<PartitionChunkId> getSplitRange(EntityId datasetId, long splitVersion); static Range<PartitionChunkId> getSplitRange(EntityId datasetId, long startSplitVersion, long endSplitVersion); static LegacyFindByRange<PartitionChunkId> getSplitsRange(DatasetConfig datasetConfig); static LegacyFindByRange<PartitionChunkId> getSplitsRange(EntityId datasetId, long splitVersionId); static boolean mayRequireNewDatasetId(DatasetConfig config); static LegacyFindByRange<PartitionChunkId> unsafeGetSplitsRange(DatasetConfig config); } | @Test public void testInvalidIdFromString() throws Exception { try { PartitionChunkId split = PartitionChunkId.of("ds1_1"); fail("ds1_1 is an invalid dataset split id"); } catch (IllegalArgumentException e) { } try { PartitionChunkId split = PartitionChunkId.of("ds2_2_"); fail("ds2_2_ is an invalid dataset split id"); } catch (IllegalArgumentException e) { } } |
FileFormat { public String toTableOptions() throws IllegalArgumentException { final StringBuilder stringBuilder = new StringBuilder(); switch (getFileType()) { case TEXT: case CSV: case TSV: case PSV: final TextFileConfig textFileConfig = (TextFileConfig)this; stringBuilder.append("type => 'text', "); stringBuilder.append(format("fieldDelimiter => %s, ", SqlUtils.stringLiteral(textFileConfig.getFieldDelimiter()))); stringBuilder.append(format("comment => %s, ", SqlUtils.stringLiteral(singleChar(textFileConfig.getComment())))); stringBuilder.append(format("%1$sescape%1$s => %2$s, ", SqlUtils.QUOTE, SqlUtils.stringLiteral(singleChar(textFileConfig.getEscape())))); stringBuilder.append(format("quote => %s, ", SqlUtils.stringLiteral(singleChar(textFileConfig.getQuote())))); stringBuilder.append(format("lineDelimiter => %s, ", SqlUtils.stringLiteral(textFileConfig.getLineDelimiter()))); stringBuilder.append(format("extractHeader => %s, ", textFileConfig.getExtractHeader().toString())); stringBuilder.append(format("skipFirstLine => %s, ", textFileConfig.getSkipFirstLine().toString())); stringBuilder.append(format("autoGenerateColumnNames => %s, ", textFileConfig.getAutoGenerateColumnNames().toString())); stringBuilder.append(format("trimHeader => %s", textFileConfig.getTrimHeader().toString())); return stringBuilder.toString(); case JSON: return "type => 'json'"; case PARQUET: return "type => 'parquet'"; case ICEBERG: return "type => 'iceberg'"; case AVRO: return "type => 'avro'"; case HTTP_LOG: case UNKNOWN: throw new UnsupportedOperationException("HTTP LOG and UNKNOWN file formats are not supported"); case EXCEL: { final ExcelFileConfig excelFileConfig = (ExcelFileConfig) this; stringBuilder.append("type => 'excel', "); if (excelFileConfig.getSheetName() != null) { stringBuilder.append(format("sheet => %s, ", SqlUtils.stringLiteral(excelFileConfig.getSheetName()))); } stringBuilder.append(format("extractHeader => %s, ", excelFileConfig.getExtractHeader().toString())); stringBuilder.append(format("hasMergedCells => %s, ", excelFileConfig.getHasMergedCells().toString())); stringBuilder.append(format("xls => false ")); return stringBuilder.toString(); } case XLS: { final XlsFileConfig xlsFileConfig = (XlsFileConfig) this; stringBuilder.append("type => 'excel', "); if (xlsFileConfig.getSheetName() != null) { stringBuilder.append(format("sheet => %s, ", SqlUtils.stringLiteral(xlsFileConfig.getSheetName()))); } stringBuilder.append(format("extractHeader => %s, ", xlsFileConfig.getExtractHeader().toString())); stringBuilder.append(format("hasMergedCells => %s, ", xlsFileConfig.getHasMergedCells().toString())); stringBuilder.append(format("xls => true ")); return stringBuilder.toString(); } default: throw new IllegalArgumentException("Invalid file format type " + getFileType()); } } @Override String toString(); String toTableOptions(); String getName(); String getOwner(); boolean getIsFolder(); void setIsFolder(boolean isFolder); String getLocation(); List<String> getFullPath(); long getCtime(); String getVersion(); void setName(String name); void setOwner(String owner); void setFullPath(List<String> fullPath); void setCtime(long ctime); void setVersion(String version); void setLocation(String location); @JsonIgnore @SuppressWarnings({ "rawtypes", "unchecked" }) FileConfig asFileConfig(); @JsonIgnore FileType getFileType(); static FileFormat getForFile(FileConfig fileConfig); static FileFormat getForFolder(FileConfig fileConfig); static FileFormat getEmptyConfig(FileType type); static String getExtension(FileType type); static FileType getFileFormatType(List<String> extensions); } | @Test public void testDefaultTextFileFormatOptions() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'text'", tableOptions); assertContains("fieldDelimiter => ','", tableOptions); assertContains("comment => '#'", tableOptions); assertContains("\"escape\" => '\"'", tableOptions); assertContains("quote => '\"'", tableOptions); assertContains("lineDelimiter => '\r\n'", tableOptions); assertContains("extractHeader => false", tableOptions); assertContains("skipFirstLine => false", tableOptions); assertContains("autoGenerateColumnNames => true", tableOptions); }
@Test public void testLineDelimiterTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setLineDelimiter("\t"); String tableOptions = fileFormat.toTableOptions(); assertContains("lineDelimiter => '\t'", tableOptions); }
@Test public void testLineDelimiterTextFileWithSingleQuote() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setLineDelimiter("'a"); String tableOptions = fileFormat.toTableOptions(); assertContains("lineDelimiter => '''a'", tableOptions); }
@Test public void testCommentTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setComment("$"); String tableOptions = fileFormat.toTableOptions(); assertContains("comment => '$'", tableOptions); }
@Test public void testEscapeTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setEscape("\\"); String tableOptions = fileFormat.toTableOptions(); assertContains("\"escape\" => '\\", tableOptions); }
@Test public void testQuoteTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setQuote("\""); String tableOptions = fileFormat.toTableOptions(); assertContains("quote => '\"'", tableOptions); }
@Test public void testSingleQuoteTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setQuote("'"); String tableOptions = fileFormat.toTableOptions(); assertContains("quote => ''''", tableOptions); }
@Test public void testFieldDelimiterTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setFieldDelimiter("@"); String tableOptions = fileFormat.toTableOptions(); assertContains("fieldDelimiter => '@'", tableOptions); }
@Test public void testExtractHeaderTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setExtractHeader(true); String tableOptions = fileFormat.toTableOptions(); assertContains("extractHeader => true", tableOptions); }
@Test public void testsetSkipFirstLineTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setSkipFirstLine(true); String tableOptions = fileFormat.toTableOptions(); assertContains("skipFirstLine => true", tableOptions); }
@Test public void testAutoGenerateColumnNamesTextFile() throws Exception { TextFileConfig fileFormat = new TextFileConfig(); fileFormat.setAutoGenerateColumnNames(false); String tableOptions = fileFormat.toTableOptions(); assertContains("autoGenerateColumnNames => false", tableOptions); }
@Test public void testDefaultJsonFileFormatOptions() throws Exception { JsonFileConfig fileFormat = new JsonFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'json'", tableOptions); }
@Test public void testDefaultParquetFileFormatOptions() throws Exception { ParquetFileConfig fileFormat = new ParquetFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'parquet'", tableOptions); }
@Test public void testDefaultAvroFileFormatOptions() throws Exception { AvroFileConfig fileFormat = new AvroFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'avro'", tableOptions); }
@Test public void testDefaultExcelFileFormatOptions() throws Exception { ExcelFileConfig fileFormat = new ExcelFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("extractHeader => false", tableOptions); assertContains("hasMergedCells => false", tableOptions); assertContains("xls => false", tableOptions); }
@Test public void testDefaultXlsFileFormatOptions() throws Exception { XlsFileConfig fileFormat = new XlsFileConfig(); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("extractHeader => false", tableOptions); assertContains("hasMergedCells => false", tableOptions); assertContains("xls => true", tableOptions); }
@Test public void testSheetExcelFile() throws Exception { ExcelFileConfig fileFormat = new ExcelFileConfig(); fileFormat.setSheetName("foo"); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => false", tableOptions); assertContains("sheet => 'foo'", tableOptions); }
@Test public void testSheetExcelFileWithSingleQuote() throws Exception { ExcelFileConfig fileFormat = new ExcelFileConfig(); fileFormat.setSheetName("fo'o"); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => false", tableOptions); assertContains("sheet => 'fo''o'", tableOptions); }
@Test public void testSheetXlsFile() throws Exception { XlsFileConfig fileFormat = new XlsFileConfig(); fileFormat.setSheetName("foo"); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => true", tableOptions); assertContains("sheet => 'foo'", tableOptions); }
@Test public void testExtractHeaderExcelFile() throws Exception { ExcelFileConfig fileFormat = new ExcelFileConfig(); fileFormat.setExtractHeader(true); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => false", tableOptions); assertContains("extractHeader => true", tableOptions); }
@Test public void testHasMergedCellsExcelFile() throws Exception { ExcelFileConfig fileFormat = new ExcelFileConfig(); fileFormat.setHasMergedCells(true); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => false", tableOptions); assertContains("hasMergedCells => true", tableOptions); }
@Test public void testExtractHeaderXlsFile() throws Exception { XlsFileConfig fileFormat = new XlsFileConfig(); fileFormat.setExtractHeader(true); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => true", tableOptions); assertContains("extractHeader => true", tableOptions); }
@Test public void testHasMergedCellsXlsFile() throws Exception { XlsFileConfig fileFormat = new XlsFileConfig(); fileFormat.setHasMergedCells(true); String tableOptions = fileFormat.toTableOptions(); assertContains("type => 'excel'", tableOptions); assertContains("xls => true", tableOptions); assertContains("hasMergedCells => true", tableOptions); } |
DateUtils { public static LocalDate fromEpochMillis(final long epochMillis) { return Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC).toLocalDate(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); } | @Test public void testFromEpochMillis() { LocalDate extractedDate = DateUtils.fromEpochMillis(System.currentTimeMillis()); assertEquals(LocalDate.now(), extractedDate); } |
DatasetStateMutator { public TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn) { return apply(oldCol, newCol, newExp.wrap(), dropSourceColumn); } DatasetStateMutator(String username, VirtualDatasetState virtualDatasetState, boolean preview); void setSql(QueryMetadata metadata); void addColumn(int index, Column column); void addColumn(Column column); void moveColumn(int index, int dest); int columnCount(); void addJoin(Join join); void updateColumnTables(); String uniqueColumnName(String column); String getDatasetAlias(); void groupedBy(List<Column> newColumns, List<Column> groupBys); void addFilter(Filter filter); void setOrdersList(List<Order> columnsList); TransformResult result(); int indexOfCol(String colName); void nest(); TransformResult rename(String oldCol, String newCol); TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn); TransformResult apply(String oldCol, String newCol, Expression newExpWrapped, boolean dropSourceColumn); Expression findColValueForModification(String colName); Expression findColValue(String colName); boolean isGrouped(); void dropColumn(String droppedColumnName); } | @Test public void testMutatorApplyNoDropNonPreview() { boolean preview = false; TransformResult result = mutator(preview).apply("foo", "foo2", newValue, false); assertEquals(newHashSet("foo2"), result.getAddedColumns()); assertEquals(newHashSet(), result.getModifiedColumns()); assertEquals(newHashSet(), result.getRemovedColumns()); assertColIs(newValue, result, "foo2"); assertColIs(value, result, "foo"); }
@Test public void testMutatorApplyReplaceNonPreview() { boolean preview = false; TransformResult result1 = mutator(preview).apply("foo", "foo", newValue, true); assertEquals(newHashSet(), result1.getAddedColumns()); assertEquals(newHashSet("foo"), result1.getModifiedColumns()); assertEquals(newHashSet(), result1.getRemovedColumns()); assertColIs(null, result1, "foo2"); assertColIs(newValue, result1, "foo"); }
@Test public void testMutatorApplyDropNonPreview() { boolean preview = false; TransformResult result2 = mutator(preview).apply("foo", "foo2", newValue, true); assertEquals(newHashSet("foo2"), result2.getAddedColumns()); assertEquals(newHashSet(), result2.getModifiedColumns()); assertEquals(newHashSet("foo"), result2.getRemovedColumns()); assertColIs(null, result2, "foo"); assertColIs(newValue, result2, "foo2"); }
@Test public void testMutatorApplyNoDropPreview() { boolean preview = true; TransformResult result = mutator(preview).apply("foo", "foo2", newValue, false); assertEquals(newHashSet("foo2"), result.getAddedColumns()); assertEquals(newHashSet(), result.getModifiedColumns()); assertEquals(newHashSet(), result.getRemovedColumns()); assertColIs(newValue, result, "foo2"); assertColIs(value, result, "foo"); }
@Test public void testMutatorApplyReplacePreview() { boolean preview = true; TransformResult result1 = mutator(preview).apply("foo", "foo", newValue, true); assertEquals(newHashSet("foo (new)"), result1.getAddedColumns()); assertEquals(newHashSet(), result1.getModifiedColumns()); assertEquals(newHashSet("foo"), result1.getRemovedColumns()); assertColIs(null, result1, "foo2"); assertColIs(value, result1, "foo"); assertColIs(newValue, result1, "foo (new)"); }
@Test public void testMutatorApplyDropPreview() { boolean preview = true; TransformResult result2 = mutator(preview).apply("foo", "foo2", newValue, true); assertEquals(newHashSet("foo2"), result2.getAddedColumns()); assertEquals(newHashSet(), result2.getModifiedColumns()); assertEquals(newHashSet("foo"), result2.getRemovedColumns()); assertColIs(value, result2, "foo"); assertColIs(newValue, result2, "foo2"); } |
PathUtils { public static final String join(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part:parts) { Preconditions.checkNotNull(part, "parts cannot contain null"); if (!Strings.isNullOrEmpty(part)) { sb.append(part).append("/"); } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } final String path = sb.toString(); return normalize(path); } static final String join(final String... parts); static final String normalize(final String path); } | @Test(expected = NullPointerException.class) public void testNullSegmentThrowsNPE() { PathUtils.join("", null, ""); }
@Test public void testJoinPreservesAbsoluteOrRelativePaths() { final String actual = PathUtils.join("/a", "/b", "/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.join("/a", "b", "c"); final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.join("a", "b", "c"); final String expected3 = "a/b/c"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.join("a", "", "c"); final String expected4 = "a/c"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.join("", "", "c"); final String expected5 = "c"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.join("", "", ""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); final String actual7 = PathUtils.join("", "", "/"); final String expected7 = "/"; Assert.assertEquals("invalid path", expected7, actual7); final String actual8 = PathUtils.join("", "", "c/"); final String expected8 = "c/"; Assert.assertEquals("invalid path", expected8, actual8); } |
PathUtils { public static final String normalize(final String path) { if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) { return path; } final StringBuilder builder = new StringBuilder(); char last = path.charAt(0); builder.append(last); for (int i=1; i<path.length(); i++) { char cur = path.charAt(i); if (last == '/' && cur == last) { continue; } builder.append(cur); last = cur; } return builder.toString(); } static final String join(final String... parts); static final String normalize(final String path); } | @Test public void testNormalizeRemovesRedundantForwardSlashes() { final String actual = PathUtils.normalize("/a/b/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.normalize(" final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.normalize(" final String expected3 = "/"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.normalize("/a"); final String expected4 = "/a"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.normalize(" final String expected5 = "/"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.normalize(""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); } |
QueueProcessor implements AutoCloseable { public QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer) { this.name = name; this.lockSupplier = lockSupplier; this.consumer = consumer; this.queue = new LinkedBlockingQueue<>(); this.workerThread = null; this.isClosed = false; this.completed = true; } QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer); void enqueue(T event); void start(); @VisibleForTesting boolean completed(); void close(); } | @Test public void testQueueProcessor() throws Exception { Pointer<Long> counter = new Pointer<>(0L); final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); Lock readLock = rwlock.readLock(); Lock writeLock = rwlock.writeLock(); QueueProcessor<Long> qp = new QueueProcessor<>("queue-processor", () -> new AutoCloseableLock(writeLock).open(), (i) -> counter.value += i); qp.start(); final long totalCount = 100_000; final long numBatches = 10; final long batchCount = totalCount / numBatches; for (long i = 0; i < totalCount; i++) { qp.enqueue(new Long(i)); if (i % batchCount == (batchCount - 1)) { Thread.sleep(1); } } final long timeout = 5_000; long loopCount = 0; long expectedValue = totalCount * (totalCount - 1) / 2; while (getValue(counter, readLock) != expectedValue) { Thread.sleep(1); assertTrue(String.format("Timed out after %d ms", timeout), loopCount++ < timeout); } qp.close(); } |
JmxConfigurator extends ReporterConfigurator { @Override public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) { reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build(); reporter.start(); } @JsonCreator JmxConfigurator(
@JsonProperty("rate") TimeUnit rateUnit,
@JsonProperty("duration") TimeUnit durationUnit); @Override void configureAndStart(String name, MetricRegistry registry, MetricFilter filter); @Override int hashCode(); @Override boolean equals(Object other); @Override void close(); } | @Test public void testConfigureAndStart() throws IOException, InterruptedException, MalformedObjectNameException { final MetricRegistry metrics = new MetricRegistry(); metrics.counter(NAME, () -> { Counter counter = new Counter(); counter.inc(1234); return counter; }); final JmxConfigurator configurator = new JmxConfigurator(TimeUnit.SECONDS, TimeUnit.MILLISECONDS); configurator.configureAndStart("test", metrics, new MetricFilter() { @Override public boolean matches(String s, Metric metric) { return true; } }); final Set<ObjectInstance> beans = ManagementFactory.getPlatformMBeanServer().queryMBeans(new ObjectName(OBJECT_NAME), null); assertEquals(1, beans.size()); assertEquals(OBJECT_NAME, beans.iterator().next().getObjectName().getCanonicalName()); } |
LocalSchedulerService implements SchedulerService { @Override public void close() throws Exception { LOGGER.info("Stopping SchedulerService"); AutoCloseables.close(AutoCloseables.iter(executorService), taskLeaderElectionServiceMap.values()); LOGGER.info("Stopped SchedulerService"); } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); } | @Test public void close() throws Exception { final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); final LocalSchedulerService service = new LocalSchedulerService(executorService, null, null, false); service.close(); verify(executorService).close(); } |
LocalSchedulerService implements SchedulerService { @VisibleForTesting public CloseableSchedulerThreadPool getExecutorService() { return executorService; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); } | @Test public void newThread() { LocalSchedulerService service = new LocalSchedulerService(1); final Runnable runnable = mock(Runnable.class); final Thread thread = service.getExecutorService().getThreadFactory().newThread(runnable); assertTrue("thread should be a daemon thread", thread.isDaemon()); assertTrue("thread name should start with scheduler-", thread.getName().startsWith("scheduler-")); } |
LocalSchedulerService implements SchedulerService { @Override public Cancellable schedule(Schedule schedule, Runnable task) { if (!assumeTaskLeadership) { return plainSchedule(schedule, task); } if (!schedule.isDistributedSingleton()) { return plainSchedule(schedule, task); } final TaskLeaderElection taskLeaderElection = getTaskLeaderElection(schedule); CancellableTask cancellableTask = new CancellableTask(schedule, task, schedule.getTaskName()); taskLeaderElection.getTaskLeader(); taskLeaderElection.addListener(cancellableTask.taskLeaderChangeListener); if (taskLeaderElection.isTaskLeader()) { cancellableTask.scheduleNext(); } else { cancellableTask.taskState = true; } return cancellableTask; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); } | @Test public void schedule() throws Exception { final List<MockScheduledFuture<?>> futures = Lists.newArrayList(); final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); doAnswer(new Answer<ScheduledFuture<Object>>() { @Override public ScheduledFuture<Object> answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); MockScheduledFuture<Object> result = new MockScheduledFuture<>(Clock.systemUTC(), Executors.callable((Runnable) arguments[0]), (long) arguments[1], (TimeUnit) arguments[2]); futures.add(result); return result; } }).when(executorService).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); final AtomicInteger runCount = new AtomicInteger(0); final Runnable runnable = new Runnable() { @Override public void run() { runCount.incrementAndGet(); } }; @SuppressWarnings("resource") final SchedulerService service = new LocalSchedulerService(executorService, null, null, false); @SuppressWarnings("unused") final Cancellable cancellable = service.schedule(Schedule.Builder.everyHours(1).build(), runnable); ImmutableList<MockScheduledFuture<?>> copyOfFutures = ImmutableList.copyOf(futures); for(MockScheduledFuture<?> future: copyOfFutures) { future.call(); } assertEquals(2, futures.size()); assertTrue("1st future should be completed", futures.get(0).isDone()); assertFalse("2nd future should still be pending", futures.get(1).isDone()); assertTrue("1st future delay should be shorted than 2nd future delay", futures.get(0).compareTo(futures.get(1)) < 0); assertEquals(1, runCount.get()); }
@Test public void scheduleCancelledBeforeRun() throws Exception { final List<MockScheduledFuture<?>> futures = Lists.newArrayList(); final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); doAnswer(new Answer<ScheduledFuture<Object>>() { @Override public ScheduledFuture<Object> answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); MockScheduledFuture<Object> result = new MockScheduledFuture<>(Clock.systemUTC(), Executors.callable((Runnable) arguments[0]), (long) arguments[1], (TimeUnit) arguments[2]); futures.add(result); return result; } }).when(executorService).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); final AtomicInteger runCount = new AtomicInteger(0); final Runnable runnable = new Runnable() { @Override public void run() { runCount.incrementAndGet(); } }; @SuppressWarnings("resource") final SchedulerService service = new LocalSchedulerService(executorService, null, null, false); final Cancellable cancellable = service.schedule(Schedule.Builder.everyHours(1).build(), runnable); cancellable.cancel(true); ImmutableList<MockScheduledFuture<?>> copyOfFutures = ImmutableList.copyOf(futures); for(MockScheduledFuture<?> future: copyOfFutures) { try { future.call(); } catch (IllegalStateException e) { } } assertTrue("Cancellable should have been cancelled", cancellable.isCancelled()); assertEquals(1, futures.size()); assertTrue("1st future should be completed", futures.get(0).isDone()); assertEquals(0, runCount.get()); } |
IncludesExcludesFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (includes.isEmpty() || matches(name, includes)) { return allowedViaExcludes(name); } return false; } IncludesExcludesFilter(List<String> includes, List<String> excludes); @Override boolean matches(String name, Metric metric); @Override int hashCode(); @Override boolean equals(Object other); } | @Test public void onlyExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList("a.*")); assertFalse(f.matches("alpha", null)); assertTrue(f.matches("beta", null)); }
@Test public void onlyInclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList()); assertTrue(f.matches("alpha", null)); assertFalse(f.matches("beta", null)); }
@Test public void includeAndExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList("a\\.b.*")); assertTrue(f.matches("a.alpha", null)); assertFalse(f.matches("a.beta", null)); }
@Test public void noValues() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList()); assertTrue(f.matches(null, null)); } |
MutableVarcharVector extends BaseVariableWidthVector { @Override public void close() { this.clear(); } MutableVarcharVector(String name, BufferAllocator allocator, double compactionThreshold); MutableVarcharVector(String name, FieldType fieldType, BufferAllocator allocator, double compactionThreshold); final void setCompactionThreshold(double in); final boolean needsCompaction(); final int getCurrentOffset(); final int getGarbageSizeInBytes(); final int getUsedByteCapacity(); @Override FieldReader getReader(); @Override MinorType getMinorType(); void zeroVector(); void reset(); @Override void close(); @Override void clear(); byte[] get(int index); Text getObject(int index); void get(int index, NullableVarCharHolder holder); void copyFrom(int fromIndex, int thisIndex, VarCharVector from); void copyFromSafe(int fromIndex, int thisIndex, VarCharVector from); void compact(); void forceCompact(); void set(int index, VarCharHolder holder); void setSafe(int index, VarCharHolder holder); void set(int index, NullableVarCharHolder holder); void setSafe(int index, NullableVarCharHolder holder); void set(int index, Text text); void setSafe(int index, Text text); void set(int index, byte[] value); void setSafe(int index, byte[] value); void set(int index, byte[] value, int start, int length); void setSafe(int index, byte[] value, int start, int length); void set(int index, ByteBuffer value, int start, int length); void setSafe(int index, ByteBuffer value, int start, int length); void set(int index, int isSet, int start, int end, ArrowBuf buffer); void setSafe(int index, int isSet, int start, int end, ArrowBuf buffer); void set(int index, int start, int length, ArrowBuf buffer); void setSafe(int index, int start, int length, ArrowBuf buffer); void copyToVarchar(VarCharVector in, final int from, final int to); boolean isIndexSafe(int index); @Override TransferPair getTransferPair(String ref, BufferAllocator allocator); @Override TransferPair makeTransferPair(ValueVector to); } | @Test public void TestInterleavedMidToSmall() { LinkedList<String> l1 = GetRandomStringList(TOTAL_STRINGS, midAvgSize); LinkedList<String> l2 = GetRandomStringList(TOTAL_STRINGS, smallAvgSize); final double threshold = 1.0D; System.out.println("TestInterleavedMidToSmall: threshold: " + threshold + " (only forcecompact)"); MutableVarcharVector m1 = new MutableVarcharVector("TestInterleavedMidToSmall", testAllocator, threshold ); try { TestInterLeaved(m1, l1, l2); } finally { m1.close(); } }
@Test public void TestInterleavedSmallToMid() { LinkedList<String> l1 = GetRandomStringList(TOTAL_STRINGS, smallAvgSize); LinkedList<String> l2 = GetRandomStringList(TOTAL_STRINGS, midAvgSize); final double threshold = 1.0D; System.out.println("TestInterleavedSmallToMid: threshold: " + threshold + " (only forcecompact)"); MutableVarcharVector m1 = new MutableVarcharVector("TestInterleavedSmallToMid", testAllocator, 1.0 ); try { TestInterLeaved(m1, l1, l2); } finally { m1.close(); } } |
UserRPCServer extends BasicServer<RpcType, UserRPCServer.UserClientConnectionImpl> { @Override protected Response handle(UserClientConnectionImpl connection, int rpcType, byte[] pBody, ByteBuf dBody) throws RpcException { throw new IllegalStateException("UserRPCServer#handle must not be invoked without ResponseSender"); } @VisibleForTesting UserRPCServer(
RpcConfig rpcConfig,
Provider<UserService> userServiceProvider,
Provider<NodeEndpoint> nodeEndpointProvider,
WorkIngestor workIngestor,
Provider<UserWorker> worker,
BufferAllocator allocator,
EventLoopGroup eventLoopGroup,
InboundImpersonationManager impersonationManager,
Tracer tracer,
OptionValidatorListing optionValidatorListing
); UserRPCServer(
RpcConfig rpcConfig,
Provider<UserService> userServiceProvider,
Provider<NodeEndpoint> nodeEndpointProvider,
Provider<UserWorker> worker,
BufferAllocator allocator,
EventLoopGroup eventLoopGroup,
InboundImpersonationManager impersonationManager,
Tracer tracer,
OptionValidatorListing optionValidatorListing
); @Override UserClientConnectionImpl initRemoteConnection(SocketChannel channel); } | @Test public void testHandlePassesNoopTracesByDefault() throws RpcException { setup(false); server.handle(connection, GET_CATALOGS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_CATALOGS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); verifySendResponse(0); }
@Test public void testHandleCreatesSpansFromTracerWhenTracingEnabled() throws RpcException { setup(true); server.handle(connection, GET_SCHEMAS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_SCHEMAS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); verifySendResponse(1); assertEquals("GET_SCHEMAS", tracer.finishedSpans().get(0).tags().get("rpc_type")); }
@Test public void testHandleSpansWhileSendingFailure() throws RpcException { setup(true); server.handle(connection, GET_CATALOGS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_CATALOGS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); UserRpcException r = mock(UserRpcException.class); verifyZeroInteractions(responseSender); captorSender.getValue().sendFailure(r); verify(responseSender).sendFailure(r); assertEquals(1, tracer.finishedSpans().size()); assertEquals("GET_CATALOGS", tracer.finishedSpans().get(0).tags().get("rpc_type")); }
@Test public void testHandleFinishesSpanIfFeedFailure() throws RpcException { WorkIngestor ingest = (con, rpc, pb, db, sender) -> { throw new RpcException(); }; setup(ingest, true); try { server.handle(connection, CANCEL_QUERY_VALUE, pBody, dBody, responseSender); } catch (RpcException e) { } assertEquals(1, tracer.finishedSpans().size()); assertEquals("CANCEL_QUERY", tracer.finishedSpans().get(0).tags().get("rpc_type")); } |
QueriesClerk { QueriesClerk(final WorkloadTicketDepot workloadTicketDepot) { this.workloadTicketDepot = workloadTicketDepot; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo,
final QueryStarter queryStarter); FragmentTicket newFragmentTicket(final QueryTicket queryTicket, final PlanFragmentFull fragment, final SchedulingInfo schedulingInfo); } | @Test public void testQueriesClerk() throws Exception{ WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); assertLivePhasesCount(clerk, 0); int baseNumAllocators = getNumAllocators(); UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder().setPart1(12).setPart2(23).build(); QueryTicketGetter qtg1 = new QueryTicketGetter(); clerk.buildAndStartQuery(getDummyPlan(queryId,1,0), getDummySchedulingInfo(), qtg1); QueryTicket queryTicket = qtg1.getObtainedTicket(); assertNotNull(queryTicket); assertLivePhasesCount(clerk, 0); assertEquals(baseNumAllocators + 1, getNumAllocators()); FragmentTicket ticket10 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,1,0), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); FragmentTicket ticket11 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,1,1), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); FragmentTicket ticket20 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,2,0), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 2); assertEquals(baseNumAllocators + 3, getNumAllocators()); qtg1.close(); assertEquals(baseNumAllocators + 3, getNumAllocators()); ticket10.close(); assertLivePhasesCount(clerk, 2); assertEquals(baseNumAllocators + 3, getNumAllocators()); ticket20.close(); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); ticket11.close(); assertLivePhasesCount(clerk, 0); assertEquals(baseNumAllocators, getNumAllocators()); AutoCloseables.close(ticketDepot); } |
QueriesClerk { Collection<FragmentTicket> getFragmentTickets(QueryId queryId) { List<FragmentTicket> fragmentTickets = new ArrayList<>(); for (WorkloadTicket workloadTicket : getWorkloadTickets()) { QueryTicket queryTicket = workloadTicket.getQueryTicket(queryId); if (queryTicket != null) { for (PhaseTicket phaseTicket : queryTicket.getActivePhaseTickets()) { fragmentTickets.addAll(phaseTicket.getFragmentTickets()); } break; } } return fragmentTickets; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo,
final QueryStarter queryStarter); FragmentTicket newFragmentTicket(final QueryTicket queryTicket, final PlanFragmentFull fragment, final SchedulingInfo schedulingInfo); } | @Test public void testGetFragmentTickets() throws Exception { WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder().setPart1(12).setPart2(23).build(); QueryTicketGetter qtg1 = new QueryTicketGetter(); clerk.buildAndStartQuery(getDummyPlan(queryId,1,0), getDummySchedulingInfo(), qtg1); QueryTicket queryTicket = qtg1.getObtainedTicket(); assertNotNull(queryTicket); Set<FragmentTicket> expected = new HashSet<>(); int numMajors = 3; int numMinors = 5; for (int i = 0; i < numMajors; ++i) { for (int j = 0; j < numMinors; ++j) { FragmentTicket fragmentTicket = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId, i, j), getDummySchedulingInfo()); expected.add(fragmentTicket); } } qtg1.close(); Collection<FragmentTicket> actual = clerk.getFragmentTickets(queryId); assertEquals(expected.size(), actual.size()); assertTrue(expected.containsAll(actual)); for (FragmentTicket ticket : expected) { ticket.close(); } AutoCloseables.close(ticketDepot); } |
ThreadsStatsCollector extends Thread implements AutoCloseable { public Integer getCpuTrailingAverage(long id, int seconds) { return cpuStat.getTrailingAverage(id, seconds); } ThreadsStatsCollector(Set<Long> slicingThreadIds); ThreadsStatsCollector(long collectionIntervalInMilliSeconds, Set<Long> slicingThreadIds); @Override void run(); Integer getCpuTrailingAverage(long id, int seconds); Integer getUserTrailingAverage(long id, int seconds); void close(); } | @Test public void testOldThreadsArePruned() throws InterruptedException { Thread t = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; Thread t1 = new Thread() { public void run () { try { sleep(400l); } catch (InterruptedException e) { } } }; t.start(); t1.start(); ThreadsStatsCollector collector = new ThreadsStatsCollector(50L, Sets.newHashSet(t1.getId())); collector.start(); sleep(200l); Integer stat = collector.getCpuTrailingAverage(t.getId(), 1); Integer statThread2 = collector.getCpuTrailingAverage(t1.getId(), 1); Assert.assertTrue(stat == null); Assert.assertTrue(statThread2 != null); t.join(); t1.join(); stat = collector.getCpuTrailingAverage(t.getId(), 1); Assert.assertTrue(stat == null); } |
VectorizedHashJoinOperator implements DualInputOperator { @VisibleForTesting void sendRuntimeFilterToProbeScan(RuntimeFilter filter, Optional<BloomFilter> partitionColFilter) { logger.debug("Sending join runtime filter to probe scan {}:{}, Filter {}", filter.getProbeScanOperatorId(), filter.getProbeScanMajorFragmentId(), partitionColFilter); logger.debug("Partition col filter fpp {}", partitionColFilter.map(BloomFilter::getExpectedFPP).orElse(-1D)); final MajorFragmentAssignment majorFragmentAssignment = context.getExtMajorFragmentAssignments(filter.getProbeScanMajorFragmentId()); try(ArrowBuf bloomFilterBuf = partitionColFilter.map(bf -> bf.getDataBuffer()).orElse(null)) { if (majorFragmentAssignment==null) { logger.warn("Major fragment assignment for probe scan id {} is null. Dropping the runtime filter.", filter.getProbeScanOperatorId()); return; } for (FragmentAssignment assignment : majorFragmentAssignment.getAllAssignmentList()) { try (RollbackCloseable closeOnErrSend = new RollbackCloseable()) { logger.info("Sending filter to OpId {}, Frag {}:{}", filter.getProbeScanOperatorId(), filter.getProbeScanMajorFragmentId(), assignment.getMinorFragmentIdList()); final OutOfBandMessage message = new OutOfBandMessage( context.getFragmentHandle().getQueryId(), filter.getProbeScanMajorFragmentId(), assignment.getMinorFragmentIdList(), filter.getProbeScanOperatorId(), context.getFragmentHandle().getMajorFragmentId(), context.getFragmentHandle().getMinorFragmentId(), config.getProps().getOperatorId(), new OutOfBandMessage.Payload(filter), bloomFilterBuf, true); closeOnErrSend.add(bloomFilterBuf); final NodeEndpoint endpoint = context.getEndpointsIndex().getNodeEndpoint(assignment.getAssignmentIndex()); context.getTunnelProvider().getExecTunnel(endpoint).sendOOBMessage(message); closeOnErrSend.commit(); } catch (Exception e) { logger.warn("Error while sending runtime filter to minor fragments " + assignment.getMinorFragmentIdList(), e); } } } } VectorizedHashJoinOperator(OperatorContext context, HashJoinPOP popConfig); @Override State getState(); VectorAccessible setup(VectorAccessible left, VectorAccessible right); @Override void consumeDataRight(int records); @Override void noMoreToConsumeRight(); @Override void consumeDataLeft(int records); @Override int outputData(); @Override void noMoreToConsumeLeft(); ArrowBuf newLinksBuffer(int recordCount); @Override OUT accept(OperatorVisitor<OUT, IN, EXCEP> visitor, IN value); @Override void workOnOOB(OutOfBandMessage message); @Override void close(); static final int BATCH_MASK; } | @Test public void testSendRuntimeFilterToProbeScan() { int probeScanId = 2; int probeOpId = 131074; int buildMajorFragment = 1; int buildMinorFragment = 2; int buildOpId = 65541; QueryId queryId = QueryId.newBuilder().build(); try (ArrowBuf recvBuffer = bfTestAllocator.buffer(64)) { recvBuffer.setBytes(0, new byte[64]); FragmentHandle fh = FragmentHandle.newBuilder() .setQueryId(queryId).setMajorFragmentId(buildMajorFragment).setMinorFragmentId(buildMinorFragment).build(); TunnelProvider tunnelProvider = mock(TunnelProvider.class); AccountingExecTunnel tunnel = mock(AccountingExecTunnel.class); doNothing().when(tunnel).sendOOBMessage(any(OutOfBandMessage.class)); when(tunnelProvider.getExecTunnel(any(NodeEndpoint.class))).thenReturn(tunnel); OperatorContext opCtx = mockOpContext(fh); EndpointsIndex ei = mock(EndpointsIndex.class); NodeEndpoint node1 = NodeEndpoint.newBuilder().build(); when(ei.getNodeEndpoint(any(Integer.class))).thenReturn(node1); when(opCtx.getEndpointsIndex()).thenReturn(ei); when(opCtx.getTunnelProvider()).thenReturn(tunnelProvider); HashJoinPOP popConfig = mockPopConfig(newRuntimeFilterInfo(false, "col1")); OpProps props = mock(OpProps.class); when(props.getOperatorId()).thenReturn(buildOpId); when(popConfig.getProps()).thenReturn(props); VectorizedHashJoinOperator joinOp = spy(new VectorizedHashJoinOperator(opCtx, popConfig)); BloomFilter bloomFilter = mockedBloom().get(); when(bloomFilter.getDataBuffer()).thenReturn(recvBuffer); when(bloomFilter.getExpectedFPP()).thenReturn(0.001D); RuntimeFilter filter = RuntimeFilter.newBuilder() .setProbeScanMajorFragmentId(probeScanId) .setProbeScanOperatorId(probeOpId) .setPartitionColumnFilter(ExecProtos.CompositeColumnFilter.newBuilder() .addColumns("col1") .setFilterType(ExecProtos.RuntimeFilterType.BLOOM_FILTER) .setSizeBytes(64).build()) .build(); FragmentAssignment assignment1 = FragmentAssignment.newBuilder() .addAllMinorFragmentId(Lists.newArrayList(1, 3, 5)).setAssignmentIndex(1).build(); FragmentAssignment assignment2 = FragmentAssignment.newBuilder() .addAllMinorFragmentId(Lists.newArrayList(0, 2, 4)).setAssignmentIndex(2).build(); MajorFragmentAssignment majorFragmentAssignment = MajorFragmentAssignment.newBuilder() .setMajorFragmentId(probeScanId) .addAllAllAssignment(Lists.newArrayList(assignment1, assignment2)) .build(); when(opCtx.getExtMajorFragmentAssignments(eq(probeScanId))).thenReturn(majorFragmentAssignment); ArgumentCaptor<OutOfBandMessage> oobMessageCaptor = ArgumentCaptor.forClass(OutOfBandMessage.class); joinOp.sendRuntimeFilterToProbeScan(filter, Optional.of(bloomFilter)); verify(tunnel, times(2)).sendOOBMessage(oobMessageCaptor.capture()); for (int assignment = 0; assignment <= 1; assignment++) { assertEquals(queryId, oobMessageCaptor.getAllValues().get(assignment).getQueryId()); assertEquals(probeScanId, oobMessageCaptor.getAllValues().get(assignment).getMajorFragmentId()); assertEquals(probeOpId, oobMessageCaptor.getAllValues().get(assignment).getOperatorId()); assertEquals(buildMajorFragment, oobMessageCaptor.getAllValues().get(assignment).getSendingMajorFragmentId()); assertEquals(buildMinorFragment, oobMessageCaptor.getAllValues().get(assignment).getSendingMinorFragmentId()); } assertEquals(Lists.newArrayList(1,3,5), oobMessageCaptor.getAllValues().get(0).getTargetMinorFragmentIds()); assertEquals(Lists.newArrayList(0,2,4), oobMessageCaptor.getAllValues().get(1).getTargetMinorFragmentIds()); assertEquals(2, recvBuffer.refCnt()); recvBuffer.close(); } }
@Test public void testSendRuntimeFilterToProbeScanMajorFragmentNotPresent() { int probeScanId = 2; int differentProbeScanId = 5; int probeOpId = 131074; int buildMajorFragment = 1; int buildMinorFragment = 2; int buildOpId = 65541; QueryId queryId = QueryId.newBuilder().build(); ArrowBuf recvBuffer = bfTestAllocator.buffer(64); FragmentHandle fh = FragmentHandle.newBuilder() .setQueryId(queryId).setMajorFragmentId(buildMajorFragment).setMinorFragmentId(buildMinorFragment).build(); TunnelProvider tunnelProvider = mock(TunnelProvider.class); AccountingExecTunnel tunnel = mock(AccountingExecTunnel.class); doNothing().when(tunnel).sendOOBMessage(any(OutOfBandMessage.class)); when(tunnelProvider.getExecTunnel(any(NodeEndpoint.class))).thenReturn(tunnel); OperatorContext opCtx = mockOpContext(fh); EndpointsIndex ei = mock(EndpointsIndex.class); NodeEndpoint node1 = NodeEndpoint.newBuilder().build(); when(ei.getNodeEndpoint(any(Integer.class))).thenReturn(node1); when(opCtx.getEndpointsIndex()).thenReturn(ei); when(opCtx.getTunnelProvider()).thenReturn(tunnelProvider); HashJoinPOP popConfig = mockPopConfig(newRuntimeFilterInfo(false, "col1")); OpProps props = mock(OpProps.class); when(props.getOperatorId()).thenReturn(buildOpId); when(popConfig.getProps()).thenReturn(props); VectorizedHashJoinOperator joinOp = spy(new VectorizedHashJoinOperator(opCtx, popConfig)); BloomFilter bloomFilter = mockedBloom().get(); when(bloomFilter.getDataBuffer()).thenReturn(recvBuffer); when(bloomFilter.getExpectedFPP()).thenReturn(0.001D); RuntimeFilter filter = RuntimeFilter.newBuilder() .setProbeScanMajorFragmentId(probeScanId) .setProbeScanOperatorId(probeOpId) .setPartitionColumnFilter(ExecProtos.CompositeColumnFilter.newBuilder() .addColumns("col1") .setFilterType(ExecProtos.RuntimeFilterType.BLOOM_FILTER) .setSizeBytes(64).build()) .build(); FragmentAssignment assignment1 = FragmentAssignment.newBuilder() .addAllMinorFragmentId(Lists.newArrayList(1, 3, 5)).setAssignmentIndex(1).build(); FragmentAssignment assignment2 = FragmentAssignment.newBuilder() .addAllMinorFragmentId(Lists.newArrayList(0, 2, 4)).setAssignmentIndex(2).build(); MajorFragmentAssignment majorFragmentAssignment = MajorFragmentAssignment.newBuilder() .setMajorFragmentId(differentProbeScanId) .addAllAllAssignment(Lists.newArrayList(assignment1, assignment2)) .build(); when(opCtx.getExtMajorFragmentAssignments(eq(differentProbeScanId))).thenReturn(majorFragmentAssignment); when(opCtx.getExtMajorFragmentAssignments(eq(probeScanId))).thenReturn(null); ArgumentCaptor<OutOfBandMessage> oobMessageCaptor = ArgumentCaptor.forClass(OutOfBandMessage.class); joinOp.sendRuntimeFilterToProbeScan(filter, Optional.of(bloomFilter)); verify(tunnel, never()).sendOOBMessage(oobMessageCaptor.capture()); } |
MatchBitSet implements AutoCloseable { public void set(final int index) { final int wordNum = index >>> LONG_TO_BITS_SHIFT; final int bit = index & BIT_OFFSET_MUSK; final long bitMask = 1L << bit; final long wordAddr = bufferAddr + wordNum * BYTES_PER_WORD; PlatformDependent.putLong(wordAddr, PlatformDependent.getLong(wordAddr) | bitMask); } MatchBitSet(final int numBits, final BufferAllocator allocator); void set(final int index); boolean get(final int index); int nextUnSetBit(final int index); int cardinality(); @Override void close(); } | @Test public void randomBits() throws Exception { final int count = 8*1024*1024; BitSet bitSet = new BitSet(count); final Random rand = new Random(); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i ++) { int val = rand.nextInt(10); if (val > 3) { bitSet.set(i); matchBitSet.set(i); } } validateBits(matchBitSet, bitSet, count); } }
@Test public void fullBits() throws Exception { final int count = 256*1024; BitSet bitSet = new BitSet(count); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i++) { bitSet.set(i); matchBitSet.set(i); } validateBits(matchBitSet, bitSet, count); } }
@Test public void specifiedBits() throws Exception { final int count = 256*1024 + 13; BitSet bitSet = new BitSet(count); try (MatchBitSet matchBitSet = new MatchBitSet(count, allocator)) { for (int i = 0; i < count; i += WORD_BITS) { if ((i / WORD_BITS) % 3 == 0) { for (int j = 0; j < WORD_BITS; j++) { bitSet.set(i + j); matchBitSet.set(i + j); } } else if ((i / WORD_BITS) % 3 == 1) { for (int j = 0; j < WORD_BITS; j++) { if (j % 3 == 0) { bitSet.set(i + j); matchBitSet.set(i + j); } } } else { } } validateBits(matchBitSet, bitSet, count); } } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.