src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ApplicationServiceImpl implements ApplicationService { @Transactional @Override public Application createApplication(final CreateApplicationRequest createApplicationRequest, final User aCreatingUser) { createApplicationRequest.validate(); return applicationPersistenceService.createApplication(createApplicationRequest); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @SuppressWarnings("unchecked") @Test(expected = BadRequestException.class) public void testCreateBadRequest() { when(Config.applicationPersistenceService.createApplication(any(CreateApplicationRequest.class))).thenReturn(Config.mockApplication2); CreateApplicationRequest cac = new CreateApplicationRequest(Identifier.id(1L, Group.class), "", "", true, true, false); Application created = applicationService.createApplication(cac, new User("user")); assertTrue(created == Config.mockApplication2); }
@SuppressWarnings("unchecked") @Test public void testCreate() { when(Config.applicationPersistenceService.createApplication(any(CreateApplicationRequest.class))).thenReturn(Config.mockApplication2); CreateApplicationRequest cac = new CreateApplicationRequest(Identifier.id(1L, Group.class), "wan", "/wan", true, true, false); Application created = applicationService.createApplication(cac, new User("user")); assertTrue(created == Config.mockApplication2); } |
ApplicationServiceImpl implements ApplicationService { @Transactional @Override public Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser) throws ApplicationServiceException{ updateApplicationRequest.validate(); final Application application = applicationPersistenceService.updateApplication(updateApplicationRequest); String appName = application.getName(); Identifier<Group> newGroupId = application.getGroup().getId(); Long id = newGroupId.getId(); List<Long> idList = Collections.singletonList(id); List<JpaGroup> jpaGroups = groupPersistenceService.findGroups(idList); if (jpaGroups.size() == 1) { JpaApplication jpaApp = applicationPersistenceService.getJpaApplication(appName); if (null != jpaApp.getWarName()) { resourceDao.updateResourceGroup(jpaApp, jpaGroups.get(0)); } } else { throw new ApplicationServiceException("One Jpa Group expected for the application."); } updateApplicationWarMetaData(updateApplicationRequest, application); return application; } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @SuppressWarnings("unchecked") @Test public void testUpdate() throws ApplicationServiceException, IOException { when(Config.applicationPersistenceService.updateApplication(any(UpdateApplicationRequest.class))) .thenReturn(Config.mockApplication2); Group group = mock(Group.class); when(Config.mockApplication2.getName()).thenReturn("test-app-name"); when(Config.mockApplication2.getWarName()).thenReturn("test-war-name"); when(Config.mockApplication2.getGroup()).thenReturn(group); when(group.getName()).thenReturn("group1"); long id = 22; JpaGroup jpaGroup = mock(JpaGroup.class); when(group.getId()).thenReturn(new Identifier<Group>(id)); List<Long> listOfIds = new ArrayList<>(); listOfIds.add((long) 22); List<JpaGroup> jpaGroups = new ArrayList<>(); jpaGroups.add(jpaGroup); when(Config.mockGroupPersistenceService.findGroups(listOfIds)).thenReturn(jpaGroups); JpaApplication jpaApplication = mock(JpaApplication.class); when(Config.applicationPersistenceService.getJpaApplication(Config.mockApplication2.getName())).thenReturn (jpaApplication); when(Config.mockGroupPersistenceService.getGroupAppResourceTemplateMetaData("group1", "test-war-name", "test-app-names")) .thenReturn ("{\"templateName\":\"test-template-name\", \"contentType\":\"application/zip\", \"deployFileName\":\"test-app.war\", \"deployPath\":\"/fake/deploy/path\", \"entity\":{}, \"unpack\":\"true\", \"overwrite\":\"true\"}"); when(Config.mockResourceService.getMetaData(anyString())).thenReturn(new ResourceTemplateMetaData("test-template-name", MediaType.APPLICATION_ZIP, "deploy-file-name", "deploy-path", null, true, false, null)); UpdateApplicationRequest cac = new UpdateApplicationRequest(Config.mockApplication2.getId(), Identifier.id(1L, Group.class), "wan", "/wan", true, true, false); Application created = applicationService.updateApplication(cac, new User("user")); assertTrue(created == Config.mockApplication2); verify(Config.mockGroupPersistenceService).updateGroupAppResourceMetaData(anyString(), anyString(), anyString(), anyString()); } |
ApplicationServiceImpl implements ApplicationService { @Transactional @Override public void removeApplication(Identifier<Application> anAppIdToRemove, User user) { applicationPersistenceService.removeApplication(anAppIdToRemove); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @SuppressWarnings("unchecked") @Test public void testRemove() { applicationService.removeApplication(Config.mockApplication.getId(), testUser); verify(Config.applicationPersistenceService, Mockito.times(1)).removeApplication(Mockito.any(Identifier.class)); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional(readOnly = true) public List<String> getResourceTemplateNames(final String appName, final String jvmName) { return applicationPersistenceService.getResourceTemplateNames(appName, jvmName); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testGetResourceTemplateNames() { final String[] nameArray = {"hct.xml"}; when(Config.applicationPersistenceService.getResourceTemplateNames(eq("hct"), anyString())).thenReturn(Arrays.asList(nameArray)); final List names = applicationService.getResourceTemplateNames("hct", "any"); assertEquals("hct.xml", names.get(0)); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName) { return applicationPersistenceService.updateResourceTemplate(appName, resourceTemplateName, template, jvmName, groupName); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testUpdateResourceTemplate() { applicationService.updateResourceTemplate("hct", "hct.xml", "content", "jvm1", "group1"); verify(Config.applicationPersistenceService).updateResourceTemplate(eq("hct"), eq("hct.xml"), eq("content"), eq("jvm1"), eq("group1")); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public CommandOutput deployConf(final String appName, final String groupName, final String jvmName, final String resourceTemplateName, ResourceGroup resourceGroup, User user) { String lockKey = generateKey(groupName, jvmName, appName, resourceTemplateName); try { binaryDistributionLockManager.writeLock(lockKey); ResourceIdentifier resourceIdentifier = new ResourceIdentifier.Builder() .setResourceName(resourceTemplateName) .setGroupName(groupName) .setWebAppName(appName) .setJvmName(jvmName) .build(); final Jvm jvm = jvmPersistenceService.findJvmByExactName(jvmName); checkJvmStateBeforeDeploy(jvm, resourceIdentifier); String hostName = jvm.getHostName(); Group group = groupPersistenceService.getGroup(groupName); historyFacadeService.write(hostName, group, "Deploying application resource " + resourceTemplateName, EventType.USER_ACTION_INFO, user.getId()); return resourceService.generateAndDeployFile(resourceIdentifier, appName + "-" + jvmName, resourceTemplateName, jvm.getHostName()); } catch (ResourceFileGeneratorException e) { LOGGER.error("Fail to generate the resource file {}", resourceTemplateName, e); throw new DeployApplicationConfException(e); } finally { binaryDistributionLockManager.writeUnlock(lockKey); } } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testDeployConf() throws CommandFailureException, IOException { final Jvm jvm = mock(Jvm.class); when(jvm.getHostName()).thenReturn("localhost"); when(jvm.getState()).thenReturn(JvmState.JVM_STOPPED); when(Config.jvmPersistenceService.findJvmByExactName(eq("jvm-1"))).thenReturn(jvm); final CommandOutput execData = mock(CommandOutput.class); when(execData.getReturnCode()).thenReturn(new ExecReturnCode(0)); when(Config.applicationPersistenceService.getResourceTemplate(eq("hct"), eq("hct.xml"), eq("jvm-1"), eq("hct-group"))).thenReturn("Test template"); when(Config.applicationPersistenceService.findApplication(eq("hct"), eq("hct-group"), eq("jvm-1"))).thenReturn(Config.mockApplication); when(Config.applicationPersistenceService.getMetaData(anyString(), anyString(), anyString(), anyString())).thenReturn(META_DATA_TEST_VALUES); when(Config.jvmPersistenceService.findJvm(eq("jvm-1"), eq("hct-group"))).thenReturn(jvm); ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class); when(mockMetaData.getDeployFileName()).thenReturn("hct.xml"); when(mockMetaData.getDeployPath()).thenReturn("./test/deploy-path/conf/CatalinaSSL/localhost"); when(mockMetaData.getContentType()).thenReturn(MediaType.APPLICATION_XML); when(Config.mockResourceService.getTokenizedMetaData(anyString(), any(Object.class), anyString())).thenReturn(mockMetaData); when(Config.mockResourceService.generateResourceFile(anyString(), anyString(), any(ResourceGroup.class), any(), any(ResourceGeneratorType.class))).thenReturn("{\"deployPath\":\"./test/deploy-path/conf/CatalinaSSL/localhost\",\"contentType\":\"text/xml\",\"entity\":{\"type\":\"APPLICATION\",\"target\":\"soarcom-hct\",\"group\":\"soarcom-616\",\"parentName\":null,\"deployToJvms\":true},\"templateName\":\"hctXmlTemplate.tpl\",\"deployFileName\":\"hct.xml\"}"); when(Config.mockResourceService.generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString())).thenReturn(execData); when(mockMetaData.isHotDeploy()).thenReturn(false); when(Config.mockResourceService.getResourceContent(any(ResourceIdentifier.class))).thenReturn(new ResourceContent("{\"test\":\"meta data\"}", "test resource content")); when(Config.mockResourceService.getTokenizedMetaData(anyString(), anyObject(), anyString())).thenReturn(mockMetaData); CommandOutput retExecData = applicationService.deployConf("hct", "hct-group", "jvm-1", "hct.xml", mock(ResourceGroup.class), testUser); assertTrue(retExecData.getReturnCode().wasSuccessful()); when(Config.mockApplication.isSecure()).thenReturn(false); retExecData = applicationService.deployConf("hct", "hct-group", "jvm-1", "hct.xml", mock(ResourceGroup.class), testUser); assertTrue(retExecData.getReturnCode().wasSuccessful()); when(Config.mockApplication.isSecure()).thenReturn(true); retExecData = applicationService.deployConf("hct", "hct-group", "jvm-1", "hct.xml", mock(ResourceGroup.class), testUser); assertTrue(retExecData.getReturnCode().wasSuccessful()); when(execData.getReturnCode()).thenReturn(new ExecReturnCode(1)); when(execData.getStandardError()).thenReturn("REMOTE COMMAND FAILURE"); try { applicationService.deployConf("hct", "hct-group", "jvm-1", "hct.xml", mock(ResourceGroup.class), testUser); } catch (DeployApplicationConfException ee) { assertEquals("REMOTE COMMAND FAILURE", ee.getMessage()); } try { applicationService.deployConf("hct", "hct-group", "jvm-1", "hct.xml", mock(ResourceGroup.class), testUser); } catch (DeployApplicationConfException ee) { assertTrue(ee.getCause() instanceof CommandFailureException); } }
@Test(expected = InternalErrorException.class) public void testDeployConfJvmNotStopped() throws IOException { reset(Config.jvmPersistenceService, Config.applicationPersistenceService, Config.mockResourceService); Jvm mockJvm = mock(Jvm.class); when(mockJvm.getState()).thenReturn(JvmState.JVM_STARTED); when(Config.jvmPersistenceService.findJvmByExactName(anyString())).thenReturn(mockJvm); when(Config.jvmPersistenceService.findJvm(anyString(), anyString())).thenReturn(mockJvm); when(Config.applicationPersistenceService.findApplication(anyString(), anyString(), anyString())).thenReturn(Config.mockApplication); when(Config.applicationPersistenceService.getResourceTemplate(anyString(), anyString(), anyString(), anyString())).thenReturn("IGNORED CONTENT"); ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class); when(mockMetaData.isHotDeploy()).thenReturn(false); when(Config.mockResourceService.getResourceContent(any(ResourceIdentifier.class))).thenReturn(new ResourceContent("{\"test\":\"meta data\"}", "test resource content")); when(Config.mockResourceService.getTokenizedMetaData(anyString(), anyObject(), anyString())).thenReturn(mockMetaData); applicationService.deployConf("testApp", "testGroup", "testJvm", "HttpSslConfTemplate.tpl", mock(ResourceGroup.class), testUser); verify(Config.mockResourceService, never()).generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString()); }
@Test public void testDeployConfJvmNotStoppedAndHotDeploy() throws IOException { Jvm mockJvm = mock(Jvm.class); when(mockJvm.getState()).thenReturn(JvmState.JVM_STARTED); when(mockJvm.getJvmName()).thenReturn("jvm-name"); when(Config.jvmPersistenceService.findJvmByExactName(anyString())).thenReturn(mockJvm); when(Config.jvmPersistenceService.findJvm(anyString(), anyString())).thenReturn(mockJvm); when(Config.applicationPersistenceService.findApplication(anyString(), anyString(), anyString())).thenReturn(Config.mockApplication); when(Config.applicationPersistenceService.getResourceTemplate(anyString(), anyString(), anyString(), anyString())).thenReturn("IGNORED CONTENT"); ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class); when(mockMetaData.isHotDeploy()).thenReturn(true); when(Config.mockResourceService.getResourceContent(any(ResourceIdentifier.class))).thenReturn(new ResourceContent("{\"test\":\"meta data\"}", "test resource content")); when(Config.mockResourceService.getTokenizedMetaData(anyString(), anyObject(), anyString())).thenReturn(mockMetaData); applicationService.deployConf("testApp", "testGroup", "testJvm", "HttpSslConfTemplate.tpl", mock(ResourceGroup.class), testUser); verify(Config.mockResourceService).generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString()); }
@Test(expected = ApplicationServiceException.class) public void testDeployConfJvmNotStoppedAndHotDeployThrowsException() throws IOException { Jvm mockJvm = mock(Jvm.class); when(mockJvm.getState()).thenReturn(JvmState.JVM_STARTED); when(mockJvm.getJvmName()).thenReturn("jvm-name"); when(Config.jvmPersistenceService.findJvmByExactName(anyString())).thenReturn(mockJvm); when(Config.jvmPersistenceService.findJvm(anyString(), anyString())).thenReturn(mockJvm); when(Config.applicationPersistenceService.findApplication(anyString(), anyString(), anyString())).thenReturn(Config.mockApplication); when(Config.applicationPersistenceService.getResourceTemplate(anyString(), anyString(), anyString(), anyString())).thenReturn("IGNORED CONTENT"); ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class); when(mockMetaData.isHotDeploy()).thenReturn(true); when(Config.mockResourceService.getResourceContent(any(ResourceIdentifier.class))).thenReturn(new ResourceContent("{\"test\":\"meta data\"}", "test resource content")); when(Config.mockResourceService.getTokenizedMetaData(anyString(), anyObject(), anyString())).thenThrow(new IOException("FAIL THIS TEST")); applicationService.deployConf("testApp", "testGroup", "testJvm", "HttpSslConfTemplate.tpl", mock(ResourceGroup.class), testUser); verify(Config.mockResourceService, never()).generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString()); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup) { Application application; if (StringUtils.isNotEmpty(jvmName)) { application = applicationPersistenceService.findApplication(appName, groupName, jvmName); application.setParentJvm(jvmPersistenceService.findJvmByExactName(jvmName)); } else { application = getApplication(appName); } return resourceService.generateResourceFile(fileName, template, resourceGroup, application, ResourceGeneratorType.PREVIEW); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testPreviewResourceTemplate() { final Jvm jvm = mock(Jvm.class); when(Config.applicationPersistenceService.findApplication(eq("hct"), eq("hct-group"), eq("jvm-1"))).thenReturn(Config.mockApplication); when(Config.jvmPersistenceService.findJvm(eq("jvm-1"), eq("hct-group"))).thenReturn(jvm); final String preview = applicationService.previewResourceTemplate("myFile", "hct", "hct-group", "jvm-1", "Template contents", new ResourceGroup()); verify(Config.mockResourceService).generateResourceFile(anyString(), anyString(), any(ResourceGroup.class), any(Application.class), any(ResourceGeneratorType.class)); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest) { uploadAppTemplateRequest.validate(); Jvm jvm = jvmPersistenceService.findJvmByExactName(uploadAppTemplateRequest.getJvmName()); JpaJvm jpaJvm = jvmPersistenceService.getJpaJvm(jvm.getId(), false); return applicationPersistenceService.uploadAppTemplate(uploadAppTemplateRequest, jpaJvm); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testUploadTemplate() { final UploadAppTemplateRequest cmd = mock(UploadAppTemplateRequest.class); when(cmd.getConfFileName()).thenReturn("roleMapping.properties"); when(cmd.getJvmName()).thenReturn("testJvmName"); Jvm mockJvm = mock(Jvm.class); when(mockJvm.getId()).thenReturn(new Identifier<Jvm>(111L)); when(Config.jvmPersistenceService.findJvmByExactName(anyString())).thenReturn(mockJvm); JpaJvm mockJpaJvm = mock(JpaJvm.class); when(Config.jvmPersistenceService.getJpaJvm(any(Identifier.class), anyBoolean())).thenReturn(mockJpaJvm); applicationService.uploadAppTemplate(cmd); verify(cmd).validate(); verify(Config.applicationPersistenceService).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class)); List<Jvm> jvmList = new ArrayList<>(); jvmList.add(mockJvm); when(mockJvm.getJvmName()).thenReturn("testJvmName"); when(cmd.getConfFileName()).thenReturn("hct.xml"); applicationService.uploadAppTemplate(cmd); verify(cmd, times(2)).validate(); verify(Config.applicationPersistenceService, times(2)).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class)); when(mockJvm.getJvmName()).thenReturn("notTestJvmName"); applicationService.uploadAppTemplate(cmd); verify(cmd, times(3)).validate(); verify(Config.applicationPersistenceService, times(3)).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class)); } |
ApplicationServiceImpl implements ApplicationService { @Transactional(readOnly = true) @Override public List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId) { return applicationPersistenceService.findApplicationsBelongingToJvm(jvmId); } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testFindApplicationsByJvmId() { final Identifier<Jvm> id = new Identifier<Jvm>(1l); applicationService.findApplicationsByJvmId(id); verify(Config.applicationPersistenceService).findApplicationsBelongingToJvm(eq(id)); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public void copyApplicationWarToGroupHosts(Application application) { Group group = groupPersistenceService.getGroup(application.getGroup().getId()); final Set<Jvm> theJvms = group.getJvms(); if (theJvms != null && !theJvms.isEmpty()) { Set<String> hostNames = new HashSet<>(); for (Jvm jvm : theJvms) { final String host = jvm.getHostName().toLowerCase(Locale.US); if (!hostNames.contains(host)) { hostNames.add(host); } } copyAndExecuteCommand(application, hostNames); } } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testCopyApplicationWarToGroupHosts() throws IOException { Jvm mockJvm = mock(Jvm.class); when(mockJvm.getHostName()).thenReturn("mock-hostname"); Group mockGroup = mock(Group.class); when(mockGroup.getId()).thenReturn(new Identifier<Group>(999L)); when(mockGroup.getJvms()).thenReturn(Collections.singleton(mockJvm)); Application mockApplicationForCopy = mock(Application.class); when(mockApplicationForCopy.getGroup()).thenReturn(mockGroup); when(mockApplicationForCopy.getWarPath()).thenReturn("./src/test/resources/archive/test_archive.war"); when(mockApplicationForCopy.getWarName()).thenReturn("mock-application-war-name"); when(mockApplicationForCopy.getName()).thenReturn("mock-application-name"); when(mockApplicationForCopy.isUnpackWar()).thenReturn(false); when(Config.mockGroupPersistenceService.getGroup(any(Identifier.class))).thenReturn(mockGroup); when(Config.binaryDistributionControlService.createDirectory(anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Create directory succeeded", "")); when(Config.binaryDistributionControlService.secureCopyFile(anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Secure copy succeeded", "")); ResourceTemplateMetaData mockResourceTemplateMetaData = mock(ResourceTemplateMetaData.class); when(mockResourceTemplateMetaData.getDeployPath()).thenReturn("C:/deploy/path"); when(Config.mockResourceService.getResourceContent(any(ResourceIdentifier.class))).thenReturn(new ResourceContent("C:/deploy/path", "content")); when(Config.mockResourceService.getTokenizedMetaData(anyString(), any(Application.class), anyString())).thenReturn(mockResourceTemplateMetaData); applicationService.copyApplicationWarToGroupHosts(mockApplicationForCopy); verify(Config.binaryDistributionService, never()).distributeUnzip(anyString()); }
@Test public void testCopyApplicationWarToGroupHostsAndUnpack() { reset(Config.binaryDistributionControlService); Jvm mockJvm = mock(Jvm.class); when(mockJvm.getHostName()).thenReturn("mock-hostname"); Group mockGroup = mock(Group.class); when(mockGroup.getId()).thenReturn(new Identifier<Group>(999L)); when(mockGroup.getJvms()).thenReturn(Collections.singleton(mockJvm)); Application mockApplicationForCopy = mock(Application.class); when(mockApplicationForCopy.getGroup()).thenReturn(mockGroup); when(mockApplicationForCopy.getWarPath()).thenReturn("./src/test/resources/archive/test_archive.war"); when(mockApplicationForCopy.getWarName()).thenReturn("mock-application-war-name"); when(mockApplicationForCopy.getName()).thenReturn("mock-application-name"); when(mockApplicationForCopy.isUnpackWar()).thenReturn(true); when(Config.mockGroupPersistenceService.getGroup(any(Identifier.class))).thenReturn(mockGroup); when(Config.binaryDistributionControlService.createDirectory(anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Create directory succeeded", "")); when(Config.binaryDistributionControlService.secureCopyFile(anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Secure copy succeeded", "")); when(Config.binaryDistributionControlService.changeFileMode(anyString(), anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Change file mode succeeded", "")); when(Config.binaryDistributionControlService.checkFileExists(anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "File exists succeeded", "")); when(Config.binaryDistributionControlService.backupFileWithMove(anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Backup succeeded", "")); when(Config.binaryDistributionControlService.unzipBinary(anyString(), anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Unzip succeeded", "")); applicationService.copyApplicationWarToGroupHosts(mockApplicationForCopy); verify(Config.binaryDistributionControlService, times(1)).unzipBinary(anyString(), anyString(), anyString(), anyString()); } |
ApplicationServiceImpl implements ApplicationService { @Override @Transactional public void copyApplicationWarToHost(Application application, String hostName) { if (hostName != null && !hostName.isEmpty()) { Set<String> hostNames = new HashSet<>(); hostNames.add(hostName); copyAndExecuteCommand(application, hostNames); } } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testCopyApplicationWarToHost() { Jvm mockJvm = mock(Jvm.class); when(mockJvm.getHostName()).thenReturn("mock-hostname"); Group mockGroup = mock(Group.class); when(mockGroup.getId()).thenReturn(new Identifier<Group>(999L)); when(mockGroup.getJvms()).thenReturn(Collections.singleton(mockJvm)); Application mockApplicationForCopy = mock(Application.class); when(mockApplicationForCopy.getGroup()).thenReturn(mockGroup); when(mockApplicationForCopy.getWarPath()).thenReturn("./src/test/resources/archive/test_archive.war"); when(mockApplicationForCopy.getWarName()).thenReturn("mock-application-war-name"); when(mockApplicationForCopy.getName()).thenReturn("mock-application-name"); when(mockApplicationForCopy.isUnpackWar()).thenReturn(false); when(Config.mockGroupPersistenceService.getGroup(any(Identifier.class))).thenReturn(mockGroup); when(Config.binaryDistributionControlService.createDirectory(anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Create directory succeeded", "")); when(Config.binaryDistributionControlService.secureCopyFile(anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Secure copy succeeded", "")); applicationService.copyApplicationWarToHost(mockApplicationForCopy, "mock-hostname"); verify(Config.binaryDistributionService, never()).distributeUnzip(anyString()); } |
ApplicationServiceImpl implements ApplicationService { @Override public void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup) { List<String> appResourcesNames = groupPersistenceService.getGroupAppsResourceTemplateNames(groupName); final List<Jvm> jvms = jvmPersistenceService.getJvmsByGroupName(groupName); if (null != appResourcesNames && !appResourcesNames.isEmpty()) { for (String resourceTemplateName : appResourcesNames) { String metaDataStr = groupPersistenceService.getGroupAppResourceTemplateMetaData(groupName, resourceTemplateName, app.getName()); try { ResourceTemplateMetaData metaData = resourceService.getTokenizedMetaData(resourceTemplateName, app, metaDataStr); if (jvms != null && !jvms.isEmpty() && !metaData.getEntity().getDeployToJvms()) { Set<String> hostNames = new HashSet<>(); for (Jvm jvm : jvms) { final String host = jvm.getHostName().toLowerCase(Locale.US); if (!hostNames.contains(host)) { hostNames.add(host); executeDeployGroupAppTemplate(groupName, resourceTemplateName, app, jvm.getHostName()); } } } } catch (IOException e) { LOGGER.error("Failed to map meta data for template {} in group {}", resourceTemplateName, groupName, e); throw new InternalErrorException(FaultType.BAD_STREAM, "Failed to read meta data for template " + resourceTemplateName + " in group " + groupName, e); } } } } ApplicationServiceImpl(final ApplicationPersistenceService applicationPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final GroupPersistenceService groupPersistenceService,
final ResourceService resourceService,
final BinaryDistributionService binaryDistributionService,
final HistoryFacadeService historyFacadeService,
final BinaryDistributionLockManager binaryDistributionLockManager); @Transactional(readOnly = true) @Override Application getApplication(Identifier<Application> aApplicationId); @Transactional(readOnly = true) @Override Application getApplication(final String name); @Transactional(readOnly = true) @Override List<Application> getApplications(); @Transactional(readOnly = true) @Override List<Application> findApplications(Identifier<Group> groupId); @Transactional(readOnly = true) @Override List<Application> findApplicationsByJvmId(Identifier<Jvm> jvmId); @Transactional @Override Application updateApplication(UpdateApplicationRequest updateApplicationRequest, User anUpdatingUser); @Transactional @Override Application createApplication(final CreateApplicationRequest createApplicationRequest,
final User aCreatingUser); @Transactional @Override void removeApplication(Identifier<Application> anAppIdToRemove, User user); @Override @Transactional(readOnly = true) List<String> getResourceTemplateNames(final String appName, final String jvmName); @Override @Transactional String updateResourceTemplate(final String appName, final String resourceTemplateName, final String template, final String jvmName, final String groupName); @Override @Transactional // TODO: Have an option to do a hot deploy or not. CommandOutput deployConf(final String appName, final String groupName, final String jvmName,
final String resourceTemplateName, ResourceGroup resourceGroup, User user); @Override @Transactional JpaApplicationConfigTemplate uploadAppTemplate(UploadAppTemplateRequest uploadAppTemplateRequest); @Override @Transactional String previewResourceTemplate(String fileName, String appName, String groupName, String jvmName, String template, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToGroupHosts(Application application); @Override void deployApplicationResourcesToGroupHosts(String groupName, Application app, ResourceGroup resourceGroup); @Override @Transactional void copyApplicationWarToHost(Application application, String hostName); @Override void deployConf(final String appName, final String hostName, final User user); } | @Test public void testDeployApplicationResourcesToGroupHosts() throws IOException { reset(Config.mockResourceService); Jvm mockJvm = mock(Jvm.class); when(mockJvm.getHostName()).thenReturn("mock-hostname"); Group mockGroup = mock(Group.class); when(mockGroup.getName()).thenReturn("mock-group-name"); when(mockGroup.getId()).thenReturn(new Identifier<Group>(999L)); Application mockApplicationForDeploy = mock(Application.class); when(mockApplicationForDeploy.getGroup()).thenReturn(mockGroup); when(mockApplicationForDeploy.getWarPath()).thenReturn("./src/test/resources/archive/test_archive.war"); when(mockApplicationForDeploy.getWarName()).thenReturn("mock-application-war-name"); when(mockApplicationForDeploy.getName()).thenReturn("mock-application-name"); when(mockApplicationForDeploy.isUnpackWar()).thenReturn(false); ResourceGroup mockResourceGroup = mock(ResourceGroup.class); Entity mockEntity = mock(Entity.class); when(mockEntity.getDeployToJvms()).thenReturn(false); ResourceTemplateMetaData mockResourceTemplateMetaData = mock(ResourceTemplateMetaData.class); when(mockResourceTemplateMetaData.getEntity()).thenReturn(mockEntity); when(Config.mockGroupPersistenceService.getGroupAppsResourceTemplateNames(anyString())).thenReturn(Collections.singletonList("mock-application-resource")); when(Config.mockGroupPersistenceService.getGroupAppResourceTemplateMetaData(anyString(), anyString(), anyString())).thenReturn("{\"fake\":\"meta-data\"}"); when(Config.mockResourceService.getTokenizedMetaData(anyString(), anyObject(), anyString())).thenReturn(mockResourceTemplateMetaData); when(Config.mockResourceService.generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString())).thenReturn(new CommandOutput(new ExecReturnCode(0), "Generate and deploy succeeded", "")); when(Config.jvmPersistenceService.getJvmsByGroupName(anyString())).thenReturn(Collections.singletonList(mockJvm)); applicationService.deployApplicationResourcesToGroupHosts("mock-group-name", mockApplicationForDeploy, mockResourceGroup); verify(Config.mockResourceService, times(1)).generateAndDeployFile(any(ResourceIdentifier.class), anyString(), anyString(), anyString()); } |
WebServerResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) { if (canHandle(resourceIdentifier)) { return webServerPersistenceService.updateResourceMetaData(resourceIdentifier.webServerName, resourceName, metaData); } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } WebServerResourceHandler(final ResourceDao resourceDao,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; when(mockWebServerPersistence.updateResourceMetaData(anyString(), anyString(), anyString())).thenReturn(updatedMetaData); webServerResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockWebServerPersistence).updateResourceMetaData(eq(resourceIdentifier.webServerName), eq(resourceName), eq(updatedMetaData)); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-webserver").build(); webServerResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
WebServerResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return webServerPersistenceService.findWebServerByName(resourceIdentifier.webServerName); } else { return successor.getSelectedValue(resourceIdentifier); } } WebServerResourceHandler(final ResourceDao resourceDao,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { WebServer mockWebServer = mock(WebServer.class); when(mockWebServerPersistence.findWebServerByName(anyString())).thenReturn(mockWebServer); WebServer webServer = (WebServer) webServerResourceHandler.getSelectedValue(resourceIdentifier); assertEquals(mockWebServer, webServer); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("webserver-resource").setGroupName("not-a-webserver").build(); webServerResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
WebServerResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return webServerPersistenceService.getResourceTemplateNames(resourceIdentifier.webServerName); } else { return successor.getResourceNames(resourceIdentifier); } } WebServerResourceHandler(final ResourceDao resourceDao,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetResourceNames() { webServerResourceHandler.getResourceNames(resourceIdentifier); verify(mockWebServerPersistence).getResourceTemplateNames(anyString()); ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("what-webserver").setGroupName("not-a-web-server").build(); webServerResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); } |
GroupLevelAppResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(final ResourceIdentifier resourceIdentifier, final String resourceName, final String metaData) { if (canHandle(resourceIdentifier)) { final String previousMetaData = groupPersistenceService.getGroupAppResourceTemplateMetaData(resourceIdentifier.groupName, resourceName, resourceIdentifier.webAppName); final String updatedMetaData = groupPersistenceService.updateGroupAppResourceMetaData(resourceIdentifier.groupName, resourceIdentifier.webAppName, resourceName, metaData); updateApplicationUnpackWar(resourceIdentifier.webAppName, resourceName, metaData); updateMetaDataForChildJVMResources(resourceIdentifier, resourceName, metaData); updateAppTemplatesWhenDeployToJvmsChanged(resourceIdentifier, resourceName, previousMetaData, updatedMetaData); return updatedMetaData; } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } GroupLevelAppResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(final ResourceIdentifier resourceIdentifier, final String resourceName, final String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"templateName\":\"test-template-name\", \"contentType\":\"application/zip\", \"deployFileName\":\"test-app.war\", \"deployPath\":\"/fake/deploy/path\", \"entity\":{}, \"unpack\":\"true\", \"overwrite\":\"true\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); Set<Jvm> jvmSet = new HashSet<>(); Jvm mockJvm = mock(Jvm.class); jvmSet.add(mockJvm); when(mockJvm.getJvmName()).thenReturn("mockJvm"); when(mockGroup.getJvms()).thenReturn(jvmSet); when(mockGroup.getName()).thenReturn("test-group-name"); when(mockGroupPersistence.updateGroupAppResourceMetaData(anyString(), anyString(), anyString(), anyString())).thenReturn(updatedMetaData); when(mockGroupPersistence.getGroupAppResourceTemplateMetaData(anyString(), anyString(), anyString())).thenReturn("{\"entity\":{\"deployToJvms\":true}}"); when(mockGroupPersistence.getGroup(anyString())).thenReturn(mockGroup); when(mockAppPersistence.getResourceTemplateNames(anyString(), anyString())).thenReturn(Collections.singletonList(resourceName)); Application mockApplication = mock(Application.class); when(mockApplication.getName()).thenReturn("test-app-name"); when(mockApplication.getId()).thenReturn(new Identifier<Application>(1111L)); when(mockApplication.getGroup()).thenReturn(mockGroup); when(mockApplication.getWebAppContext()).thenReturn("/test-app-context"); when(mockApplication.isLoadBalanceAcrossServers()).thenReturn(true); when(mockApplication.isSecure()).thenReturn(true); when(mockAppPersistence.getApplication(anyString())).thenReturn(mockApplication); groupAppResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockGroupPersistence).updateGroupAppResourceMetaData(eq(resourceIdentifier.groupName), eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData)); verify(mockAppPersistence).updateResourceMetaData(eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData), eq("mockJvm"), eq(resourceIdentifier.groupName)); verify(mockAppPersistence).updateApplication(any(UpdateApplicationRequest.class)); }
@Test public void testUpdateMetaDataSetDeployToJvmsTrue() { reset(mockResourceDao, mockAppPersistence); final String updatedMetaData = "{\"templateName\":\"test-template-name\", \"contentType\":\"application/zip\", \"deployFileName\":\"test-app.war\", \"deployPath\":\"/fake/deploy/path\", \"entity\":{}, \"unpack\":\"true\", \"overwrite\":\"true\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); Set<Jvm> jvmSet = new HashSet<>(); Jvm mockJvm = mock(Jvm.class); jvmSet.add(mockJvm); when(mockJvm.getJvmName()).thenReturn("mockJvm"); when(mockGroup.getJvms()).thenReturn(jvmSet); when(mockGroup.getName()).thenReturn("test-group-name"); when(mockGroupPersistence.updateGroupAppResourceMetaData(anyString(), anyString(), anyString(), anyString())).thenReturn(updatedMetaData); when(mockGroupPersistence.getGroupAppResourceTemplateMetaData(anyString(), anyString(), anyString())).thenReturn("{\"entity\":{\"deployToJvms\":false}}"); when(mockGroupPersistence.getGroup(anyString())).thenReturn(mockGroup); when(mockAppPersistence.getResourceTemplateNames(anyString(), anyString())).thenReturn(Collections.singletonList(resourceName)); JpaJvm mockJpaJvm = mock(JpaJvm.class); when(mockJvmPersistence.getJpaJvm(any(Identifier.class), anyBoolean())).thenReturn(mockJpaJvm); JpaGroupAppConfigTemplate mockGroupAppConfigTemplate = mock(JpaGroupAppConfigTemplate.class); when(mockGroupAppConfigTemplate.getTemplateContent()).thenReturn("some template content"); when(mockResourceDao.getGroupLevelAppResource(anyString(), anyString(), anyString())).thenReturn(mockGroupAppConfigTemplate); Application mockApplication = mock(Application.class); when(mockApplication.getName()).thenReturn("app-name"); when(mockApplication.getId()).thenReturn(new Identifier<Application>(1111L)); when(mockApplication.getGroup()).thenReturn(mockGroup); when(mockApplication.getWebAppContext()).thenReturn("/test-app-context"); when(mockApplication.isLoadBalanceAcrossServers()).thenReturn(true); when(mockApplication.isSecure()).thenReturn(true); when(mockAppPersistence.getApplication(anyString())).thenReturn(mockApplication); when(mockAppPersistence.findApplicationsBelongingTo(anyString())).thenReturn(Collections.singletonList(mockApplication)); groupAppResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockGroupPersistence).updateGroupAppResourceMetaData(eq(resourceIdentifier.groupName), eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData)); verify(mockAppPersistence).updateResourceMetaData(eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData), eq("mockJvm"), eq(resourceIdentifier.groupName)); verify(mockAppPersistence).updateApplication(any(UpdateApplicationRequest.class)); verify(mockResourceDao, never()).deleteAppResource(anyString(), anyString(), anyString()); verify(mockAppPersistence).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class)); }
@Test public void testUpdateMetaDataSetDeployToJvmsFalse() { reset(mockResourceDao, mockAppPersistence); final String updatedMetaData = "{\"templateName\":\"test-template-name\", \"contentType\":\"application/zip\", \"deployFileName\":\"test-app.war\", \"deployPath\":\"/fake/deploy/path\", \"entity\":{\"deployToJvms\":false}, \"unpack\":\"true\", \"overwrite\":\"true\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); Set<Jvm> jvmSet = new HashSet<>(); Jvm mockJvm = mock(Jvm.class); jvmSet.add(mockJvm); when(mockJvm.getJvmName()).thenReturn("mockJvm"); when(mockGroup.getJvms()).thenReturn(jvmSet); when(mockGroup.getName()).thenReturn("test-group-name"); when(mockGroupPersistence.updateGroupAppResourceMetaData(anyString(), anyString(), anyString(), anyString())).thenReturn(updatedMetaData); when(mockGroupPersistence.getGroupAppResourceTemplateMetaData(anyString(), anyString(), anyString())).thenReturn("{\"entity\":{}}"); when(mockGroupPersistence.getGroup(anyString())).thenReturn(mockGroup); when(mockAppPersistence.getResourceTemplateNames(anyString(), anyString())).thenReturn(Collections.singletonList(resourceName)); Application mockApplication = mock(Application.class); when(mockApplication.getName()).thenReturn("app-name"); when(mockApplication.getId()).thenReturn(new Identifier<Application>(1111L)); when(mockApplication.getGroup()).thenReturn(mockGroup); when(mockApplication.getWebAppContext()).thenReturn("/test-app-context"); when(mockApplication.isLoadBalanceAcrossServers()).thenReturn(true); when(mockApplication.isSecure()).thenReturn(true); when(mockAppPersistence.getApplication(anyString())).thenReturn(mockApplication); groupAppResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockGroupPersistence).updateGroupAppResourceMetaData(eq(resourceIdentifier.groupName), eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData)); verify(mockAppPersistence).updateResourceMetaData(eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData), eq("mockJvm"), eq(resourceIdentifier.groupName)); verify(mockAppPersistence).updateApplication(any(UpdateApplicationRequest.class)); verify(mockResourceDao, times(1)).deleteAppResource(eq(resourceName), eq(resourceIdentifier.webAppName), anyString()); verify(mockAppPersistence, never()).uploadAppTemplate(any(UploadAppTemplateRequest.class), any(JpaJvm.class)); }
@Test (expected = GroupLevelAppResourceHandlerException.class) public void testUpdateMetaDataFailsToParseMetaData() { reset(mockResourceDao, mockAppPersistence); final String updatedMetaData = "{\"templateName\":\"test-template-name\", \"contentType\":\"application/zip\", \"deployFileName\":\"test-app.war\", \"deployPath\":\"/fake/deploy/path\", \"entity\":{\"deployToJvms\":false}, \"unpack\":\"true\", \"overwrite\":\"true\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); Set<Jvm> jvmSet = new HashSet<>(); Jvm mockJvm = mock(Jvm.class); jvmSet.add(mockJvm); when(mockJvm.getJvmName()).thenReturn("mockJvm"); when(mockGroup.getJvms()).thenReturn(jvmSet); when(mockGroup.getName()).thenReturn("test-group-name"); when(mockGroupPersistence.updateGroupAppResourceMetaData(anyString(), anyString(), anyString(), anyString())).thenReturn(updatedMetaData); when(mockGroupPersistence.getGroupAppResourceTemplateMetaData(anyString(), anyString(), anyString())).thenReturn("{\"entity\":{},,,}"); when(mockGroupPersistence.getGroup(anyString())).thenReturn(mockGroup); when(mockAppPersistence.getResourceTemplateNames(anyString(), anyString())).thenReturn(Collections.singletonList(resourceName)); Application mockApplication = mock(Application.class); when(mockApplication.getName()).thenReturn("app-name"); when(mockApplication.getId()).thenReturn(new Identifier<Application>(1111L)); when(mockApplication.getGroup()).thenReturn(mockGroup); when(mockApplication.getWebAppContext()).thenReturn("/test-app-context"); when(mockApplication.isLoadBalanceAcrossServers()).thenReturn(true); when(mockApplication.isSecure()).thenReturn(true); when(mockAppPersistence.getApplication(anyString())).thenReturn(mockApplication); groupAppResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-web-app").build(); groupAppResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
GroupLevelAppResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)) { return applicationPersistenceService.getApplication(resourceIdentifier.webAppName); } else { return successor.getSelectedValue(resourceIdentifier); } } GroupLevelAppResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(final ResourceIdentifier resourceIdentifier, final String resourceName, final String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { Object selectedValue = groupAppResourceHandler.getSelectedValue(resourceIdentifier); assertNull(selectedValue); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("whats-app-amiright").setGroupName("not-a-web-app").build(); groupAppResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
GroupLevelAppResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)) { return resourceDao.getGroupLevelAppResourceNames(resourceIdentifier.groupName, resourceIdentifier.webAppName); } else { return successor.getResourceNames(resourceIdentifier); } } GroupLevelAppResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(final ResourceIdentifier resourceIdentifier, final String resourceName, final String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetResourceNames() { groupAppResourceHandler.getResourceNames(resourceIdentifier); verify(mockResourceDao).getGroupLevelAppResourceNames(eq(resourceIdentifier.groupName), eq(resourceIdentifier.webAppName)); ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("whats-app-amiright").setGroupName("not-a-web-app").build(); groupAppResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); } |
AppResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) { if (canHandle(resourceIdentifier)) { return applicationPersistenceService.updateResourceMetaData(resourceIdentifier.webAppName, resourceName, metaData, resourceIdentifier.jvmName, resourceIdentifier.groupName); } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } AppResourceHandler(final ResourceDao resourceDao, final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; when(mockAppPersistence.updateResourceMetaData(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(updatedMetaData); appResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockAppPersistence).updateResourceMetaData(eq(resourceIdentifier.webAppName), eq(resourceName), eq(updatedMetaData), eq(resourceIdentifier.jvmName), eq(resourceIdentifier.groupName)); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-web-app").build(); appResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
AppResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)) { Application application = applicationPersistenceService.getApplication(resourceIdentifier.webAppName); application.setParentJvm(jvmPersistenceService.findJvmByExactName(resourceIdentifier.jvmName)); return application; } else { return successor.getSelectedValue(resourceIdentifier); } } AppResourceHandler(final ResourceDao resourceDao, final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { Application mockApp = mock(Application.class); Jvm mockJvm = mock(Jvm.class); when(mockAppPersistence.getApplication(anyString())).thenReturn(mockApp); when(mockJvmPersistence.findJvmByExactName(anyString())).thenReturn(mockJvm); Application app = (Application) appResourceHandler.getSelectedValue(resourceIdentifier); verify(mockApp).setParentJvm(eq(mockJvm)); assertEquals(mockApp, app); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("whats-app-amiright").setGroupName("not-a-web-app").build(); Application app = (Application) appResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
AppResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)) { return applicationPersistenceService.getResourceTemplateNames(resourceIdentifier.webAppName, resourceIdentifier.jvmName); } else { return successor.getResourceNames(resourceIdentifier); } } AppResourceHandler(final ResourceDao resourceDao, final JvmPersistenceService jvmPersistenceService,
final ApplicationPersistenceService applicationPersistenceService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetResourceNames() { appResourceHandler.getResourceNames(resourceIdentifier); verify(mockAppPersistence).getResourceTemplateNames(anyString(), anyString()); ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("whats-app-amiright").setGroupName("not-a-web-app").build(); appResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); } |
ExternalPropertiesResourceHandler extends ResourceHandler { @Override protected boolean canHandle(ResourceIdentifier resourceIdentifier) { return StringUtils.isNotEmpty(resourceIdentifier.resourceName) && StringUtils.isEmpty(resourceIdentifier.webAppName) && StringUtils.isEmpty(resourceIdentifier.jvmName) && StringUtils.isEmpty(resourceIdentifier.groupName) && StringUtils.isEmpty(resourceIdentifier.webServerName); } ExternalPropertiesResourceHandler(final ResourceDao resourceDao, final ResourceHandler successor); @Override ConfigTemplate fetchResource(ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testCanHandle() { ResourceIdentifier.Builder resourceIdentifier = new ResourceIdentifier.Builder(); resourceIdentifier.setGroupName(null); resourceIdentifier.setWebAppName(null); resourceIdentifier.setJvmName(null); resourceIdentifier.setWebServerName(null); resourceIdentifier.setResourceName("external.properties"); assertTrue(externalPropertiesResourceHandler.canHandle(resourceIdentifier.build())); } |
ExternalPropertiesResourceHandler extends ResourceHandler { @Override public void deleteResource(ResourceIdentifier resourceIdentifier) { throw new UnsupportedOperationException(); } ExternalPropertiesResourceHandler(final ResourceDao resourceDao, final ResourceHandler successor); @Override ConfigTemplate fetchResource(ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test (expected = UnsupportedOperationException.class) public void testDeleteExternalProperties() { ResourceIdentifier.Builder resourceIdentifier = new ResourceIdentifier.Builder(); externalPropertiesResourceHandler.deleteResource(resourceIdentifier.build()); } |
ExternalPropertiesResourceHandler extends ResourceHandler { @Override public ConfigTemplate fetchResource(ResourceIdentifier resourceIdentifier) { ConfigTemplate configTemplate = null; if (canHandle(resourceIdentifier)) { configTemplate = resourceDao.getExternalPropertiesResource(resourceIdentifier.resourceName); } else if (successor != null) { configTemplate = successor.fetchResource(resourceIdentifier); } return configTemplate; } ExternalPropertiesResourceHandler(final ResourceDao resourceDao, final ResourceHandler successor); @Override ConfigTemplate fetchResource(ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testFetchResource() { ResourceIdentifier.Builder resourceIdentifierBuilder = new ResourceIdentifier.Builder(); resourceIdentifierBuilder.setGroupName(null); resourceIdentifierBuilder.setWebAppName(null); resourceIdentifierBuilder.setJvmName(null); resourceIdentifierBuilder.setWebServerName(null); resourceIdentifierBuilder.setResourceName("external.properties"); JpaResourceConfigTemplate mockResourceConfigTemplate = mock(JpaResourceConfigTemplate.class); when(mockResourceDao.getExternalPropertiesResource(eq("external.properties"))).thenReturn(mockResourceConfigTemplate); externalPropertiesResourceHandler.fetchResource(resourceIdentifierBuilder.build()); verify(mockResourceDao).getExternalPropertiesResource(eq("external.properties")); }
@Test public void testFetchResourcePassesOnToSuccessor() { ResourceIdentifier.Builder resourceIdentifierBuilder = new ResourceIdentifier.Builder(); resourceIdentifierBuilder.setGroupName("test-group-name"); resourceIdentifierBuilder.setWebAppName("test-app-name"); resourceIdentifierBuilder.setJvmName(null); resourceIdentifierBuilder.setWebServerName(null); resourceIdentifierBuilder.setResourceName("external.properties"); ConfigTemplate mockResourceConfigTemplate = mock(JpaResourceConfigTemplate.class); when(mockSuccessor.fetchResource(any(ResourceIdentifier.class))).thenReturn(mockResourceConfigTemplate); final ResourceIdentifier resourceId = resourceIdentifierBuilder.build(); externalPropertiesResourceHandler.fetchResource(resourceId); verify(mockSuccessor).fetchResource(eq(resourceId)); } |
ExternalPropertiesResourceHandler extends ResourceHandler { @Override public CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier, final ResourceTemplateMetaData metaData, final String templateContent) { CreateResourceResponseWrapper createResourceResponseWrapper = null; if (canHandle(resourceIdentifier)) { Long entityId = null; Long groupId = null; Long appId = null; EntityType entityType = EntityType.EXT_PROPERTIES; List<String> existingTemplateNames = resourceDao.getResourceNames(resourceIdentifier, EntityType.EXT_PROPERTIES); if (!existingTemplateNames.isEmpty()) { resourceDao.deleteExternalProperties(); ExternalProperties.reset(); } final String deployFileName = metaData.getDeployFileName(); createResourceResponseWrapper = new CreateResourceResponseWrapper(resourceDao.createResource(entityId, groupId, appId, entityType, deployFileName, templateContent, metaData.getJsonData())); String propertiesContent = resourceDao.getExternalPropertiesResource(deployFileName).getTemplateContent(); ExternalProperties.loadFromInputStream(new ByteArrayInputStream(propertiesContent.getBytes())); } else if (successor != null) { createResourceResponseWrapper = successor.createResource(resourceIdentifier, metaData, templateContent); } return createResourceResponseWrapper; } ExternalPropertiesResourceHandler(final ResourceDao resourceDao, final ResourceHandler successor); @Override ConfigTemplate fetchResource(ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testCreateResource() throws IOException { ResourceIdentifier.Builder resourceIdentifierBuilder = new ResourceIdentifier.Builder(); resourceIdentifierBuilder.setGroupName(null); resourceIdentifierBuilder.setWebAppName(null); resourceIdentifierBuilder.setJvmName(null); resourceIdentifierBuilder.setWebServerName(null); resourceIdentifierBuilder.setResourceName("external.properties"); ResourceIdentifier identifier = resourceIdentifierBuilder.build(); final ResourceTemplateMetaData metaData = resourceService.getMetaData("{\"deployFileName\": \"external.properties\"}"); String templateContent = "key=value"; JpaResourceConfigTemplate mockJpaResourceConfigTemplate = mock(JpaResourceConfigTemplate.class); when(mockResourceDao.createResource(anyLong(), anyLong(), anyLong(), eq(EntityType.EXT_PROPERTIES), eq("external.properties"), anyString(), anyString())).thenReturn(mockJpaResourceConfigTemplate); when(mockResourceDao.getExternalPropertiesResource(anyString())).thenReturn(mockJpaResourceConfigTemplate); when(mockJpaResourceConfigTemplate.getTemplateContent()).thenReturn("key=value"); CreateResourceResponseWrapper result = externalPropertiesResourceHandler.createResource(identifier, metaData, templateContent); assertNotNull(result); verify(mockResourceDao).createResource((Long)isNull(), (Long)isNull(), (Long)isNull(), eq(EntityType.EXT_PROPERTIES), eq("external.properties"), eq(templateContent), anyString()); }
@Test public void testCreateResourceCallsSuccessor() throws IOException { ResourceIdentifier.Builder resourceIdentifierBuilder = new ResourceIdentifier.Builder(); resourceIdentifierBuilder.setGroupName("test-group-name"); resourceIdentifierBuilder.setWebAppName("test-app-name"); resourceIdentifierBuilder.setJvmName(null); resourceIdentifierBuilder.setWebServerName(null); resourceIdentifierBuilder.setResourceName("external.properties"); final ResourceTemplateMetaData metaData = resourceService.getMetaData("{\"deployFileName\": \"external.properties\"}"); CreateResourceResponseWrapper mockCreateResourceResponseWrapper = mock(CreateResourceResponseWrapper.class); when(mockSuccessor.createResource(any(ResourceIdentifier.class), any(ResourceTemplateMetaData.class), anyString())).thenReturn(mockCreateResourceResponseWrapper); CreateResourceResponseWrapper result = externalPropertiesResourceHandler.createResource(resourceIdentifierBuilder.build(), metaData, "key=value"); assertNotNull(result); verify(mockSuccessor).createResource(any(ResourceIdentifier.class), any(ResourceTemplateMetaData.class), anyString()); } |
JvmResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) { if (canHandle(resourceIdentifier)) { return jvmPersistenceService.updateResourceMetaData(resourceIdentifier.jvmName, resourceName, metaData); } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } JvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; when(mockJvmPersistence.updateResourceMetaData(anyString(), anyString(), anyString())).thenReturn(updatedMetaData); jvmResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockJvmPersistence).updateResourceMetaData(eq(resourceIdentifier.jvmName), eq(resourceName), eq(updatedMetaData)); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-jvm").build(); jvmResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
JvmResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return jvmPersistenceService.findJvmByExactName(resourceIdentifier.jvmName); } else { return successor.getSelectedValue(resourceIdentifier); } } JvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { Jvm mockJvm = mock(Jvm.class); when(mockJvmPersistence.findJvmByExactName(anyString())).thenReturn(mockJvm); Jvm jvm = (Jvm) jvmResourceHandler.getSelectedValue(resourceIdentifier); assertEquals(mockJvm, jvm); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("jvm-resource").setGroupName("not-a-jvm").build(); jvmResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
JvmResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return jvmPersistenceService.getResourceTemplateNames(resourceIdentifier.jvmName); } else { return successor.getResourceNames(resourceIdentifier); } } JvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetResourceNames() { jvmResourceHandler.getResourceNames(resourceIdentifier); verify(mockJvmPersistence).getResourceTemplateNames(anyString()); ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("what-jvm").setGroupName("not-a-jvm").build(); jvmResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); } |
GroupLevelJvmResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) { if (canHandle(resourceIdentifier)) { final String updatedMetaData = groupPersistenceService.updateGroupJvmResourceMetaData(resourceIdentifier.groupName, resourceName, metaData); Set<Jvm> jvmSet = groupPersistenceService.getGroup(resourceIdentifier.groupName).getJvms(); for (Jvm jvm : jvmSet) { jvmPersistenceService.updateResourceMetaData(jvm.getJvmName(), resourceName, metaData); } return updatedMetaData; } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } GroupLevelJvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); Jvm mockJvm = mock(Jvm.class); Set<Jvm> groupSet = new HashSet<>(); groupSet.add(mockJvm); when(mockGroup.getJvms()).thenReturn(groupSet); when(mockJvm.getJvmName()).thenReturn("jvm-name"); when(mockGroupPersistence.getGroup(anyString())).thenReturn(mockGroup); when(mockGroupPersistence.updateGroupJvmResourceMetaData(anyString(), anyString(), anyString())).thenReturn(updatedMetaData); groupLevelJvmResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockGroupPersistence).updateGroupJvmResourceMetaData(eq(resourceIdentifier.groupName), eq(resourceName), eq(updatedMetaData)); verify(mockJvmPersistence).updateResourceMetaData(eq(mockJvm.getJvmName()), eq(resourceName), eq(updatedMetaData)); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-jvm").build(); groupLevelJvmResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
GroupLevelJvmResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return null; } else { return successor.getSelectedValue(resourceIdentifier); } } GroupLevelJvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { Object selectedValue = groupLevelJvmResourceHandler.getSelectedValue(resourceIdentifier); assertNull(selectedValue); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("jvm-resource").setGroupName("not-a-jvm").build(); groupLevelJvmResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
GroupLevelJvmResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ throw new UnsupportedOperationException(); } else { return successor.getResourceNames(resourceIdentifier); } } GroupLevelJvmResourceHandler(final ResourceDao resourceDao, final GroupPersistenceService groupPersistenceService,
final JvmPersistenceService jvmPersistenceService, final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test (expected = UnsupportedOperationException.class) public void testGetResourceNames() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("what-group-level-jvm").setGroupName("not-a-jvm").build(); groupLevelJvmResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); groupLevelJvmResourceHandler.getResourceNames(resourceIdentifier); } |
GroupLevelWebServerResourceHandler extends ResourceHandler { @Override public String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData) { if (canHandle(resourceIdentifier)) { final String updatedMetaData = groupPersistenceService.updateGroupWebServerResourceMetaData(resourceIdentifier.groupName, resourceName, metaData); Set<WebServer> webServersSet = groupPersistenceService.getGroupWithWebServers(resourceIdentifier.groupName).getWebServers(); for (WebServer webServer : webServersSet){ webServerPersistenceService.updateResourceMetaData(webServer.getName(), resourceName, metaData); } return updatedMetaData; } else { return successor.updateResourceMetaData(resourceIdentifier, resourceName, metaData); } } GroupLevelWebServerResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testUpdateMetaData() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; Group mockGroup = mock(Group.class); WebServer mockWebServer = mock(WebServer.class); Set<WebServer> groupSet = new HashSet<>(); groupSet.add(mockWebServer); when(mockGroup.getWebServers()).thenReturn(groupSet); when(mockWebServer.getName()).thenReturn("webserver-name"); when(mockGroupPersistence.getGroupWithWebServers(anyString())).thenReturn(mockGroup); when(mockGroupPersistence.updateGroupWebServerResourceMetaData(anyString(), anyString(), anyString())).thenReturn(updatedMetaData); groupLevelWebServerResourceHandler.updateResourceMetaData(resourceIdentifier, resourceName, updatedMetaData); verify(mockGroupPersistence).updateGroupWebServerResourceMetaData(eq(resourceIdentifier.groupName), eq(resourceName), eq(updatedMetaData)); verify(mockWebServerPersistence).updateResourceMetaData(eq(mockWebServer.getName()), eq(resourceName), eq(updatedMetaData)); }
@Test public void testUpdateMetaDataCallsSuccessor() { final String updatedMetaData = "{\"updated\":\"meta-data\"}"; final String resourceName = "update-my-meta-data.txt"; ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName(resourceName).setGroupName("not-a-webserver").build(); groupLevelWebServerResourceHandler.updateResourceMetaData(notMeResourceIdentifier, resourceName, updatedMetaData); verify(mockSuccessor).updateResourceMetaData(eq(notMeResourceIdentifier), eq(resourceName), eq(updatedMetaData)); } |
GroupLevelWebServerResourceHandler extends ResourceHandler { @Override public Object getSelectedValue(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ return null; } else { return successor.getSelectedValue(resourceIdentifier); } } GroupLevelWebServerResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test public void testGetSelectedValue() { Object selectedValue = groupLevelWebServerResourceHandler.getSelectedValue(resourceIdentifier); assertNull(selectedValue); }
@Test public void testGetSelectedValueCallsSuccessor() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("webserver-resource").setGroupName("not-a-webserver").build(); groupLevelWebServerResourceHandler.getSelectedValue(notMeResourceIdentifier); verify(mockSuccessor).getSelectedValue(notMeResourceIdentifier); } |
GroupLevelWebServerResourceHandler extends ResourceHandler { @Override public List<String> getResourceNames(ResourceIdentifier resourceIdentifier) { if (canHandle(resourceIdentifier)){ throw new UnsupportedOperationException(); } else { return successor.getResourceNames(resourceIdentifier); } } GroupLevelWebServerResourceHandler(final ResourceDao resourceDao,
final GroupPersistenceService groupPersistenceService,
final WebServerPersistenceService webServerPersistenceService,
final ResourceContentGeneratorService resourceContentGeneratorService,
final ResourceHandler successor); @Override ConfigTemplate fetchResource(final ResourceIdentifier resourceIdentifier); @Override CreateResourceResponseWrapper createResource(final ResourceIdentifier resourceIdentifier,
final ResourceTemplateMetaData metaData,
final String templateContent); @Override void deleteResource(final ResourceIdentifier resourceIdentifier); @Override String updateResourceMetaData(ResourceIdentifier resourceIdentifier, String resourceName, String metaData); @Override Object getSelectedValue(ResourceIdentifier resourceIdentifier); @Override List<String> getResourceNames(ResourceIdentifier resourceIdentifier); } | @Test (expected = UnsupportedOperationException.class) public void testGetResourceNames() { ResourceIdentifier notMeResourceIdentifier = new ResourceIdentifier.Builder().setResourceName("what-group-level-web-server").setGroupName("not-a-web-server").build(); groupLevelWebServerResourceHandler.getResourceNames(notMeResourceIdentifier); verify(mockSuccessor).getResourceNames(notMeResourceIdentifier); groupLevelWebServerResourceHandler.getResourceNames(resourceIdentifier); } |
ApplicationContextListener { @EventListener public void handleEvent(ApplicationEvent event) { if (!(event instanceof ContextRefreshedEvent)) { LOGGER.debug("Expecting ContextRefreshedEvent. Skipping."); return; } LOGGER.info("Received ContextRefreshedEvent {}", event); ContextRefreshedEvent crEvent = (ContextRefreshedEvent) event; final ApplicationContext applicationContext = crEvent.getApplicationContext(); if (null == applicationContext) { LOGGER.debug("Expecting non-null ApplicationContext. Skipping."); return; } if (null == applicationContext.getParent()) { LOGGER.debug("Expecting non-null ApplicationContext parent. Skipping."); return; } processBootstrapConfiguration(); } @EventListener void handleEvent(ApplicationEvent event); } | @Test public void testNoApplicationContext() { JpaMedia mockJdkMedia = mock(JpaMedia.class); when(mockJdkMedia.getType()).thenReturn(MediaType.JDK); List<JpaMedia> mediaList = Collections.singletonList(mockJdkMedia); when(Config.mediaServiceMock.findAll()).thenReturn(mediaList); ContextRefreshedEvent mockStartupEvent = mock(ContextRefreshedEvent.class); applicationContextListener.handleEvent(mockStartupEvent); verify(Config.jvmServiceMock, never()).updateJvm(any(UpdateJvmRequest.class), eq(true)); verify(Config.mediaServiceMock, never()).create(anyMap(), anyMap()); }
@Test public void testNoParentForApplicationContext() { JpaMedia mockJdkMedia = mock(JpaMedia.class); when(mockJdkMedia.getType()).thenReturn(MediaType.JDK); List<JpaMedia> mediaList = Collections.singletonList(mockJdkMedia); when(Config.mediaServiceMock.findAll()).thenReturn(mediaList); ContextRefreshedEvent mockStartupEvent = mock(ContextRefreshedEvent.class); ApplicationContext mockApplicationContext = mock(ApplicationContext.class); when(mockStartupEvent.getApplicationContext()).thenReturn(mockApplicationContext); applicationContextListener.handleEvent(mockStartupEvent); verify(Config.jvmServiceMock, never()).updateJvm(any(UpdateJvmRequest.class), eq(true)); verify(Config.mediaServiceMock, never()).create(anyMap(), anyMap()); }
@Test public void testApplicationContextWithParent() { applicationContextListener.handleEvent(mockStartupEvent); verify(Config.jvmServiceMock, never()).updateJvm(any(UpdateJvmRequest.class), eq(true)); verify(Config.mediaServiceMock, never()).create(anyMap(), anyMap()); } |
Constraints { public static void remove(HTableDescriptor desc) { disable(desc); List<ImmutableBytesWritable> keys = new ArrayList<ImmutableBytesWritable>(); for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : desc .getValues().entrySet()) { String key = Bytes.toString((e.getKey().get())); String[] className = CONSTRAINT_HTD_ATTR_KEY_PATTERN.split(key); if (className.length == 2) { keys.add(e.getKey()); } } for (ImmutableBytesWritable key : keys) { desc.remove(key); } } private Constraints(); static void enable(HTableDescriptor desc); static void disable(HTableDescriptor desc); static void remove(HTableDescriptor desc); static boolean has(HTableDescriptor desc,
Class<? extends Constraint> clazz); static void add(HTableDescriptor desc,
Class<? extends Constraint>... constraints); static void add(HTableDescriptor desc,
Pair<Class<? extends Constraint>, Configuration>... constraints); static void add(HTableDescriptor desc,
Class<? extends Constraint> constraint, Configuration conf); static void setConfiguration(HTableDescriptor desc,
Class<? extends Constraint> clazz, Configuration configuration); static void remove(HTableDescriptor desc,
Class<? extends Constraint> clazz); static void enableConstraint(HTableDescriptor desc,
Class<? extends Constraint> clazz); static void disableConstraint(HTableDescriptor desc,
Class<? extends Constraint> clazz); static boolean enabled(HTableDescriptor desc,
Class<? extends Constraint> clazz); } | @Test public void testRemoveUnsetConstraint() throws Throwable { HTableDescriptor desc = new HTableDescriptor(TableName.valueOf("table")); Constraints.remove(desc); Constraints.remove(desc, AlsoWorks.class); } |
AccessController extends BaseRegionObserver implements MasterObserver, RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver { private TableName getTableName(RegionCoprocessorEnvironment e) { HRegion region = e.getRegion(); if (region != null) { return getTableName(region); } return null; } HRegion getRegion(); TableAuthManager getAuthManager(); void start(CoprocessorEnvironment env); void stop(CoprocessorEnvironment env); @Override void preCreateTable(ObserverContext<MasterCoprocessorEnvironment> c,
HTableDescriptor desc, HRegionInfo[] regions); @Override void preCreateTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
HTableDescriptor desc, HRegionInfo[] regions); @Override void postCreateTable(ObserverContext<MasterCoprocessorEnvironment> c,
HTableDescriptor desc, HRegionInfo[] regions); @Override void postCreateTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
HTableDescriptor desc, HRegionInfo[] regions); @Override void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName); @Override void preDeleteTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postDeleteTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void preTruncateTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName); @Override void postTruncateTable(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void preTruncateTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postTruncateTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void preModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
HTableDescriptor htd); @Override void preModifyTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HTableDescriptor htd); @Override void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HTableDescriptor htd); @Override void postModifyTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HTableDescriptor htd); @Override void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
HColumnDescriptor column); @Override void preAddColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor column); @Override void postAddColumn(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor column); @Override void postAddColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor column); @Override void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
HColumnDescriptor descriptor); @Override void preModifyColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor descriptor); @Override void postModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor descriptor); @Override void postModifyColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, HColumnDescriptor descriptor); @Override void preDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
byte[] col); @Override void preDeleteColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, byte[] col); @Override void postDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, byte[] col); @Override void postDeleteColumnHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName, byte[] col); @Override void preEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName); @Override void preEnableTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postEnableTable(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postEnableTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName); @Override void preDisableTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postDisableTable(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void postDisableTableHandler(ObserverContext<MasterCoprocessorEnvironment> c,
TableName tableName); @Override void preMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region,
ServerName srcServer, ServerName destServer); @Override void postMove(ObserverContext<MasterCoprocessorEnvironment> c,
HRegionInfo region, ServerName srcServer, ServerName destServer); @Override void preAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo); @Override void postAssign(ObserverContext<MasterCoprocessorEnvironment> c,
HRegionInfo regionInfo); @Override void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo,
boolean force); @Override void postUnassign(ObserverContext<MasterCoprocessorEnvironment> c,
HRegionInfo regionInfo, boolean force); @Override void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c,
HRegionInfo regionInfo); @Override void postRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c,
HRegionInfo regionInfo); @Override void preBalance(ObserverContext<MasterCoprocessorEnvironment> c); @Override void postBalance(ObserverContext<MasterCoprocessorEnvironment> c, List<RegionPlan> plans); @Override boolean preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c,
boolean newValue); @Override void postBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c,
boolean oldValue, boolean newValue); @Override void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c); @Override void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c); @Override void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> ctx); @Override void preMasterInitialization(
ObserverContext<MasterCoprocessorEnvironment> ctx); @Override void preSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void postSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void preCloneSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void postCloneSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void preRestoreSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void postRestoreSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor); @Override void preDeleteSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot); @Override void postDeleteSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final SnapshotDescription snapshot); @Override void preCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
NamespaceDescriptor ns); @Override void postCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
NamespaceDescriptor ns); @Override void preDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace); @Override void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
String namespace); @Override void preModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
NamespaceDescriptor ns); @Override void postModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
NamespaceDescriptor ns); @Override void preTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final TableName tableName); @Override void postTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx,
final TableName tableName); @Override void preOpen(ObserverContext<RegionCoprocessorEnvironment> e); @Override void postOpen(ObserverContext<RegionCoprocessorEnvironment> c); @Override void postLogReplay(ObserverContext<RegionCoprocessorEnvironment> c); @Override void preFlush(ObserverContext<RegionCoprocessorEnvironment> e); @Override void preSplit(ObserverContext<RegionCoprocessorEnvironment> e); @Override void preSplit(ObserverContext<RegionCoprocessorEnvironment> e,
byte[] splitRow); @Override InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e,
final Store store, final InternalScanner scanner, final ScanType scanType); @Override void preCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> e,
final Store store, final List<StoreFile> candidates); @Override void preGetClosestRowBefore(final ObserverContext<RegionCoprocessorEnvironment> c,
final byte [] row, final byte [] family, final Result result); @Override void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> c,
final Get get, final List<Cell> result); @Override boolean preExists(final ObserverContext<RegionCoprocessorEnvironment> c,
final Get get, final boolean exists); @Override void prePut(final ObserverContext<RegionCoprocessorEnvironment> c,
final Put put, final WALEdit edit, final Durability durability); @Override void postPut(final ObserverContext<RegionCoprocessorEnvironment> c,
final Put put, final WALEdit edit, final Durability durability); @Override void preDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
final Delete delete, final WALEdit edit, final Durability durability); @Override void postDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
final Delete delete, final WALEdit edit, final Durability durability); @Override boolean preCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> c,
final byte [] row, final byte [] family, final byte [] qualifier,
final CompareFilter.CompareOp compareOp,
final ByteArrayComparable comparator, final Put put,
final boolean result); @Override boolean preCheckAndDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
final byte [] row, final byte [] family, final byte [] qualifier,
final CompareFilter.CompareOp compareOp,
final ByteArrayComparable comparator, final Delete delete,
final boolean result); @Override long preIncrementColumnValue(final ObserverContext<RegionCoprocessorEnvironment> c,
final byte [] row, final byte [] family, final byte [] qualifier,
final long amount, final boolean writeToWAL); @Override Result preAppend(ObserverContext<RegionCoprocessorEnvironment> c, Append append); @Override Result preIncrement(final ObserverContext<RegionCoprocessorEnvironment> c,
final Increment increment); @Override Cell postMutationBeforeWAL(ObserverContext<RegionCoprocessorEnvironment> ctx,
MutationType opType, Mutation mutation, Cell oldCell, Cell newCell); @Override RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner s); @Override RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner s); @Override boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> c,
final InternalScanner s, final List<Result> result,
final int limit, final boolean hasNext); @Override void preScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c,
final InternalScanner s); @Override void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c,
final InternalScanner s); @Override void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
List<Pair<byte[], String>> familyPaths); void prePrepareBulkLoad(RegionCoprocessorEnvironment e); void preCleanupBulkLoad(RegionCoprocessorEnvironment e); @Override Message preEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx,
Service service, String methodName, Message request); @Override void postEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx,
Service service, String methodName, Message request, Message.Builder responseBuilder); @Override void grant(RpcController controller,
AccessControlProtos.GrantRequest request,
RpcCallback<AccessControlProtos.GrantResponse> done); @Override void revoke(RpcController controller,
AccessControlProtos.RevokeRequest request,
RpcCallback<AccessControlProtos.RevokeResponse> done); @Override void getUserPermissions(RpcController controller,
AccessControlProtos.GetUserPermissionsRequest request,
RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done); @Override void checkPermissions(RpcController controller,
AccessControlProtos.CheckPermissionsRequest request,
RpcCallback<AccessControlProtos.CheckPermissionsResponse> done); @Override Service getService(); @Override void preClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested); @Override void preStopRegionServer(
ObserverContext<RegionServerCoprocessorEnvironment> env); @Override void preGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx,
List<TableName> tableNamesList,
List<HTableDescriptor> descriptors); @Override void postGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx,
List<HTableDescriptor> descriptors); @Override void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx, HRegion regionA,
HRegion regionB); @Override void postMerge(ObserverContext<RegionServerCoprocessorEnvironment> c, HRegion regionA,
HRegion regionB, HRegion mergedRegion); @Override void preMergeCommit(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
HRegion regionA, HRegion regionB, List<Mutation> metaEntries); @Override void postMergeCommit(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
HRegion regionA, HRegion regionB, HRegion mergedRegion); @Override void preRollBackMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
HRegion regionA, HRegion regionB); @Override void postRollBackMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
HRegion regionA, HRegion regionB); static final Log LOG; } | @Test public void testTableDeletion() throws Exception { User TABLE_ADMIN = User.createUserForTesting(conf, "TestUser", new String[0]); grantOnTable(TEST_UTIL, TABLE_ADMIN.getShortName(), TEST_TABLE.getTableName(), null, null, Permission.Action.ADMIN); AccessTestAction deleteTableAction = new AccessTestAction() { @Override public Object run() throws Exception { HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration()); try { admin.disableTable(TEST_TABLE.getTableName()); admin.deleteTable(TEST_TABLE.getTableName()); } finally { admin.close(); } return null; } }; verifyDenied(deleteTableAction, USER_RW, USER_RO, USER_NONE); verifyAllowed(deleteTableAction, TABLE_ADMIN); }
@Test public void testNamespaceUserGrant() throws Exception { AccessTestAction getAction = new AccessTestAction() { @Override public Object run() throws Exception { HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { return t.get(new Get(TEST_ROW)); } finally { t.close(); } } }; verifyDenied(getAction, USER_NONE); grantOnNamespace(TEST_UTIL, USER_NONE.getShortName(), TEST_TABLE.getTableName().getNamespaceAsString(), Permission.Action.READ); verifyAllowed(getAction, USER_NONE); }
@Test public void testCoprocessorExec() throws Exception { for (JVMClusterUtil.RegionServerThread thread: TEST_UTIL.getMiniHBaseCluster().getRegionServerThreads()) { HRegionServer rs = thread.getRegionServer(); for (HRegion region: rs.getOnlineRegions(TEST_TABLE.getTableName())) { region.getCoprocessorHost().load(PingCoprocessor.class, Coprocessor.PRIORITY_USER, conf); } } User userA = User.createUserForTesting(conf, "UserA", new String[0]); User userB = User.createUserForTesting(conf, "UserB", new String[0]); grantOnTable(TEST_UTIL, userA.getShortName(), TEST_TABLE.getTableName(), null, null, Permission.Action.EXEC); AccessTestAction execEndpointAction = new AccessTestAction() { @Override public Object run() throws Exception { HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { BlockingRpcChannel service = t.coprocessorService(HConstants.EMPTY_BYTE_ARRAY); PingCoprocessor.newBlockingStub(service).noop(null, NoopRequest.newBuilder().build()); } finally { t.close(); } return null; } }; verifyDenied(execEndpointAction, userB); verifyAllowed(execEndpointAction, userA); grantOnNamespace(TEST_UTIL, userB.getShortName(), TEST_TABLE.getTableName().getNamespaceAsString(), Permission.Action.EXEC); verifyAllowed(execEndpointAction, userA, userB); }
@Test public void testRead() throws Exception { AccessTestAction getAction = new AccessTestAction() { @Override public Object run() throws Exception { Get g = new Get(TEST_ROW); g.addFamily(TEST_FAMILY); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.get(g); } finally { t.close(); } return null; } }; verifyRead(getAction); AccessTestAction scanAction = new AccessTestAction() { @Override public Object run() throws Exception { Scan s = new Scan(); s.addFamily(TEST_FAMILY); HTable table = new HTable(conf, TEST_TABLE.getTableName()); try { ResultScanner scanner = table.getScanner(s); try { for (Result r = scanner.next(); r != null; r = scanner.next()) { } } catch (IOException e) { } finally { scanner.close(); } } finally { table.close(); } return null; } }; verifyRead(scanAction); }
@Test public void testWrite() throws Exception { AccessTestAction putAction = new AccessTestAction() { @Override public Object run() throws Exception { Put p = new Put(TEST_ROW); p.add(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(1)); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.put(p); } finally { t.close(); } return null; } }; verifyWrite(putAction); AccessTestAction deleteAction = new AccessTestAction() { @Override public Object run() throws Exception { Delete d = new Delete(TEST_ROW); d.deleteFamily(TEST_FAMILY); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.delete(d); } finally { t.close(); } return null; } }; verifyWrite(deleteAction); AccessTestAction incrementAction = new AccessTestAction() { @Override public Object run() throws Exception { Increment inc = new Increment(TEST_ROW); inc.addColumn(TEST_FAMILY, TEST_QUALIFIER, 1); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.increment(inc); } finally { t.close(); } return null; } }; verifyWrite(incrementAction); }
@Test public void testReadWrite() throws Exception { AccessTestAction checkAndDeleteAction = new AccessTestAction() { @Override public Object run() throws Exception { Delete d = new Delete(TEST_ROW); d.deleteFamily(TEST_FAMILY); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.checkAndDelete(TEST_ROW, TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes("test_value"), d); } finally { t.close(); } return null; } }; verifyReadWrite(checkAndDeleteAction); AccessTestAction checkAndPut = new AccessTestAction() { @Override public Object run() throws Exception { Put p = new Put(TEST_ROW); p.add(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(1)); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.checkAndPut(TEST_ROW, TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes("test_value"), p); } finally { t.close(); } return null; } }; verifyReadWrite(checkAndPut); }
@Test public void testBulkLoad() throws Exception { FileSystem fs = TEST_UTIL.getTestFileSystem(); final Path dir = TEST_UTIL.getDataTestDirOnTestFS("testBulkLoad"); fs.mkdirs(dir); fs.setPermission(dir, FsPermission.valueOf("-rwxrwxrwx")); AccessTestAction bulkLoadAction = new AccessTestAction() { @Override public Object run() throws Exception { int numRows = 3; byte[][][] hfileRanges = {{{(byte)0}, {(byte)9}}}; Path bulkLoadBasePath = new Path(dir, new Path(User.getCurrent().getName())); new BulkLoadHelper(bulkLoadBasePath) .bulkLoadHFile(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_QUALIFIER, hfileRanges, numRows); return null; } }; verifyAllowed(bulkLoadAction, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE); verifyDenied(bulkLoadAction, USER_RW, USER_NONE, USER_RO); TEST_UTIL.getHBaseAdmin().disableTable(TEST_TABLE.getTableName()); TEST_UTIL.getHBaseAdmin().enableTable(TEST_TABLE.getTableName()); }
@Test public void testAppend() throws Exception { AccessTestAction appendAction = new AccessTestAction() { @Override public Object run() throws Exception { byte[] row = TEST_ROW; byte[] qualifier = TEST_QUALIFIER; Put put = new Put(row); put.add(TEST_FAMILY, qualifier, Bytes.toBytes(1)); Append append = new Append(row); append.add(TEST_FAMILY, qualifier, Bytes.toBytes(2)); HTable t = new HTable(conf, TEST_TABLE.getTableName()); try { t.put(put); t.append(append); } finally { t.close(); } return null; } }; verifyAllowed(appendAction, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW); verifyDenied(appendAction, USER_RO, USER_NONE); }
@Test public void testTableDescriptorsEnumeration() throws Exception { User TABLE_ADMIN = User.createUserForTesting(conf, "UserA", new String[0]); grantOnTable(TEST_UTIL, TABLE_ADMIN.getShortName(), TEST_TABLE.getTableName(), null, null, Permission.Action.ADMIN); AccessTestAction listTablesAction = new AccessTestAction() { @Override public Object run() throws Exception { HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration()); try { admin.listTables(); } finally { admin.close(); } return null; } }; AccessTestAction getTableDescAction = new AccessTestAction() { @Override public Object run() throws Exception { HBaseAdmin admin = new HBaseAdmin(TEST_UTIL.getConfiguration()); try { admin.getTableDescriptor(TEST_TABLE.getTableName()); } finally { admin.close(); } return null; } }; verifyAllowed(listTablesAction, SUPERUSER, USER_ADMIN); verifyDenied(listTablesAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, TABLE_ADMIN); verifyAllowed(getTableDescAction, SUPERUSER, USER_ADMIN, USER_CREATE, TABLE_ADMIN); verifyDenied(getTableDescAction, USER_RW, USER_RO, USER_NONE); } |
ZKSecretWatcher extends ZooKeeperListener { public void start() throws KeeperException { watcher.registerListener(this); ZKUtil.createWithParents(watcher, keysParentZNode); if (ZKUtil.watchAndCheckExists(watcher, keysParentZNode)) { List<ZKUtil.NodeAndData> nodes = ZKUtil.getChildDataAndWatchForNewChildren(watcher, keysParentZNode); refreshNodes(nodes); } } ZKSecretWatcher(Configuration conf,
ZooKeeperWatcher watcher,
AuthenticationTokenSecretManager secretManager); void start(); @Override void nodeCreated(String path); @Override void nodeDeleted(String path); @Override void nodeDataChanged(String path); @Override void nodeChildrenChanged(String path); String getRootKeyZNode(); void removeKeyFromZK(AuthenticationKey key); void addKeyToZK(AuthenticationKey key); void updateKeyInZK(AuthenticationKey key); } | @Test public void testKeyUpdate() throws Exception { assertTrue(KEY_MASTER.isMaster()); assertFalse(KEY_SLAVE.isMaster()); int maxKeyId = 0; KEY_MASTER.rollCurrentKey(); AuthenticationKey key1 = KEY_MASTER.getCurrentKey(); assertNotNull(key1); LOG.debug("Master current key: "+key1.getKeyId()); Thread.sleep(1000); AuthenticationKey slaveCurrent = KEY_SLAVE.getCurrentKey(); assertNotNull(slaveCurrent); assertEquals(key1, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key2 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key2.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key3 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key3.getKeyId()); key1.setExpiration(EnvironmentEdgeManager.currentTimeMillis() - 1000); KEY_MASTER.removeExpiredKeys(); assertNull(KEY_MASTER.getKey(key1.getKeyId())); KEY_SLAVE.getLatch().await(); AuthenticationKey slave2 = KEY_SLAVE.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); AuthenticationKey slave3 = KEY_SLAVE.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE.getCurrentKey(); assertEquals(key3, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); assertNull(KEY_SLAVE.getKey(key1.getKeyId())); Configuration conf = TEST_UTIL.getConfiguration(); ZooKeeperWatcher zk = newZK(conf, "server3", new MockAbortable()); KEY_SLAVE2 = new AuthenticationTokenSecretManager( conf, zk, "server3", 60*60*1000, 60*1000); KEY_SLAVE2.start(); Thread.sleep(1000); slave2 = KEY_SLAVE2.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); slave3 = KEY_SLAVE2.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE2.getCurrentKey(); assertEquals(key3, slaveCurrent); assertNull(KEY_SLAVE2.getKey(key1.getKeyId())); KEY_MASTER.stop(); Thread.sleep(1000); assertFalse(KEY_MASTER.isMaster()); AuthenticationTokenSecretManager[] mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2 }; AuthenticationTokenSecretManager newMaster = null; int tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current = newMaster.getCurrentKey(); assertTrue(current.getKeyId() >= slaveCurrent.getKeyId()); LOG.debug("New master, current key: "+current.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent = newMaster.getCurrentKey(); LOG.debug("New master, rolled new current key: "+newCurrent.getKeyId()); assertTrue(newCurrent.getKeyId() > current.getKeyId()); ZooKeeperWatcher zk3 = newZK(conf, "server4", new MockAbortable()); KEY_SLAVE3 = new AuthenticationTokenSecretManager( conf, zk3, "server4", 60*60*1000, 60*1000); KEY_SLAVE3.start(); Thread.sleep(5000); newMaster.stop(); Thread.sleep(5000); assertFalse(newMaster.isMaster()); mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2, KEY_SLAVE3 }; newMaster = null; tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current2 = newMaster.getCurrentKey(); assertTrue(current2.getKeyId() >= newCurrent.getKeyId()); LOG.debug("New master 2, current key: "+current2.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent2 = newMaster.getCurrentKey(); LOG.debug("New master 2, rolled new current key: "+newCurrent2.getKeyId()); assertTrue(newCurrent2.getKeyId() > current2.getKeyId()); }
@Test public void testKeyUpdate() throws Exception { assertTrue(KEY_MASTER.isMaster()); assertFalse(KEY_SLAVE.isMaster()); int maxKeyId = 0; KEY_MASTER.rollCurrentKey(); AuthenticationKey key1 = KEY_MASTER.getCurrentKey(); assertNotNull(key1); LOG.debug("Master current key: "+key1.getKeyId()); Thread.sleep(1000); AuthenticationKey slaveCurrent = KEY_SLAVE.getCurrentKey(); assertNotNull(slaveCurrent); assertEquals(key1, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key2 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key2.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key3 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key3.getKeyId()); key1.setExpiration(EnvironmentEdgeManager.currentTimeMillis() - 1000); KEY_MASTER.removeExpiredKeys(); assertNull(KEY_MASTER.getKey(key1.getKeyId())); Thread.sleep(1000); AuthenticationKey slave2 = KEY_SLAVE.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); AuthenticationKey slave3 = KEY_SLAVE.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE.getCurrentKey(); assertEquals(key3, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); assertNull(KEY_SLAVE.getKey(key1.getKeyId())); Configuration conf = TEST_UTIL.getConfiguration(); ZooKeeperWatcher zk = newZK(conf, "server3", new MockAbortable()); KEY_SLAVE2 = new AuthenticationTokenSecretManager( conf, zk, "server3", 60*60*1000, 60*1000); KEY_SLAVE2.start(); Thread.sleep(1000); slave2 = KEY_SLAVE2.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); slave3 = KEY_SLAVE2.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE2.getCurrentKey(); assertEquals(key3, slaveCurrent); assertNull(KEY_SLAVE2.getKey(key1.getKeyId())); KEY_MASTER.stop(); Thread.sleep(1000); assertFalse(KEY_MASTER.isMaster()); AuthenticationTokenSecretManager[] mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2 }; AuthenticationTokenSecretManager newMaster = null; int tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current = newMaster.getCurrentKey(); assertTrue(current.getKeyId() >= slaveCurrent.getKeyId()); LOG.debug("New master, current key: "+current.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent = newMaster.getCurrentKey(); LOG.debug("New master, rolled new current key: "+newCurrent.getKeyId()); assertTrue(newCurrent.getKeyId() > current.getKeyId()); ZooKeeperWatcher zk3 = newZK(conf, "server4", new MockAbortable()); KEY_SLAVE3 = new AuthenticationTokenSecretManager( conf, zk3, "server4", 60*60*1000, 60*1000); KEY_SLAVE3.start(); Thread.sleep(5000); newMaster.stop(); Thread.sleep(5000); assertFalse(newMaster.isMaster()); mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2, KEY_SLAVE3 }; newMaster = null; tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current2 = newMaster.getCurrentKey(); assertTrue(current2.getKeyId() >= newCurrent.getKeyId()); LOG.debug("New master 2, current key: "+current2.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent2 = newMaster.getCurrentKey(); LOG.debug("New master 2, rolled new current key: "+newCurrent2.getKeyId()); assertTrue(newCurrent2.getKeyId() > current2.getKeyId()); }
@Test public void testKeyUpdate() throws Exception { assertTrue(KEY_MASTER.isMaster()); assertFalse(KEY_SLAVE.isMaster()); int maxKeyId = 0; KEY_MASTER.rollCurrentKey(); AuthenticationKey key1 = KEY_MASTER.getCurrentKey(); assertNotNull(key1); LOG.debug("Master current key: "+key1.getKeyId()); Thread.sleep(1000); AuthenticationKey slaveCurrent = KEY_SLAVE.getCurrentKey(); assertNotNull(slaveCurrent); assertEquals(key1, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key2 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key2.getKeyId()); KEY_MASTER.rollCurrentKey(); AuthenticationKey key3 = KEY_MASTER.getCurrentKey(); LOG.debug("Master new current key: "+key3.getKeyId()); key1.setExpiration(EnvironmentEdgeManager.currentTime() - 1000); KEY_MASTER.removeExpiredKeys(); assertNull(KEY_MASTER.getKey(key1.getKeyId())); KEY_SLAVE.getLatch().await(); AuthenticationKey slave2 = KEY_SLAVE.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); AuthenticationKey slave3 = KEY_SLAVE.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE.getCurrentKey(); assertEquals(key3, slaveCurrent); LOG.debug("Slave current key: "+slaveCurrent.getKeyId()); assertNull(KEY_SLAVE.getKey(key1.getKeyId())); Configuration conf = TEST_UTIL.getConfiguration(); ZooKeeperWatcher zk = newZK(conf, "server3", new MockAbortable()); KEY_SLAVE2 = new AuthenticationTokenSecretManager( conf, zk, "server3", 60*60*1000, 60*1000); KEY_SLAVE2.start(); Thread.sleep(1000); slave2 = KEY_SLAVE2.getKey(key2.getKeyId()); assertNotNull(slave2); assertEquals(key2, slave2); slave3 = KEY_SLAVE2.getKey(key3.getKeyId()); assertNotNull(slave3); assertEquals(key3, slave3); slaveCurrent = KEY_SLAVE2.getCurrentKey(); assertEquals(key3, slaveCurrent); assertNull(KEY_SLAVE2.getKey(key1.getKeyId())); KEY_MASTER.stop(); Thread.sleep(1000); assertFalse(KEY_MASTER.isMaster()); AuthenticationTokenSecretManager[] mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2 }; AuthenticationTokenSecretManager newMaster = null; int tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current = newMaster.getCurrentKey(); assertTrue(current.getKeyId() >= slaveCurrent.getKeyId()); LOG.debug("New master, current key: "+current.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent = newMaster.getCurrentKey(); LOG.debug("New master, rolled new current key: "+newCurrent.getKeyId()); assertTrue(newCurrent.getKeyId() > current.getKeyId()); ZooKeeperWatcher zk3 = newZK(conf, "server4", new MockAbortable()); KEY_SLAVE3 = new AuthenticationTokenSecretManager( conf, zk3, "server4", 60*60*1000, 60*1000); KEY_SLAVE3.start(); Thread.sleep(5000); newMaster.stop(); Thread.sleep(5000); assertFalse(newMaster.isMaster()); mgrs = new AuthenticationTokenSecretManager[]{ KEY_SLAVE, KEY_SLAVE2, KEY_SLAVE3 }; newMaster = null; tries = 0; while (newMaster == null && tries++ < 5) { for (AuthenticationTokenSecretManager mgr : mgrs) { if (mgr.isMaster()) { newMaster = mgr; break; } } if (newMaster == null) { Thread.sleep(500); } } assertNotNull(newMaster); AuthenticationKey current2 = newMaster.getCurrentKey(); assertTrue(current2.getKeyId() >= newCurrent.getKeyId()); LOG.debug("New master 2, current key: "+current2.getKeyId()); newMaster.rollCurrentKey(); AuthenticationKey newCurrent2 = newMaster.getCurrentKey(); LOG.debug("New master 2, rolled new current key: "+newCurrent2.getKeyId()); assertTrue(newCurrent2.getKeyId() > current2.getKeyId()); } |
EnforcingScanLabelGenerator implements ScanLabelGenerator { public EnforcingScanLabelGenerator() { this.labelsManager = VisibilityLabelsManager.get(); } EnforcingScanLabelGenerator(); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override List<String> getLabels(User user, Authorizations authorizations); } | @Test public void testEnforcingScanLabelGenerator() throws Exception { final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); SUPERUSER.runAs(new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { HTable table = TEST_UTIL.createTable(tableName, CF); try { Put put = new Put(ROW_1); put.add(CF, Q1, HConstants.LATEST_TIMESTAMP, value); put.setCellVisibility(new CellVisibility(SECRET)); table.put(put); put = new Put(ROW_1); put.add(CF, Q2, HConstants.LATEST_TIMESTAMP, value); put.setCellVisibility(new CellVisibility(CONFIDENTIAL)); table.put(put); put = new Put(ROW_1); put.add(CF, Q3, HConstants.LATEST_TIMESTAMP, value); table.put(put); return null; } finally { table.close(); } } }); TESTUSER.runAs(new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { HTable table = new HTable(conf, tableName); try { Get get = new Get(ROW_1); get.setAuthorizations(new Authorizations(new String[] { SECRET, CONFIDENTIAL })); Result result = table.get(get); assertFalse("Inappropriate authorization", result.containsColumn(CF, Q1)); assertTrue("Missing authorization", result.containsColumn(CF, Q2)); assertTrue("Inappropriate filtering", result.containsColumn(CF, Q3)); get = new Get(ROW_1); result = table.get(get); assertFalse("Inappropriate authorization", result.containsColumn(CF, Q1)); assertTrue("Missing authorization", result.containsColumn(CF, Q2)); assertTrue("Inappropriate filtering", result.containsColumn(CF, Q3)); return null; } finally { table.close(); } } }); } |
ExpressionExpander { public ExpressionNode expand(ExpressionNode src) { if (!src.isSingleNode()) { NonLeafExpressionNode nlExp = (NonLeafExpressionNode) src; List<ExpressionNode> childExps = nlExp.getChildExps(); Operator outerOp = nlExp.getOperator(); if (isToBeExpanded(childExps)) { NonLeafExpressionNode newNode = new NonLeafExpressionNode(nlExp.getOperator()); for (ExpressionNode exp : childExps) { if (exp.isSingleNode()) { newNode.addChildExp(exp); } else { newNode.addChildExp(expand(exp)); } } nlExp = expandNonLeaf(newNode, outerOp); } return nlExp; } if (src instanceof NonLeafExpressionNode && ((NonLeafExpressionNode) src).getOperator() == Operator.NOT) { return negate((NonLeafExpressionNode) src); } return src; } ExpressionNode expand(ExpressionNode src); } | @Test public void testPositiveCases() throws Exception { ExpressionExpander expander = new ExpressionExpander(); NonLeafExpressionNode exp1 = new NonLeafExpressionNode(Operator.NOT, new LeafExpressionNode("a")); ExpressionNode result = expander.expand(exp1); assertTrue(result instanceof NonLeafExpressionNode); NonLeafExpressionNode nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.NOT, nlResult.getOperator()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); NonLeafExpressionNode exp2 = new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b")); result = expander.expand(exp2); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp3 = new NonLeafExpressionNode(Operator.AND, new LeafExpressionNode("a"), new LeafExpressionNode("b")); result = expander.expand(exp3); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.AND, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp4 = new NonLeafExpressionNode(Operator.OR, new NonLeafExpressionNode( Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b")), new LeafExpressionNode("c")); result = expander.expand(exp4); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(3, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) nlResult.getChildExps().get(2)).getIdentifier()); NonLeafExpressionNode exp5 = new NonLeafExpressionNode(Operator.AND, new NonLeafExpressionNode( Operator.AND, new LeafExpressionNode("a"), new LeafExpressionNode("b")), new LeafExpressionNode("c")); result = expander.expand(exp5); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.AND, nlResult.getOperator()); assertEquals(3, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) nlResult.getChildExps().get(2)).getIdentifier()); NonLeafExpressionNode exp6 = new NonLeafExpressionNode(Operator.AND, new NonLeafExpressionNode( Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b")), new LeafExpressionNode("c")); result = expander.expand(exp6); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); NonLeafExpressionNode temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp7 = new NonLeafExpressionNode(Operator.OR, new NonLeafExpressionNode( Operator.AND, new LeafExpressionNode("a"), new LeafExpressionNode("b")), new LeafExpressionNode("c")); result = expander.expand(exp7); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); assertEquals("c", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); nlResult = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp8 = new NonLeafExpressionNode(Operator.AND); exp8.addChildExp(new NonLeafExpressionNode(Operator.OR, new NonLeafExpressionNode(Operator.AND, new LeafExpressionNode("a"), new LeafExpressionNode("b")), new LeafExpressionNode("c"))); exp8.addChildExp(new LeafExpressionNode("d")); result = expander.expand(exp8); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp9 = new NonLeafExpressionNode(Operator.OR); exp9.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b"))); exp9.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("c"), new LeafExpressionNode("d"))); result = expander.expand(exp9); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(4, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) nlResult.getChildExps().get(2)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) nlResult.getChildExps().get(3)).getIdentifier()); NonLeafExpressionNode exp10 = new NonLeafExpressionNode(Operator.AND); exp10.addChildExp(new NonLeafExpressionNode(Operator.AND, new LeafExpressionNode("a"), new LeafExpressionNode("b"))); exp10.addChildExp(new NonLeafExpressionNode(Operator.AND, new LeafExpressionNode("c"), new LeafExpressionNode("d"))); result = expander.expand(exp10); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.AND, nlResult.getOperator()); assertEquals(4, nlResult.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) nlResult.getChildExps().get(0)).getIdentifier()); assertEquals("b", ((LeafExpressionNode) nlResult.getChildExps().get(1)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) nlResult.getChildExps().get(2)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) nlResult.getChildExps().get(3)).getIdentifier()); NonLeafExpressionNode exp11 = new NonLeafExpressionNode(Operator.AND); exp11.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b"))); exp11.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("c"), new LeafExpressionNode("d"))); result = expander.expand(exp11); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(4, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(2); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(3); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp12 = new NonLeafExpressionNode(Operator.AND); NonLeafExpressionNode tempExp1 = new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode( "a"), new LeafExpressionNode("b")); NonLeafExpressionNode tempExp2 = new NonLeafExpressionNode(Operator.OR, tempExp1, new LeafExpressionNode("c")); NonLeafExpressionNode tempExp3 = new NonLeafExpressionNode(Operator.OR, tempExp2, new LeafExpressionNode("d")); exp12.addChildExp(tempExp3); exp12.addChildExp(new LeafExpressionNode("e")); result = expander.expand(exp12); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(4, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(2); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(3); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp13 = new NonLeafExpressionNode(Operator.AND, new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode( "b"), new LeafExpressionNode("c")), new LeafExpressionNode("d")); result = expander.expand(exp13); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(3, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(2); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp15 = new NonLeafExpressionNode(Operator.AND); NonLeafExpressionNode temp1 = new NonLeafExpressionNode(Operator.AND); temp1.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode("b"))); temp1.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("c"), new LeafExpressionNode("d"))); exp15.addChildExp(temp1); exp15.addChildExp(new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("e"), new LeafExpressionNode("f"))); result = expander.expand(exp15); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.OR, nlResult.getOperator()); assertEquals(8, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("f", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(2); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(3); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("f", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(4); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(5); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("f", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("c", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(6); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("e", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(7); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("f", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); temp = (NonLeafExpressionNode) temp.getChildExps().get(0); assertEquals(Operator.AND, temp.getOperator()); assertEquals(2, temp.getChildExps().size()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); assertEquals("d", ((LeafExpressionNode) temp.getChildExps().get(1)).getIdentifier()); NonLeafExpressionNode exp16 = new NonLeafExpressionNode(Operator.NOT, new NonLeafExpressionNode(Operator.OR, new LeafExpressionNode("a"), new LeafExpressionNode( "b"))); result = expander.expand(exp16); assertTrue(result instanceof NonLeafExpressionNode); nlResult = (NonLeafExpressionNode) result; assertEquals(Operator.AND, nlResult.getOperator()); assertEquals(2, nlResult.getChildExps().size()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(0); assertEquals(Operator.NOT, temp.getOperator()); assertEquals("a", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); temp = (NonLeafExpressionNode) nlResult.getChildExps().get(1); assertEquals(Operator.NOT, temp.getOperator()); assertEquals("b", ((LeafExpressionNode) temp.getChildExps().get(0)).getIdentifier()); } |
NamespaceUpgrade implements Tool { void updateAcls(HRegion region) throws IOException { byte[] rowKey = Bytes.toBytes(NamespaceUpgrade.OLD_ACL); Get g = new Get(rowKey); Result r = region.get(g); if (r != null && r.size() > 0) { Put p = new Put(AccessControlLists.ACL_GLOBAL_NAME); for (Cell c : r.rawCells()) { p.addImmutable(CellUtil.cloneFamily(c), CellUtil.cloneQualifier(c), CellUtil.cloneValue(c)); } region.put(p); Delete del = new Delete(rowKey); region.delete(del); } rowKey = Bytes.toBytes(TableName.OLD_ROOT_STR); Delete del = new Delete(rowKey); region.delete(del); rowKey = Bytes.toBytes(TableName.OLD_META_STR); g = new Get(rowKey); r = region.get(g); if (r != null && r.size() > 0) { Put p = new Put(TableName.META_TABLE_NAME.getName()); for (Cell c : r.rawCells()) { p.addImmutable(CellUtil.cloneFamily(c), CellUtil.cloneQualifier(c), CellUtil.cloneValue(c)); } region.put(p); del = new Delete(rowKey); region.delete(del); } } NamespaceUpgrade(); void init(); void upgradeTableDirs(); void deleteRoot(); void migrateDotDirs(); void makeNamespaceDirs(); void migrateTables(); void migrateSnapshots(); void migrateMeta(); void migrateACL(); static boolean verifyNSUpgrade(FileSystem fs, Path rootDir); @Override int run(String[] args); @Override void setConf(Configuration conf); @Override Configuration getConf(); } | @Test (timeout = 300000) public void testACLTableMigration() throws IOException { Path rootDir = TEST_UTIL.getDataTestDirOnTestFS("testACLTable"); FileSystem fs = TEST_UTIL.getTestFileSystem(); Configuration conf = TEST_UTIL.getConfiguration(); byte[] FAMILY = Bytes.toBytes("l"); byte[] QUALIFIER = Bytes.toBytes("testUser"); byte[] VALUE = Bytes.toBytes("RWCA"); HTableDescriptor aclTable = new HTableDescriptor(TableName.valueOf("testACLTable")); aclTable.addFamily(new HColumnDescriptor(FAMILY)); FSTableDescriptors fstd = new FSTableDescriptors(fs, rootDir); fstd.createTableDescriptor(aclTable); HRegionInfo hriAcl = new HRegionInfo(aclTable.getTableName(), null, null); HRegion region = HRegion.createHRegion(hriAcl, rootDir, conf, aclTable); try { Put p = new Put(Bytes.toBytes("-ROOT-")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); p = new Put(Bytes.toBytes(".META.")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); p = new Put(Bytes.toBytes("_acl_")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); NamespaceUpgrade upgrade = new NamespaceUpgrade(); upgrade.updateAcls(region); Get g = new Get(Bytes.toBytes("-ROOT-")); Result r = region.get(g); assertTrue(r == null || r.size() == 0); g = new Get(AccessControlLists.ACL_TABLE_NAME.toBytes()); r = region.get(g); assertTrue(r != null && r.size() == 1); assertTrue(Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)) == 0); g = new Get(TableName.META_TABLE_NAME.toBytes()); r = region.get(g); assertTrue(r != null && r.size() == 1); assertTrue(Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)) == 0); } finally { region.close(); HRegionFileSystem.deleteRegionFromFileSystem(conf, fs, FSUtils.getTableDir(rootDir, hriAcl.getTable()), hriAcl); } }
@Test (timeout = 300000) public void testACLTableMigration() throws IOException { Path rootDir = TEST_UTIL.getDataTestDirOnTestFS("testACLTable"); FileSystem fs = TEST_UTIL.getTestFileSystem(); Configuration conf = TEST_UTIL.getConfiguration(); byte[] FAMILY = Bytes.toBytes("l"); byte[] QUALIFIER = Bytes.toBytes("testUser"); byte[] VALUE = Bytes.toBytes("RWCA"); HTableDescriptor aclTable = new HTableDescriptor(TableName.valueOf("testACLTable")); aclTable.addFamily(new HColumnDescriptor(FAMILY)); FSTableDescriptors fstd = new FSTableDescriptors(conf, fs, rootDir); fstd.createTableDescriptor(aclTable); HRegionInfo hriAcl = new HRegionInfo(aclTable.getTableName(), null, null); HRegion region = HRegion.createHRegion(hriAcl, rootDir, conf, aclTable); try { Put p = new Put(Bytes.toBytes("-ROOT-")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); p = new Put(Bytes.toBytes(".META.")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); p = new Put(Bytes.toBytes("_acl_")); p.addImmutable(FAMILY, QUALIFIER, VALUE); region.put(p); NamespaceUpgrade upgrade = new NamespaceUpgrade(); upgrade.updateAcls(region); Get g = new Get(Bytes.toBytes("-ROOT-")); Result r = region.get(g); assertTrue(r == null || r.size() == 0); g = new Get(AccessControlLists.ACL_TABLE_NAME.toBytes()); r = region.get(g); assertTrue(r != null && r.size() == 1); assertTrue(Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)) == 0); g = new Get(TableName.META_TABLE_NAME.toBytes()); r = region.get(g); assertTrue(r != null && r.size() == 1); assertTrue(Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIER)) == 0); } finally { region.close(); HRegionFileSystem.deleteRegionFromFileSystem(conf, fs, FSUtils.getTableDir(rootDir, hriAcl.getTable()), hriAcl); } } |
MultiRowResource extends ResourceBase implements Constants { @GET @Produces({ MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF }) public Response get(final @Context UriInfo uriInfo) { MultivaluedMap<String, String> params = uriInfo.getQueryParameters(); servlet.getMetrics().incrementRequests(1); try { CellSetModel model = new CellSetModel(); for (String rk : params.get(ROW_KEYS_PARAM_NAME)) { RowSpec rowSpec = new RowSpec(rk); if (this.versions != null) { rowSpec.setMaxVersions(this.versions); } ResultGenerator generator = ResultGenerator.fromRowSpec(this.tableResource.getName(), rowSpec, null, !params.containsKey(NOCACHE_PARAM_NAME)); Cell value = null; RowModel rowModel = new RowModel(rk); if (generator.hasNext()) { while ((value = generator.next()) != null) { rowModel.addCell(new CellModel(CellUtil.cloneFamily(value), CellUtil .cloneQualifier(value), value.getTimestamp(), CellUtil.cloneValue(value))); } model.addRow(rowModel); } else { LOG.trace("The row : " + rk + " not found in the table."); } } if (model.getRows().size() == 0) { servlet.getMetrics().incrementFailedGetRequests(1); return Response.status(Response.Status.NOT_FOUND) .type(MIMETYPE_TEXT).entity("No rows found." + CRLF) .build(); } else { servlet.getMetrics().incrementSucessfulGetRequests(1); return Response.ok(model).build(); } } catch (Exception e) { servlet.getMetrics().incrementFailedGetRequests(1); return processException(e); } } MultiRowResource(TableResource tableResource, String versions); @GET @Produces({ MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF }) Response get(final @Context UriInfo uriInfo); } | @Test public void testMultiCellGetJSONNotFound() throws IOException, JAXBException { String row_5_url = "/" + TABLE + "/" + ROW_1 + "/" + COLUMN_1; StringBuilder path = new StringBuilder(); path.append("/"); path.append(TABLE); path.append("/multiget/?row="); path.append(ROW_1); path.append("&row="); path.append(ROW_2); client.post(row_5_url, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_1)); Response response = client.get(path.toString(), Constants.MIMETYPE_JSON); assertEquals(response.getCode(), 200); ObjectMapper mapper = new JacksonProvider().locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE); CellSetModel cellSet = (CellSetModel) mapper.readValue(response.getBody(), CellSetModel.class); assertEquals(1, cellSet.getRows().size()); assertEquals(ROW_1, Bytes.toString(cellSet.getRows().get(0).getKey())); assertEquals(VALUE_1, Bytes.toString(cellSet.getRows().get(0).getCells().get(0).getValue())); client.delete(row_5_url); }
@Test public void testMultiCellGetJSON() throws IOException, JAXBException { String row_5_url = "/" + TABLE + "/" + ROW_1 + "/" + COLUMN_1; String row_6_url = "/" + TABLE + "/" + ROW_2 + "/" + COLUMN_2; StringBuilder path = new StringBuilder(); path.append("/"); path.append(TABLE); path.append("/multiget/?row="); path.append(ROW_1); path.append("&row="); path.append(ROW_2); client.post(row_5_url, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_1)); client.post(row_6_url, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_2)); Response response = client.get(path.toString(), Constants.MIMETYPE_JSON); assertEquals(response.getCode(), 200); assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type")); client.delete(row_5_url); client.delete(row_6_url); }
@Test public void testMultiCellGetXML() throws IOException, JAXBException { String row_5_url = "/" + TABLE + "/" + ROW_1 + "/" + COLUMN_1; String row_6_url = "/" + TABLE + "/" + ROW_2 + "/" + COLUMN_2; StringBuilder path = new StringBuilder(); path.append("/"); path.append(TABLE); path.append("/multiget/?row="); path.append(ROW_1); path.append("&row="); path.append(ROW_2); client.post(row_5_url, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_1)); client.post(row_6_url, Constants.MIMETYPE_BINARY, Bytes.toBytes(VALUE_2)); Response response = client.get(path.toString(), Constants.MIMETYPE_XML); assertEquals(response.getCode(), 200); assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type")); client.delete(row_5_url); client.delete(row_6_url); } |
BufferChain { byte [] getBytes() { if (!hasRemaining()) throw new IllegalAccessError(); byte [] bytes = new byte [this.remaining]; int offset = 0; for (ByteBuffer bb: this.buffers) { System.arraycopy(bb.array(), bb.arrayOffset(), bytes, offset, bb.limit()); offset += bb.capacity(); } return bytes; } BufferChain(ByteBuffer ... buffers); } | @Test public void testGetBackBytesWePutIn() { ByteBuffer[] bufs = wrapArrays(HELLO_WORLD_CHUNKS); BufferChain chain = new BufferChain(bufs); assertTrue(Bytes.equals(Bytes.toBytes("hello world"), chain.getBytes())); } |
BufferChain { long write(GatheringByteChannel channel, int chunkSize) throws IOException { int chunkRemaining = chunkSize; ByteBuffer lastBuffer = null; int bufCount = 0; int restoreLimit = -1; while (chunkRemaining > 0 && bufferOffset + bufCount < buffers.length) { lastBuffer = buffers[bufferOffset + bufCount]; if (!lastBuffer.hasRemaining()) { bufferOffset++; continue; } bufCount++; if (lastBuffer.remaining() > chunkRemaining) { restoreLimit = lastBuffer.limit(); lastBuffer.limit(lastBuffer.position() + chunkRemaining); chunkRemaining = 0; break; } else { chunkRemaining -= lastBuffer.remaining(); } } assert lastBuffer != null; if (chunkRemaining == chunkSize) { assert !hasRemaining(); return 0; } try { long ret = channel.write(buffers, bufferOffset, bufCount); if (ret > 0) { remaining -= ret; } return ret; } finally { if (restoreLimit >= 0) { lastBuffer.limit(restoreLimit); } } } BufferChain(ByteBuffer ... buffers); } | @Test public void testWithSpy() throws IOException { ByteBuffer[] bufs = new ByteBuffer[] { stringBuf("XXXhelloYYY", 3, 5), stringBuf(" ", 0, 1), stringBuf("XXXXworldY", 4, 5) }; BufferChain chain = new BufferChain(bufs); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel ch = Mockito.spy(fos.getChannel()); try { chain.write(ch, 2); assertEquals("he", Files.toString(tmpFile, Charsets.UTF_8)); chain.write(ch, 2); assertEquals("hell", Files.toString(tmpFile, Charsets.UTF_8)); chain.write(ch, 3); assertEquals("hello w", Files.toString(tmpFile, Charsets.UTF_8)); chain.write(ch, 8); assertEquals("hello world", Files.toString(tmpFile, Charsets.UTF_8)); } finally { ch.close(); fos.close(); } } |
CallRunner { public void run() { try { if (!call.connection.channel.isOpen()) { if (RpcServer.LOG.isDebugEnabled()) { RpcServer.LOG.debug(Thread.currentThread().getName() + ": skipped " + call); } return; } this.status.setStatus("Setting up call"); this.status.setConnection(call.connection.getHostAddress(), call.connection.getRemotePort()); if (RpcServer.LOG.isDebugEnabled()) { UserGroupInformation remoteUser = call.connection.user; RpcServer.LOG.debug(call.toShortString() + " executing as " + ((remoteUser == null) ? "NULL principal" : remoteUser.getUserName())); } Throwable errorThrowable = null; String error = null; Pair<Message, CellScanner> resultPair = null; RpcServer.CurCall.set(call); TraceScope traceScope = null; try { if (!this.rpcServer.isStarted()) { throw new ServerNotRunningYetException("Server is not running yet"); } if (call.tinfo != null) { traceScope = Trace.startSpan(call.toTraceString(), call.tinfo); } RequestContext.set(userProvider.create(call.connection.user), RpcServer.getRemoteIp(), call.connection.service); resultPair = this.rpcServer.call(call.service, call.md, call.param, call.cellScanner, call.timestamp, this.status); } catch (Throwable e) { RpcServer.LOG.debug(Thread.currentThread().getName() + ": " + call.toShortString(), e); errorThrowable = e; error = StringUtils.stringifyException(e); } finally { if (traceScope != null) { traceScope.close(); } RequestContext.clear(); } RpcServer.CurCall.set(null); this.rpcServer.addCallSize(call.getSize() * -1); if (!call.isDelayed() || !call.isReturnValueDelayed()) { Message param = resultPair != null ? resultPair.getFirst() : null; CellScanner cells = resultPair != null ? resultPair.getSecond() : null; call.setResponse(param, cells, errorThrowable, error); } call.sendResponseIfReady(); this.status.markComplete("Sent response"); this.status.pause("Waiting for a call"); } catch (OutOfMemoryError e) { if (this.rpcServer.getErrorHandler() != null) { if (this.rpcServer.getErrorHandler().checkOOME(e)) { RpcServer.LOG.info(Thread.currentThread().getName() + ": exiting on OutOfMemoryError"); return; } } else { throw e; } } catch (ClosedChannelException cce) { RpcServer.LOG.warn(Thread.currentThread().getName() + ": caught a ClosedChannelException, " + "this means that the server was processing a " + "request but the client went away. The error message was: " + cce.getMessage()); } catch (Exception e) { RpcServer.LOG.warn(Thread.currentThread().getName() + ": caught: " + StringUtils.stringifyException(e)); } } CallRunner(final RpcServerInterface rpcServer, final Call call, UserProvider userProvider); Call getCall(); void run(); } | @Test public void testSimpleCall() { RpcServerInterface mockRpcServer = Mockito.mock(RpcServerInterface.class); Mockito.when(mockRpcServer.isStarted()).thenReturn(true); RpcServer.Call mockCall = Mockito.mock(RpcServer.Call.class); mockCall.connection = Mockito.mock(RpcServer.Connection.class); CallRunner cr = new CallRunner(mockRpcServer, mockCall, new UserProvider()); cr.run(); } |
TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public int hashCode() { int result = tableName != null ? tableName.hashCode() : 0; result = 31 * result + (scan != null ? scan.hashCode() : 0); result = 31 * result + (startRow != null ? Arrays.hashCode(startRow) : 0); result = 31 * result + (endRow != null ? Arrays.hashCode(endRow) : 0); result = 31 * result + (regionLocation != null ? regionLocation.hashCode() : 0); return result; } TableSplit(); @Deprecated TableSplit(final byte [] tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location, long length); @Deprecated TableSplit(final byte [] tableName, byte[] startRow, byte[] endRow,
final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow,
final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow,
final String location, long length); Scan getScan(); byte [] getTableName(); TableName getTable(); byte [] getStartRow(); byte [] getEndRow(); String getRegionLocation(); @Override String[] getLocations(); @Override long getLength(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); @Override int compareTo(TableSplit split); @Override boolean equals(Object o); @Override int hashCode(); static final Log LOG; } | @Test public void testHashCode() { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location"); TableSplit split2 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location"); assertEquals (split1, split2); assertTrue (split1.hashCode() == split2.hashCode()); HashSet<TableSplit> set = new HashSet<TableSplit>(2); set.add(split1); set.add(split2); assertTrue(set.size() == 1); }
@Test public void testHashCode_length() { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location", 1984); TableSplit split2 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location", 1982); assertEquals (split1, split2); assertTrue (split1.hashCode() == split2.hashCode()); HashSet<TableSplit> set = new HashSet<TableSplit>(2); set.add(split1); set.add(split2); assertTrue(set.size() == 1); } |
TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public long getLength() { return length; } TableSplit(); @Deprecated TableSplit(final byte [] tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location); TableSplit(TableName tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location, long length); @Deprecated TableSplit(final byte [] tableName, byte[] startRow, byte[] endRow,
final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow,
final String location); TableSplit(TableName tableName, byte[] startRow, byte[] endRow,
final String location, long length); Scan getScan(); byte [] getTableName(); TableName getTable(); byte [] getStartRow(); byte [] getEndRow(); String getRegionLocation(); @Override String[] getLocations(); @Override long getLength(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); @Override int compareTo(TableSplit split); @Override boolean equals(Object o); @Override int hashCode(); static final Log LOG; } | @Test public void testLengthIsSerialized() throws Exception { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location", 666); TableSplit deserialized = new TableSplit(TableName.valueOf("table"), "row-start2".getBytes(), "row-end2".getBytes(), "location1"); ReflectionUtils.copy(new Configuration(), split1, deserialized); Assert.assertEquals(666, deserialized.getLength()); } |
LoadIncrementalHFiles extends Configured implements Tool { protected List<LoadQueueItem> splitStoreFile(final LoadQueueItem item, final HTable table, byte[] startKey, byte[] splitKey) throws IOException { final Path hfilePath = item.hfilePath; final Path tmpDir = new Path(item.hfilePath.getParent(), "_tmp"); LOG.info("HFile at " + hfilePath + " no longer fits inside a single " + "region. Splitting..."); String uniqueName = getUniqueName(table.getName()); HColumnDescriptor familyDesc = table.getTableDescriptor().getFamily(item.family); Path botOut = new Path(tmpDir, uniqueName + ".bottom"); Path topOut = new Path(tmpDir, uniqueName + ".top"); splitStoreFile(getConf(), hfilePath, familyDesc, splitKey, botOut, topOut); FileSystem fs = tmpDir.getFileSystem(getConf()); fs.setPermission(tmpDir, FsPermission.valueOf("-rwxrwxrwx")); fs.setPermission(botOut, FsPermission.valueOf("-rwxrwxrwx")); List<LoadQueueItem> lqis = new ArrayList<LoadQueueItem>(2); lqis.add(new LoadQueueItem(item.family, botOut)); lqis.add(new LoadQueueItem(item.family, topOut)); LOG.info("Successfully split into new HFiles " + botOut + " and " + topOut); return lqis; } LoadIncrementalHFiles(Configuration conf); @SuppressWarnings("deprecation") void doBulkLoad(Path hfofDir, final HTable table); static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap); @Override int run(String[] args); static void main(String[] args); static final String NAME; static final String MAX_FILES_PER_REGION_PER_FAMILY; } | @Test public void testSplitStoreFile() throws IOException { Path dir = util.getDataTestDirOnTestFS("testSplitHFile"); FileSystem fs = util.getTestFileSystem(); Path testIn = new Path(dir, "testhfile"); HColumnDescriptor familyDesc = new HColumnDescriptor(FAMILY); HFileTestUtil.createHFile(util.getConfiguration(), fs, testIn, FAMILY, QUALIFIER, Bytes.toBytes("aaa"), Bytes.toBytes("zzz"), 1000); Path bottomOut = new Path(dir, "bottom.out"); Path topOut = new Path(dir, "top.out"); LoadIncrementalHFiles.splitStoreFile( util.getConfiguration(), testIn, familyDesc, Bytes.toBytes("ggg"), bottomOut, topOut); int rowCount = verifyHFile(bottomOut); rowCount += verifyHFile(topOut); assertEquals(1000, rowCount); } |
LoadIncrementalHFiles extends Configured implements Tool { public static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap) { ArrayList<byte[]> keysArray = new ArrayList<byte[]>(); int runningValue = 0; byte[] currStartKey = null; boolean firstBoundary = true; for (Map.Entry<byte[], Integer> item: bdryMap.entrySet()) { if (runningValue == 0) currStartKey = item.getKey(); runningValue += item.getValue(); if (runningValue == 0) { if (!firstBoundary) keysArray.add(currStartKey); firstBoundary = false; } } return keysArray.toArray(new byte[0][0]); } LoadIncrementalHFiles(Configuration conf); @SuppressWarnings("deprecation") void doBulkLoad(Path hfofDir, final HTable table); static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap); @Override int run(String[] args); static void main(String[] args); static final String NAME; static final String MAX_FILES_PER_REGION_PER_FAMILY; } | @Test public void testInferBoundaries() { TreeMap<byte[], Integer> map = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); String first; String last; first = "a"; last = "e"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "r"; last = "s"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "o"; last = "p"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "g"; last = "k"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "v"; last = "x"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "c"; last = "i"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "m"; last = "q"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "s"; last = "t"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "u"; last = "w"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); byte[][] keysArray = LoadIncrementalHFiles.inferBoundaries(map); byte[][] compare = new byte[3][]; compare[0] = "m".getBytes(); compare[1] = "r".getBytes(); compare[2] = "u".getBytes(); assertEquals(keysArray.length, 3); for (int row = 0; row<keysArray.length; row++){ assertArrayEquals(keysArray[row], compare[row]); } } |
LoadIncrementalHFiles extends Configured implements Tool { @Override public int run(String[] args) throws Exception { if (args.length != 2) { usage(); return -1; } String dirPath = args[0]; TableName tableName = TableName.valueOf(args[1]); boolean tableExists = this.doesTableExist(tableName); if (!tableExists) this.createTable(tableName,dirPath); Path hfofDir = new Path(dirPath); HTable table = new HTable(getConf(), tableName); doBulkLoad(hfofDir, table); return 0; } LoadIncrementalHFiles(Configuration conf); @SuppressWarnings("deprecation") void doBulkLoad(Path hfofDir, final HTable table); static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap); @Override int run(String[] args); static void main(String[] args); static final String NAME; static final String MAX_FILES_PER_REGION_PER_FAMILY; } | @Test public void testLoadTooMayHFiles() throws Exception { Path dir = util.getDataTestDirOnTestFS("testLoadTooMayHFiles"); FileSystem fs = util.getTestFileSystem(); dir = dir.makeQualified(fs); Path familyDir = new Path(dir, Bytes.toString(FAMILY)); byte[] from = Bytes.toBytes("begin"); byte[] to = Bytes.toBytes("end"); for (int i = 0; i <= MAX_FILES_PER_REGION_PER_FAMILY; i++) { HFileTestUtil.createHFile(util.getConfiguration(), fs, new Path(familyDir, "hfile_" + i), FAMILY, QUALIFIER, from, to, 1000); } LoadIncrementalHFiles loader = new LoadIncrementalHFiles(util.getConfiguration()); String [] args= {dir.toString(), "mytable_testLoadTooMayHFiles"}; try { loader.run(args); fail("Bulk loading too many files should fail"); } catch (IOException ie) { assertTrue(ie.getMessage().contains("Trying to load more than " + MAX_FILES_PER_REGION_PER_FAMILY + " hfiles")); } } |
ScannerResource extends ResourceBase { @PUT @Consumes({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF}) public Response put(final ScannerModel model, final @Context UriInfo uriInfo) { if (LOG.isDebugEnabled()) { LOG.debug("PUT " + uriInfo.getAbsolutePath()); } return update(model, true, uriInfo); } ScannerResource(TableResource tableResource); @PUT @Consumes({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF}) Response put(final ScannerModel model,
final @Context UriInfo uriInfo); @POST @Consumes({MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF}) Response post(final ScannerModel model,
final @Context UriInfo uriInfo); @Path("{scanner: .+}") ScannerInstanceResource getScannerInstanceResource(
final @PathParam("scanner") String id); } | @Test public void testTableDoesNotExist() throws IOException, JAXBException { ScannerModel model = new ScannerModel(); StringWriter writer = new StringWriter(); marshaller.marshal(model, writer); byte[] body = Bytes.toBytes(writer.toString()); Response response = client.put("/" + NONEXISTENT_TABLE + "/scanner", Constants.MIMETYPE_XML, body); assertEquals(response.getCode(), 404); } |
CopyTable extends Configured implements Tool { public CopyTable(Configuration conf) { super(conf); } CopyTable(Configuration conf); static Job createSubmittableJob(Configuration conf, String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testCopyTable() throws Exception { final byte[] TABLENAME1 = Bytes.toBytes("testCopyTable1"); final byte[] TABLENAME2 = Bytes.toBytes("testCopyTable2"); final byte[] FAMILY = Bytes.toBytes("family"); final byte[] COLUMN1 = Bytes.toBytes("c1"); HTable t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY); HTable t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY); for (int i = 0; i < 10; i++) { Put p = new Put(Bytes.toBytes("row" + i)); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); } CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration()); assertEquals( 0, copy.run(new String[] { "--new.name=" + Bytes.toString(TABLENAME2), Bytes.toString(TABLENAME1) })); for (int i = 0; i < 10; i++) { Get g = new Get(Bytes.toBytes("row" + i)); Result r = t2.get(g); assertEquals(1, r.size()); assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1)); } t1.close(); t2.close(); TEST_UTIL.deleteTable(TABLENAME1); TEST_UTIL.deleteTable(TABLENAME2); } |
CopyTable extends Configured implements Tool { @Override public int run(String[] args) throws Exception { String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs(); Job job = createSubmittableJob(getConf(), otherArgs); if (job == null) return 1; return job.waitForCompletion(true) ? 0 : 1; } CopyTable(Configuration conf); static Job createSubmittableJob(Configuration conf, String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testStartStopRow() throws Exception { final byte[] TABLENAME1 = Bytes.toBytes("testStartStopRow1"); final byte[] TABLENAME2 = Bytes.toBytes("testStartStopRow2"); final byte[] FAMILY = Bytes.toBytes("family"); final byte[] COLUMN1 = Bytes.toBytes("c1"); final byte[] ROW0 = Bytes.toBytes("row0"); final byte[] ROW1 = Bytes.toBytes("row1"); final byte[] ROW2 = Bytes.toBytes("row2"); HTable t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY); HTable t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY); Put p = new Put(ROW0); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); p = new Put(ROW1); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); p = new Put(ROW2); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration()); assertEquals( 0, copy.run(new String[] { "--new.name=" + Bytes.toString(TABLENAME2), "--startrow=row1", "--stoprow=row2", Bytes.toString(TABLENAME1) })); Get g = new Get(ROW1); Result r = t2.get(g); assertEquals(1, r.size()); assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1)); g = new Get(ROW0); r = t2.get(g); assertEquals(0, r.size()); g = new Get(ROW2); r = t2.get(g); assertEquals(0, r.size()); t1.close(); t2.close(); TEST_UTIL.deleteTable(TABLENAME1); TEST_UTIL.deleteTable(TABLENAME2); } |
CopyTable extends Configured implements Tool { public static void main(String[] args) throws Exception { int ret = ToolRunner.run(new CopyTable(HBaseConfiguration.create()), args); System.exit(ret); } CopyTable(Configuration conf); static Job createSubmittableJob(Configuration conf, String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testMainMethod() throws Exception { String[] emptyArgs = { "-h" }; PrintStream oldWriter = System.err; ByteArrayOutputStream data = new ByteArrayOutputStream(); PrintStream writer = new PrintStream(data); System.setErr(writer); SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); try { CopyTable.main(emptyArgs); fail("should be exit"); } catch (SecurityException e) { assertEquals(1, newSecurityManager.getExitCode()); } finally { System.setErr(oldWriter); System.setSecurityManager(SECURITY_MANAGER); } assertTrue(data.toString().contains("rs.class")); assertTrue(data.toString().contains("Usage:")); } |
WALPlayer extends Configured implements Tool { public static void main(String[] args) throws Exception { int ret = ToolRunner.run(new WALPlayer(HBaseConfiguration.create()), args); System.exit(ret); } WALPlayer(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testMainMethod() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { WALPlayer.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("ERROR: Wrong number of arguments:")); assertTrue(data.toString().contains("Usage: WALPlayer [options] <wal inputdir>" + " <tables> [<tableMappings>]")); assertTrue(data.toString().contains("-Dhlog.bulk.output=/path/for/output")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } }
@Test public void testMainMethod() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { WALPlayer.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("ERROR: Wrong number of arguments:")); assertTrue(data.toString().contains("Usage: WALPlayer [options] <wal inputdir>" + " <tables> [<tableMappings>]")); assertTrue(data.toString().contains("-Dwal.bulk.output=/path/for/output")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } } |
ImportTsv extends Configured implements Tool { private static void createTable(HBaseAdmin admin, String tableName, String[] columns) throws IOException { HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName)); Set<String> cfSet = new HashSet<String>(); for (String aColumn : columns) { if (TsvParser.ROWKEY_COLUMN_SPEC.equals(aColumn) || TsvParser.TIMESTAMPKEY_COLUMN_SPEC.equals(aColumn) || TsvParser.CELL_VISIBILITY_COLUMN_SPEC.equals(aColumn) || TsvParser.ATTRIBUTES_COLUMN_SPEC.equals(aColumn)) continue; cfSet.add(aColumn.split(":", 2)[0]); } for (String cf : cfSet) { HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toBytes(cf)); htd.addFamily(hcd); } LOG.warn(format("Creating table '%s' with '%s' columns and default descriptors.", tableName, cfSet)); admin.createTable(htd); } static Job createSubmittableJob(Configuration conf, String[] args); @Override int run(String[] args); static void main(String[] args); final static String MAPPER_CONF_KEY; final static String BULK_OUTPUT_CONF_KEY; final static String TIMESTAMP_CONF_KEY; final static String JOB_NAME_CONF_KEY; final static String SKIP_LINES_CONF_KEY; final static String COLUMNS_CONF_KEY; final static String SEPARATOR_CONF_KEY; final static String ATTRIBUTE_SEPERATOR_CONF_KEY; final static String CREDENTIALS_LOCATION; } | @Test public void testMROnTable() throws Exception { String table = "test-" + UUID.randomUUID(); String[] args = new String[] { "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B", "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", table }; util.createTable(table, FAMILY); doMROnTableTest(util, FAMILY, null, args, 1); util.deleteTable(table); }
@Test public void testMROnTableWithTimestamp() throws Exception { String table = "test-" + UUID.randomUUID(); String[] args = new String[] { "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,HBASE_TS_KEY,FAM:A,FAM:B", "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=,", table }; String data = "KEY,1234,VALUE1,VALUE2\n"; util.createTable(table, FAMILY); doMROnTableTest(util, FAMILY, data, args, 1); util.deleteTable(table); }
@Test public void testMROnTableWithCustomMapper() throws Exception { String table = "test-" + UUID.randomUUID(); String[] args = new String[] { "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapper", table }; util.createTable(table, FAMILY); doMROnTableTest(util, FAMILY, null, args, 3); util.deleteTable(table); }
@Test public void testBulkOutputWithAnExistingTable() throws Exception { String table = "test-" + UUID.randomUUID(); Path hfiles = new Path(util.getDataTestDirOnTestFS(table), "hfiles"); String[] args = new String[] { "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B", "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(), table }; util.createTable(table, FAMILY); doMROnTableTest(util, FAMILY, null, args, 3); util.deleteTable(table); } |
ImportTsv extends Configured implements Tool { public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException, ClassNotFoundException { HBaseAdmin admin = new HBaseAdmin(conf); String actualSeparator = conf.get(SEPARATOR_CONF_KEY); if (actualSeparator != null) { conf.set(SEPARATOR_CONF_KEY, Base64.encodeBytes(actualSeparator.getBytes())); } String mapperClassName = conf.get(MAPPER_CONF_KEY); Class mapperClass = mapperClassName != null ? Class.forName(mapperClassName) : DEFAULT_MAPPER; String tableName = args[0]; Path inputDir = new Path(args[1]); String jobName = conf.get(JOB_NAME_CONF_KEY,NAME + "_" + tableName); Job job = new Job(conf, jobName); job.setJarByClass(mapperClass); FileInputFormat.setInputPaths(job, inputDir); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(mapperClass); String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY); String columns[] = conf.getStrings(COLUMNS_CONF_KEY); if(StringUtils.isNotEmpty(conf.get(CREDENTIALS_LOCATION))) { String fileLoc = conf.get(CREDENTIALS_LOCATION); Credentials cred = Credentials.readTokenStorageFile(new File(fileLoc), conf); job.getCredentials().addAll(cred); } if (hfileOutPath != null) { if (!admin.tableExists(tableName)) { LOG.warn(format("Table '%s' does not exist.", tableName)); createTable(admin, tableName, columns); } HTable table = new HTable(conf, tableName); job.setReducerClass(PutSortReducer.class); Path outputDir = new Path(hfileOutPath); FileOutputFormat.setOutputPath(job, outputDir); job.setMapOutputKeyClass(ImmutableBytesWritable.class); if (mapperClass.equals(TsvImporterTextMapper.class)) { job.setMapOutputValueClass(Text.class); job.setReducerClass(TextSortReducer.class); } else { job.setMapOutputValueClass(Put.class); job.setCombinerClass(PutCombiner.class); } HFileOutputFormat.configureIncrementalLoad(job, table); } else { if (mapperClass.equals(TsvImporterTextMapper.class)) { usage(TsvImporterTextMapper.class.toString() + " should not be used for non bulkloading case. use " + TsvImporterMapper.class.toString() + " or custom mapper whose value type is Put."); System.exit(-1); } TableMapReduceUtil.initTableReducerJob(tableName, null, job); job.setNumReduceTasks(0); } TableMapReduceUtil.addDependencyJars(job); TableMapReduceUtil.addDependencyJars(job.getConfiguration(), com.google.common.base.Function.class ); return job; } static Job createSubmittableJob(Configuration conf, String[] args); @Override int run(String[] args); static void main(String[] args); final static String MAPPER_CONF_KEY; final static String BULK_OUTPUT_CONF_KEY; final static String TIMESTAMP_CONF_KEY; final static String JOB_NAME_CONF_KEY; final static String SKIP_LINES_CONF_KEY; final static String COLUMNS_CONF_KEY; final static String SEPARATOR_CONF_KEY; final static String ATTRIBUTE_SEPERATOR_CONF_KEY; final static String CREDENTIALS_LOCATION; } | @Test public void testJobConfigurationsWithTsvImporterTextMapper() throws Exception { String table = "test-" + UUID.randomUUID(); Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table),"hfiles"); String INPUT_FILE = "InputFile1.csv"; String[] args = new String[] { "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper", "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B", "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=,", "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + bulkOutputPath.toString(), table, INPUT_FILE }; GenericOptionsParser opts = new GenericOptionsParser(util.getConfiguration(), args); args = opts.getRemainingArgs(); Job job = ImportTsv.createSubmittableJob(util.getConfiguration(), args); assertTrue(job.getMapperClass().equals(TsvImporterTextMapper.class)); assertTrue(job.getReducerClass().equals(TextSortReducer.class)); assertTrue(job.getMapOutputValueClass().equals(Text.class)); } |
HttpRequestLog { public static RequestLog getRequestLog(String name) { String lookup = serverToComponent.get(name); if (lookup != null) { name = lookup; } String loggerName = "http.requests." + name; String appenderName = name + "requestlog"; Log logger = LogFactory.getLog(loggerName); if (logger instanceof Log4JLogger) { Log4JLogger httpLog4JLog = (Log4JLogger)logger; Logger httpLogger = httpLog4JLog.getLogger(); Appender appender = null; try { appender = httpLogger.getAppender(appenderName); } catch (LogConfigurationException e) { LOG.warn("Http request log for " + loggerName + " could not be created"); throw e; } if (appender == null) { LOG.info("Http request log for " + loggerName + " is not defined"); return null; } if (appender instanceof HttpRequestLogAppender) { HttpRequestLogAppender requestLogAppender = (HttpRequestLogAppender)appender; NCSARequestLog requestLog = new NCSARequestLog(); requestLog.setFilename(requestLogAppender.getFilename()); requestLog.setRetainDays(requestLogAppender.getRetainDays()); return requestLog; } else { LOG.warn("Jetty request log for " + loggerName + " was of the wrong class"); return null; } } else { LOG.warn("Jetty request log can only be enabled using Log4j"); return null; } } static RequestLog getRequestLog(String name); static final Log LOG; } | @Test public void testAppenderUndefined() { RequestLog requestLog = HttpRequestLog.getRequestLog("test"); assertNull("RequestLog should be null", requestLog); }
@Test public void testAppenderDefined() { HttpRequestLogAppender requestLogAppender = new HttpRequestLogAppender(); requestLogAppender.setName("testrequestlog"); Logger.getLogger("http.requests.test").addAppender(requestLogAppender); RequestLog requestLog = HttpRequestLog.getRequestLog("test"); Logger.getLogger("http.requests.test").removeAppender(requestLogAppender); assertNotNull("RequestLog should not be null", requestLog); assertEquals("Class mismatch", NCSARequestLog.class, requestLog.getClass()); } |
TableMapReduceUtil { public static void initTableMapperJob(String table, Scan scan, Class<? extends TableMapper> mapper, Class<?> outputKeyClass, Class<?> outputValueClass, Job job) throws IOException { initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass, job, true); } static void initTableMapperJob(String table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job); static void initTableMapperJob(byte[] table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job); static void initTableMapperJob(String table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass); static void initTableMapperJob(String table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars, boolean initCredentials,
Class<? extends InputFormat> inputFormatClass); static void initTableMapperJob(byte[] table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass); static void initTableMapperJob(byte[] table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars); static void initTableMapperJob(String table, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars); static void resetCacheConfig(Configuration conf); static void initTableSnapshotMapperJob(String snapshotName, Scan scan,
Class<? extends TableMapper> mapper,
Class<?> outputKeyClass,
Class<?> outputValueClass, Job job,
boolean addDependencyJars, Path tmpRestoreDir); static void initTableMapperJob(List<Scan> scans,
Class<? extends TableMapper> mapper,
Class<? extends WritableComparable> outputKeyClass,
Class<? extends Writable> outputValueClass, Job job); static void initTableMapperJob(List<Scan> scans,
Class<? extends TableMapper> mapper,
Class<? extends WritableComparable> outputKeyClass,
Class<? extends Writable> outputValueClass, Job job,
boolean addDependencyJars); static void initTableMapperJob(List<Scan> scans,
Class<? extends TableMapper> mapper,
Class<? extends WritableComparable> outputKeyClass,
Class<? extends Writable> outputValueClass, Job job,
boolean addDependencyJars,
boolean initCredentials); static void initCredentials(Job job); static void initCredentialsForCluster(Job job, String quorumAddress); static void initTableReducerJob(String table,
Class<? extends TableReducer> reducer, Job job); static void initTableReducerJob(String table,
Class<? extends TableReducer> reducer, Job job,
Class partitioner); static void initTableReducerJob(String table,
Class<? extends TableReducer> reducer, Job job,
Class partitioner, String quorumAddress, String serverClass,
String serverImpl); static void initTableReducerJob(String table,
Class<? extends TableReducer> reducer, Job job,
Class partitioner, String quorumAddress, String serverClass,
String serverImpl, boolean addDependencyJars); static void limitNumReduceTasks(String table, Job job); static void setNumReduceTasks(String table, Job job); static void setScannerCaching(Job job, int batchSize); static void addHBaseDependencyJars(Configuration conf); static String buildDependencyClasspath(Configuration conf); static void addDependencyJars(Job job); static void addDependencyJars(Configuration conf,
Class<?>... classes); } | @Test public void testInitTableMapperJob1() throws Exception { Configuration configuration = new Configuration(); Job job = new Job(configuration, "tableName"); TableMapReduceUtil.initTableMapperJob("Table", new Scan(), Import.Importer.class, Text.class, Text.class, job, false, HLogInputFormat.class); assertEquals(HLogInputFormat.class, job.getInputFormatClass()); assertEquals(Import.Importer.class, job.getMapperClass()); assertEquals(LongWritable.class, job.getOutputKeyClass()); assertEquals(Text.class, job.getOutputValueClass()); assertNull(job.getCombinerClass()); assertEquals("Table", job.getConfiguration().get(TableInputFormat.INPUT_TABLE)); }
@Test public void testInitTableMapperJob2() throws Exception { Configuration configuration = new Configuration(); Job job = new Job(configuration, "tableName"); TableMapReduceUtil.initTableMapperJob(Bytes.toBytes("Table"), new Scan(), Import.Importer.class, Text.class, Text.class, job, false, HLogInputFormat.class); assertEquals(HLogInputFormat.class, job.getInputFormatClass()); assertEquals(Import.Importer.class, job.getMapperClass()); assertEquals(LongWritable.class, job.getOutputKeyClass()); assertEquals(Text.class, job.getOutputValueClass()); assertNull(job.getCombinerClass()); assertEquals("Table", job.getConfiguration().get(TableInputFormat.INPUT_TABLE)); }
@Test public void testInitTableMapperJob3() throws Exception { Configuration configuration = new Configuration(); Job job = new Job(configuration, "tableName"); TableMapReduceUtil.initTableMapperJob(Bytes.toBytes("Table"), new Scan(), Import.Importer.class, Text.class, Text.class, job); assertEquals(TableInputFormat.class, job.getInputFormatClass()); assertEquals(Import.Importer.class, job.getMapperClass()); assertEquals(LongWritable.class, job.getOutputKeyClass()); assertEquals(Text.class, job.getOutputValueClass()); assertNull(job.getCombinerClass()); assertEquals("Table", job.getConfiguration().get(TableInputFormat.INPUT_TABLE)); }
@Test public void testInitTableMapperJob4() throws Exception { Configuration configuration = new Configuration(); Job job = new Job(configuration, "tableName"); TableMapReduceUtil.initTableMapperJob(Bytes.toBytes("Table"), new Scan(), Import.Importer.class, Text.class, Text.class, job, false); assertEquals(TableInputFormat.class, job.getInputFormatClass()); assertEquals(Import.Importer.class, job.getMapperClass()); assertEquals(LongWritable.class, job.getOutputKeyClass()); assertEquals(Text.class, job.getOutputValueClass()); assertNull(job.getCombinerClass()); assertEquals("Table", job.getConfiguration().get(TableInputFormat.INPUT_TABLE)); } |
JarFinder { public static String getJar(Class klass) { Preconditions.checkNotNull(klass, "klass"); ClassLoader loader = klass.getClassLoader(); if (loader != null) { String class_file = klass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements(); ) { URL url = (URL) itr.nextElement(); String path = url.getPath(); if (path.startsWith("file:")) { path = path.substring("file:".length()); } path = URLDecoder.decode(path, "UTF-8"); if ("jar".equals(url.getProtocol())) { path = URLDecoder.decode(path, "UTF-8"); return path.replaceAll("!.*$", ""); } else if ("file".equals(url.getProtocol())) { String klassName = klass.getName(); klassName = klassName.replace(".", "/") + ".class"; path = path.substring(0, path.length() - klassName.length()); File baseDir = new File(path); File testDir = new File(System.getProperty("test.build.dir", "target/test-dir")); testDir = testDir.getAbsoluteFile(); if (!testDir.exists()) { testDir.mkdirs(); } File tempJar = File.createTempFile("hadoop-", "", testDir); tempJar = new File(tempJar.getAbsolutePath() + ".jar"); createJar(baseDir, tempJar); return tempJar.getAbsolutePath(); } } } catch (IOException e) { throw new RuntimeException(e); } } return null; } static void jarDir(File dir, String relativePath, ZipOutputStream zos); static String getJar(Class klass); } | @Test public void testJar() throws Exception { String jar = JarFinder.getJar(LogFactory.class); Assert.assertTrue(new File(jar).exists()); }
@Test public void testExpandedClasspath() throws Exception { String jar = JarFinder.getJar(TestJarFinder.class); Assert.assertTrue(new File(jar).exists()); } |
JarFinder { public static void jarDir(File dir, String relativePath, ZipOutputStream zos) throws IOException { Preconditions.checkNotNull(relativePath, "relativePath"); Preconditions.checkNotNull(zos, "zos"); File manifestFile = new File(dir, JarFile.MANIFEST_NAME); ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); if (!manifestFile.exists()) { zos.putNextEntry(manifestEntry); new Manifest().write(new BufferedOutputStream(zos)); zos.closeEntry(); } else { copyToZipStream(manifestFile, manifestEntry, zos); } zos.closeEntry(); zipDir(dir, relativePath, zos, true); zos.close(); } static void jarDir(File dir, String relativePath, ZipOutputStream zos); static String getJar(Class klass); } | @Test public void testExistingManifest() throws Exception { File dir = new File(System.getProperty("test.build.dir", "target/test-dir"), TestJarFinder.class.getName() + "-testExistingManifest"); delete(dir); dir.mkdirs(); File metaInfDir = new File(dir, "META-INF"); metaInfDir.mkdirs(); File manifestFile = new File(metaInfDir, "MANIFEST.MF"); Manifest manifest = new Manifest(); OutputStream os = new FileOutputStream(manifestFile); manifest.write(os); os.close(); File propsFile = new File(dir, "props.properties"); Writer writer = new FileWriter(propsFile); new Properties().store(writer, ""); writer.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JarOutputStream zos = new JarOutputStream(baos); JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); Assert.assertNotNull(jis.getManifest()); jis.close(); }
@Test public void testNoManifest() throws Exception { File dir = new File(System.getProperty("test.build.dir", "target/test-dir"), TestJarFinder.class.getName() + "-testNoManifest"); delete(dir); dir.mkdirs(); File propsFile = new File(dir, "props.properties"); Writer writer = new FileWriter(propsFile); new Properties().store(writer, ""); writer.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JarOutputStream zos = new JarOutputStream(baos); JarFinder.jarDir(dir, "", zos); JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray())); Assert.assertNotNull(jis.getManifest()); jis.close(); } |
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { public RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter( final TaskAttemptContext context) throws IOException, InterruptedException { return HFileOutputFormat2.createRecordWriter(context); } RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter(
final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; } | @Test public void test_LATEST_TIMESTAMP_isReplaced() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, KeyValue> writer = null; TaskAttemptContext context = null; Path dir = util.getDataTestDir("test_LATEST_TIMESTAMP_isReplaced"); try { Job job = new Job(conf); FileOutputFormat.setOutputPath(job, dir); context = createTestTaskAttemptContext(job); HFileOutputFormat hof = new HFileOutputFormat(); writer = hof.getRecordWriter(context); final byte [] b = Bytes.toBytes("b"); KeyValue kv = new KeyValue(b, b, b); KeyValue original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertFalse(original.equals(kv)); assertTrue(Bytes.equals(original.getRow(), kv.getRow())); assertTrue(CellUtil.matchingColumn(original, kv.getFamily(), kv.getQualifier())); assertNotSame(original.getTimestamp(), kv.getTimestamp()); assertNotSame(HConstants.LATEST_TIMESTAMP, kv.getTimestamp()); kv = new KeyValue(b, b, b, kv.getTimestamp() - 1, b); original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertTrue(original.equals(kv)); } finally { if (writer != null && context != null) writer.close(context); dir.getFileSystem(conf).delete(dir, true); } }
@Test public void test_TIMERANGE() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, KeyValue> writer = null; TaskAttemptContext context = null; Path dir = util.getDataTestDir("test_TIMERANGE_present"); LOG.info("Timerange dir writing to dir: "+ dir); try { Job job = new Job(conf); FileOutputFormat.setOutputPath(job, dir); context = createTestTaskAttemptContext(job); HFileOutputFormat hof = new HFileOutputFormat(); writer = hof.getRecordWriter(context); final byte [] b = Bytes.toBytes("b"); KeyValue kv = new KeyValue(b, b, b, 2000, b); KeyValue original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertEquals(original,kv); kv = new KeyValue(b, b, b, 1000, b); original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertEquals(original, kv); writer.close(context); FileSystem fs = FileSystem.get(conf); Path attemptDirectory = hof.getDefaultWorkFile(context, "").getParent(); FileStatus[] sub1 = fs.listStatus(attemptDirectory); FileStatus[] file = fs.listStatus(sub1[0].getPath()); HFile.Reader rd = HFile.createReader(fs, file[0].getPath(), new CacheConfig(conf), conf); Map<byte[],byte[]> finfo = rd.loadFileInfo(); byte[] range = finfo.get("TIMERANGE".getBytes()); assertNotNull(range); TimeRangeTracker timeRangeTracker = new TimeRangeTracker(); Writables.copyWritable(range, timeRangeTracker); LOG.info(timeRangeTracker.getMinimumTimestamp() + "...." + timeRangeTracker.getMaximumTimestamp()); assertEquals(1000, timeRangeTracker.getMinimumTimestamp()); assertEquals(2000, timeRangeTracker.getMaximumTimestamp()); rd.close(); } finally { if (writer != null && context != null) writer.close(context); dir.getFileSystem(conf).delete(dir, true); } } |
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { public static void configureIncrementalLoad(Job job, HTable table) throws IOException { HFileOutputFormat2.configureIncrementalLoad(job, table, HFileOutputFormat.class); } RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter(
final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; } | @Test public void testJobConfiguration() throws Exception { Job job = new Job(util.getConfiguration()); job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration")); HTable table = Mockito.mock(HTable.class); setupMockStartKeys(table); HFileOutputFormat.configureIncrementalLoad(job, table); assertEquals(job.getNumReduceTasks(), 4); } |
HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> { public RecordWriter<ImmutableBytesWritable, Cell> getRecordWriter( final TaskAttemptContext context) throws IOException, InterruptedException { return createRecordWriter(context); } RecordWriter<ImmutableBytesWritable, Cell> getRecordWriter(
final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; } | @Test public void test_LATEST_TIMESTAMP_isReplaced() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, Cell> writer = null; TaskAttemptContext context = null; Path dir = util.getDataTestDir("test_LATEST_TIMESTAMP_isReplaced"); try { Job job = new Job(conf); FileOutputFormat.setOutputPath(job, dir); context = createTestTaskAttemptContext(job); HFileOutputFormat2 hof = new HFileOutputFormat2(); writer = hof.getRecordWriter(context); final byte [] b = Bytes.toBytes("b"); KeyValue kv = new KeyValue(b, b, b); KeyValue original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertFalse(original.equals(kv)); assertTrue(Bytes.equals(CellUtil.cloneRow(original), CellUtil.cloneRow(kv))); assertTrue(Bytes.equals(CellUtil.cloneFamily(original), CellUtil.cloneFamily(kv))); assertTrue(Bytes.equals(CellUtil.cloneQualifier(original), CellUtil.cloneQualifier(kv))); assertNotSame(original.getTimestamp(), kv.getTimestamp()); assertNotSame(HConstants.LATEST_TIMESTAMP, kv.getTimestamp()); kv = new KeyValue(b, b, b, kv.getTimestamp() - 1, b); original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertTrue(original.equals(kv)); } finally { if (writer != null && context != null) writer.close(context); dir.getFileSystem(conf).delete(dir, true); } }
@Test public void test_TIMERANGE() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, Cell> writer = null; TaskAttemptContext context = null; Path dir = util.getDataTestDir("test_TIMERANGE_present"); LOG.info("Timerange dir writing to dir: "+ dir); try { Job job = new Job(conf); FileOutputFormat.setOutputPath(job, dir); context = createTestTaskAttemptContext(job); HFileOutputFormat2 hof = new HFileOutputFormat2(); writer = hof.getRecordWriter(context); final byte [] b = Bytes.toBytes("b"); KeyValue kv = new KeyValue(b, b, b, 2000, b); KeyValue original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertEquals(original,kv); kv = new KeyValue(b, b, b, 1000, b); original = kv.clone(); writer.write(new ImmutableBytesWritable(), kv); assertEquals(original, kv); writer.close(context); FileSystem fs = FileSystem.get(conf); Path attemptDirectory = hof.getDefaultWorkFile(context, "").getParent(); FileStatus[] sub1 = fs.listStatus(attemptDirectory); FileStatus[] file = fs.listStatus(sub1[0].getPath()); HFile.Reader rd = HFile.createReader(fs, file[0].getPath(), new CacheConfig(conf), conf); Map<byte[],byte[]> finfo = rd.loadFileInfo(); byte[] range = finfo.get("TIMERANGE".getBytes()); assertNotNull(range); TimeRangeTracker timeRangeTracker = new TimeRangeTracker(); Writables.copyWritable(range, timeRangeTracker); LOG.info(timeRangeTracker.getMinimumTimestamp() + "...." + timeRangeTracker.getMaximumTimestamp()); assertEquals(1000, timeRangeTracker.getMinimumTimestamp()); assertEquals(2000, timeRangeTracker.getMaximumTimestamp()); rd.close(); } finally { if (writer != null && context != null) writer.close(context); dir.getFileSystem(conf).delete(dir, true); } } |
HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> { public static void configureIncrementalLoad(Job job, HTable table) throws IOException { configureIncrementalLoad(job, table, HFileOutputFormat2.class); } RecordWriter<ImmutableBytesWritable, Cell> getRecordWriter(
final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); static final String DATABLOCK_ENCODING_OVERRIDE_CONF_KEY; } | @Test public void testJobConfiguration() throws Exception { Job job = new Job(util.getConfiguration()); job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration")); HTable table = Mockito.mock(HTable.class); setupMockStartKeys(table); HFileOutputFormat2.configureIncrementalLoad(job, table); assertEquals(job.getNumReduceTasks(), 4); } |
RowCounter { public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 1) { printUsage("Wrong number of parameters: " + args.length); System.exit(-1); } Job job = createSubmittableJob(conf, otherArgs); if (job == null) { System.exit(-1); } System.exit(job.waitForCompletion(true) ? 0 : 1); } static Job createSubmittableJob(Configuration conf, String[] args); static void main(String[] args); } | @Test public void testImportMain() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("Wrong number of parameters:")); assertTrue(data.toString().contains( "Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100")); assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false")); } data.reset(); try { args = new String[2]; args[0] = "table"; args[1] = "--range=1"; RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains( "Please specify range in such format as \"--range=a,b\" or, with only one boundary," + " \"--range=,b\" or \"--range=a,\"")); assertTrue(data.toString().contains( "Usage: RowCounter [options] <tablename> [--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } }
@Test public void testImportMain() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager = new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("Wrong number of parameters:")); assertTrue(data.toString().contains("Usage: RowCounter [options] <tablename> " + "[--starttime=[start] --endtime=[end] " + "[--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); assertTrue(data.toString().contains("-Dhbase.client.scanner.caching=100")); assertTrue(data.toString().contains("-Dmapreduce.map.speculative=false")); } data.reset(); try { args = new String[2]; args[0] = "table"; args[1] = "--range=1"; RowCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("Please specify range in such format as \"--range=a,b\" or, with only one boundary," + " \"--range=,b\" or \"--range=a,\"")); assertTrue(data.toString().contains("Usage: RowCounter [options] <tablename> " + "[--starttime=[start] --endtime=[end] " + "[--range=[startKey],[endKey]] " + "[<column1> <column2>...]")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } } |
CellCounter { public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 1) { System.err.println("ERROR: Wrong number of parameters: " + args.length); System.err.println("Usage: CellCounter <tablename> <outputDir> <reportSeparator> " + "[^[regex pattern] or [Prefix] for row filter]] "); System.err.println(" Note: -D properties will be applied to the conf used. "); System.err.println(" Additionally, the following SCAN properties can be specified"); System.err.println(" to get fine grained control on what is counted.."); System.err.println(" -D " + TableInputFormat.SCAN_COLUMN_FAMILY + "=<familyName>"); System.err.println(" <reportSeparator> parameter can be used to override the default report separator " + "string : used to separate the rowId/column family name and qualifier name."); System.err.println(" [^[regex pattern] or [Prefix] parameter can be used to limit the cell counter count " + "operation to a limited subset of rows from the table based on regex or prefix pattern."); System.exit(-1); } Job job = createSubmittableJob(conf, otherArgs); System.exit(job.waitForCompletion(true) ? 0 : 1); } static Job createSubmittableJob(Configuration conf, String[] args); static void main(String[] args); } | @Test (timeout=300000) public void testCellCounterMain() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputStream data = new ByteArrayOutputStream(); String[] args = {}; System.setErr(new PrintStream(data)); try { System.setErr(new PrintStream(data)); try { CellCounter.main(args); fail("should be SecurityException"); } catch (SecurityException e) { assertEquals(-1, newSecurityManager.getExitCode()); assertTrue(data.toString().contains("ERROR: Wrong number of parameters:")); assertTrue(data.toString().contains("Usage:")); } } finally { System.setErr(oldPrintStream); System.setSecurityManager(SECURITY_MANAGER); } } |
ReplicationSink { public void replicateEntries(List<WALEntry> entries, final CellScanner cells) throws IOException { if (entries.isEmpty()) return; if (cells == null) throw new NullPointerException("TODO: Add handling of null CellScanner"); try { long totalReplicated = 0; Map<TableName, Map<List<UUID>, List<Row>>> rowMap = new TreeMap<TableName, Map<List<UUID>, List<Row>>>(); for (WALEntry entry : entries) { TableName table = TableName.valueOf(entry.getKey().getTableName().toByteArray()); Cell previousCell = null; Mutation m = null; int count = entry.getAssociatedCellCount(); for (int i = 0; i < count; i++) { if (!cells.advance()) { throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i); } Cell cell = cells.current(); if (isNewRowOrType(previousCell, cell)) { m = CellUtil.isDelete(cell)? new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()): new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()); List<UUID> clusterIds = new ArrayList<UUID>(); for(HBaseProtos.UUID clusterId : entry.getKey().getClusterIdsList()){ clusterIds.add(toUUID(clusterId)); } m.setClusterIds(clusterIds); addToHashMultiMap(rowMap, table, clusterIds, m); } if (CellUtil.isDelete(cell)) { ((Delete)m).addDeleteMarker(KeyValueUtil.ensureKeyValue(cell)); } else { ((Put)m).add(KeyValueUtil.ensureKeyValue(cell)); } previousCell = cell; } totalReplicated++; } for (Entry<TableName, Map<List<UUID>,List<Row>>> entry : rowMap.entrySet()) { batch(entry.getKey(), entry.getValue().values()); } int size = entries.size(); this.metrics.setAgeOfLastAppliedOp(entries.get(size - 1).getKey().getWriteTime()); this.metrics.applyBatch(size); this.totalReplicatedEdits.addAndGet(totalReplicated); } catch (IOException ex) { LOG.error("Unable to accept edit because:", ex); throw ex; } } ReplicationSink(Configuration conf, Stoppable stopper); void replicateEntries(List<WALEntry> entries, final CellScanner cells); void stopReplicationSinkServices(); String getStats(); } | @Test public void testBatchSink() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(BATCH_SIZE); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < BATCH_SIZE; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); Scan scan = new Scan(); ResultScanner scanRes = table1.getScanner(scan); assertEquals(BATCH_SIZE, scanRes.next(BATCH_SIZE).length); }
@Test public void testMixedPutDelete() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(BATCH_SIZE/2); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < BATCH_SIZE/2; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells)); entries = new ArrayList<WALEntry>(BATCH_SIZE); cells = new ArrayList<Cell>(); for(int i = 0; i < BATCH_SIZE; i++) { entries.add(createEntry(TABLE_NAME1, i, i % 2 != 0 ? KeyValue.Type.Put: KeyValue.Type.DeleteColumn, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); Scan scan = new Scan(); ResultScanner scanRes = table1.getScanner(scan); assertEquals(BATCH_SIZE/2, scanRes.next(BATCH_SIZE).length); }
@Test public void testMixedPutTables() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(BATCH_SIZE/2); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < BATCH_SIZE; i++) { entries.add(createEntry( i % 2 == 0 ? TABLE_NAME2 : TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); Scan scan = new Scan(); ResultScanner scanRes = table2.getScanner(scan); for(Result res : scanRes) { assertTrue(Bytes.toInt(res.getRow()) % 2 == 0); } }
@Test public void testMixedDeletes() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(3); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < 3; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); entries = new ArrayList<WALEntry>(3); cells = new ArrayList<Cell>(); entries.add(createEntry(TABLE_NAME1, 0, KeyValue.Type.DeleteColumn, cells)); entries.add(createEntry(TABLE_NAME1, 1, KeyValue.Type.DeleteFamily, cells)); entries.add(createEntry(TABLE_NAME1, 2, KeyValue.Type.DeleteColumn, cells)); SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); Scan scan = new Scan(); ResultScanner scanRes = table1.getScanner(scan); assertEquals(0, scanRes.next(3).length); }
@Test public void testApplyDeleteBeforePut() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(5); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < 2; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } entries.add(createEntry(TABLE_NAME1, 1, KeyValue.Type.DeleteFamily, cells)); for(int i = 3; i < 5; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScanner(cells.iterator())); Get get = new Get(Bytes.toBytes(1)); Result res = table1.get(get); assertEquals(0, res.size()); } |
ReplicationSourceManager implements ReplicationListener { protected void init() throws IOException, ReplicationException { for (String id : this.replicationPeers.getConnectedPeers()) { addSource(id); } List<String> currentReplicators = this.replicationQueues.getListOfReplicators(); if (currentReplicators == null || currentReplicators.size() == 0) { return; } List<String> otherRegionServers = replicationTracker.getListOfRegionServers(); LOG.info("Current list of replicators: " + currentReplicators + " other RSs: " + otherRegionServers); for (String rs : currentReplicators) { if (!otherRegionServers.contains(rs)) { transferQueues(rs); } } } ReplicationSourceManager(final ReplicationQueues replicationQueues,
final ReplicationPeers replicationPeers, final ReplicationTracker replicationTracker,
final Configuration conf, final Stoppable stopper, final FileSystem fs, final Path logDir,
final Path oldLogDir, final UUID clusterId); void logPositionAndCleanOldLogs(Path log, String id, long position,
boolean queueRecovered, boolean holdLogInZK); void cleanOldLogs(String key,
String id,
boolean queueRecovered); void deleteSource(String peerId, boolean closeConnection); void join(); List<ReplicationSourceInterface> getSources(); List<ReplicationSourceInterface> getOldSources(); void closeRecoveredQueue(ReplicationSourceInterface src); void removePeer(String id); @Override void regionServerRemoved(String regionserver); @Override void peerRemoved(String peerId); @Override void peerListChanged(List<String> peerIds); Path getOldLogDir(); Path getLogDir(); FileSystem getFs(); String getStats(); } | @Test public void testClaimQueues() throws Exception { LOG.debug("testNodeFailoverWorkerCopyQueuesFromRSUsingMulti"); conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true); final Server server = new DummyServer("hostname0.example.org"); ReplicationQueues rq = ReplicationFactory.getReplicationQueues(server.getZooKeeper(), server.getConfiguration(), server); rq.init(server.getServerName().toString()); files.add("log1"); files.add("log2"); for (String file : files) { rq.addLog("1", file); } Server s1 = new DummyServer("dummyserver1.example.org"); Server s2 = new DummyServer("dummyserver2.example.org"); Server s3 = new DummyServer("dummyserver3.example.org"); DummyNodeFailoverWorker w1 = new DummyNodeFailoverWorker( server.getServerName().getServerName(), s1); DummyNodeFailoverWorker w2 = new DummyNodeFailoverWorker( server.getServerName().getServerName(), s2); DummyNodeFailoverWorker w3 = new DummyNodeFailoverWorker( server.getServerName().getServerName(), s3); latch = new CountDownLatch(3); w1.start(); w2.start(); w3.start(); int populatedMap = 0; latch.await(); populatedMap += w1.isLogZnodesMapPopulated() + w2.isLogZnodesMapPopulated() + w3.isLogZnodesMapPopulated(); assertEquals(1, populatedMap); server.abort("", null); }
@Test public void testNodeFailoverDeadServerParsing() throws Exception { LOG.debug("testNodeFailoverDeadServerParsing"); conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true); final Server server = new DummyServer("ec2-54-234-230-108.compute-1.amazonaws.com"); ReplicationQueues repQueues = ReplicationFactory.getReplicationQueues(server.getZooKeeper(), conf, server); repQueues.init(server.getServerName().toString()); files.add("log1"); files.add("log2"); for (String file : files) { repQueues.addLog("1", file); } Server s1 = new DummyServer("ip-10-8-101-114.ec2.internal"); Server s2 = new DummyServer("ec2-107-20-52-47.compute-1.amazonaws.com"); Server s3 = new DummyServer("ec2-23-20-187-167.compute-1.amazonaws.com"); ReplicationQueues rq1 = ReplicationFactory.getReplicationQueues(s1.getZooKeeper(), s1.getConfiguration(), s1); rq1.init(s1.getServerName().toString()); SortedMap<String, SortedSet<String>> testMap = rq1.claimQueues(server.getServerName().getServerName()); ReplicationQueues rq2 = ReplicationFactory.getReplicationQueues(s2.getZooKeeper(), s2.getConfiguration(), s2); rq2.init(s2.getServerName().toString()); testMap = rq2.claimQueues(s1.getServerName().getServerName()); ReplicationQueues rq3 = ReplicationFactory.getReplicationQueues(s3.getZooKeeper(), s3.getConfiguration(), s3); rq3.init(s3.getServerName().toString()); testMap = rq3.claimQueues(s2.getServerName().getServerName()); ReplicationQueueInfo replicationQueueInfo = new ReplicationQueueInfo(testMap.firstKey()); List<String> result = replicationQueueInfo.getDeadRegionServers(); assertTrue(result.contains(server.getServerName().getServerName())); assertTrue(result.contains(s1.getServerName().getServerName())); assertTrue(result.contains(s2.getServerName().getServerName())); server.abort("", null); } |
ReplicationSinkManager { void chooseSinks() { List<ServerName> slaveAddresses = replicationPeers.getRegionServersOfConnectedPeer(peerClusterId); Collections.shuffle(slaveAddresses, random); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); lastUpdateToPeers = System.currentTimeMillis(); badReportCounts.clear(); } ReplicationSinkManager(HConnection conn, String peerClusterId,
ReplicationPeers replicationPeers, Configuration conf); SinkPeer getReplicationSink(); void reportBadSink(SinkPeer sinkPeer); } | @Test public void testChooseSinks() { List<ServerName> serverNames = Lists.newArrayList(); for (int i = 0; i < 20; i++) { serverNames.add(mock(ServerName.class)); } when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID)) .thenReturn(serverNames); sinkManager.chooseSinks(); assertEquals(2, sinkManager.getSinks().size()); } |
ReplicationSinkManager { public void reportBadSink(SinkPeer sinkPeer) { ServerName serverName = sinkPeer.getServerName(); int badReportCount = (badReportCounts.containsKey(serverName) ? badReportCounts.get(serverName) : 0) + 1; badReportCounts.put(serverName, badReportCount); if (badReportCount > badSinkThreshold) { this.sinks.remove(serverName); if (sinks.isEmpty()) { chooseSinks(); } } } ReplicationSinkManager(HConnection conn, String peerClusterId,
ReplicationPeers replicationPeers, Configuration conf); SinkPeer getReplicationSink(); void reportBadSink(SinkPeer sinkPeer); } | @Test public void testReportBadSink() { ServerName serverNameA = mock(ServerName.class); ServerName serverNameB = mock(ServerName.class); when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID)).thenReturn( Lists.newArrayList(serverNameA, serverNameB)); sinkManager.chooseSinks(); assertEquals(1, sinkManager.getSinks().size()); SinkPeer sinkPeer = new SinkPeer(serverNameA, mock(AdminService.BlockingInterface.class)); sinkManager.reportBadSink(sinkPeer); assertEquals(1, sinkManager.getSinks().size()); } |
ZooKeeperMainServer { public static void main(String args[]) throws Exception { String [] newArgs = args; if (!hasServer(args)) { Configuration conf = HBaseConfiguration.create(); String hostport = new ZooKeeperMainServer().parse(conf); if (hostport != null && hostport.length() > 0) { newArgs = new String[args.length + 2]; System.arraycopy(args, 0, newArgs, 2, args.length); newArgs[0] = "-server"; newArgs[1] = hostport; } } if (hasCommandLineArguments(args)) { HACK_UNTIL_ZOOKEEPER_1897_ZooKeeperMain zkm = new HACK_UNTIL_ZOOKEEPER_1897_ZooKeeperMain(newArgs); zkm.runCmdLine(); } else { ZooKeeperMain.main(newArgs); } } String parse(final Configuration c); static void main(String args[]); } | @Test public void testCommandLineWorks() throws Exception { System.setSecurityManager(new NoExitSecurityManager()); HBaseTestingUtility htu = new HBaseTestingUtility(); htu.getConfiguration().setInt(HConstants.ZK_SESSION_TIMEOUT, 1000); htu.startMiniZKCluster(); try { ZooKeeperWatcher zkw = htu.getZooKeeperWatcher(); String znode = "/testCommandLineWorks"; ZKUtil.createWithParents(zkw, znode, HConstants.EMPTY_BYTE_ARRAY); ZKUtil.checkExists(zkw, znode); boolean exception = false; try { ZooKeeperMainServer.main(new String [] {"-server", "localhost:" + htu.getZkCluster().getClientPort(), "delete", znode}); } catch (ExitException ee) { exception = true; } assertTrue(exception); assertEquals(-1, ZKUtil.checkExists(zkw, znode)); } finally { htu.shutdownMiniZKCluster(); System.setSecurityManager(null); } } |
ZKInterProcessReadWriteLock implements InterProcessReadWriteLock { public ZKInterProcessWriteLock writeLock(byte[] metadata) { return new ZKInterProcessWriteLock(zkWatcher, znode, metadata, handler); } ZKInterProcessReadWriteLock(ZooKeeperWatcher zkWatcher, String znode,
MetadataHandler handler); ZKInterProcessReadLock readLock(byte[] metadata); ZKInterProcessWriteLock writeLock(byte[] metadata); } | @Test(timeout = 30000) public void testWriteLockExcludesWriters() throws Exception { final String testName = "testWriteLockExcludesWriters"; final ZKInterProcessReadWriteLock readWriteLock = getReadWriteLock(testName); List<Future<Void>> results = Lists.newArrayList(); for (int i = 0; i < NUM_THREADS; ++i) { final String threadDesc = testName + i; results.add(executor.submit(new Callable<Void>() { @Override public Void call() throws IOException { ZKInterProcessWriteLock writeLock = readWriteLock.writeLock(Bytes.toBytes(threadDesc)); try { writeLock.acquire(); try { assertTrue(isLockHeld.compareAndSet(false, true)); Thread.sleep(1000); assertTrue(isLockHeld.compareAndSet(true, false)); } finally { isLockHeld.set(false); writeLock.release(); } } catch (InterruptedException e) { LOG.warn(threadDesc + " interrupted", e); Thread.currentThread().interrupt(); throw new InterruptedIOException(); } return null; } })); } MultithreadedTestUtil.assertOnFutures(results); }
@Test(timeout = 60000) public void testTimeout() throws Exception { final String testName = "testTimeout"; final CountDownLatch lockAcquiredLatch = new CountDownLatch(1); Callable<Void> shouldHog = new Callable<Void>() { @Override public Void call() throws Exception { final String threadDesc = testName + "-shouldHog"; ZKInterProcessWriteLock lock = getReadWriteLock(testName).writeLock(Bytes.toBytes(threadDesc)); lock.acquire(); lockAcquiredLatch.countDown(); Thread.sleep(10000); lock.release(); return null; } }; Callable<Void> shouldTimeout = new Callable<Void>() { @Override public Void call() throws Exception { final String threadDesc = testName + "-shouldTimeout"; ZKInterProcessWriteLock lock = getReadWriteLock(testName).writeLock(Bytes.toBytes(threadDesc)); lockAcquiredLatch.await(); assertFalse(lock.tryAcquire(5000)); return null; } }; Callable<Void> shouldAcquireLock = new Callable<Void>() { @Override public Void call() throws Exception { final String threadDesc = testName + "-shouldAcquireLock"; ZKInterProcessWriteLock lock = getReadWriteLock(testName).writeLock(Bytes.toBytes(threadDesc)); lockAcquiredLatch.await(); assertTrue(lock.tryAcquire(30000)); lock.release(); return null; } }; List<Future<Void>> results = Lists.newArrayList(); results.add(executor.submit(shouldHog)); results.add(executor.submit(shouldTimeout)); results.add(executor.submit(shouldAcquireLock)); MultithreadedTestUtil.assertOnFutures(results); } |
ZKInterProcessReadWriteLock implements InterProcessReadWriteLock { public ZKInterProcessReadLock readLock(byte[] metadata) { return new ZKInterProcessReadLock(zkWatcher, znode, metadata, handler); } ZKInterProcessReadWriteLock(ZooKeeperWatcher zkWatcher, String znode,
MetadataHandler handler); ZKInterProcessReadLock readLock(byte[] metadata); ZKInterProcessWriteLock writeLock(byte[] metadata); } | @Test(timeout = 30000) public void testReadLockDoesNotExcludeReaders() throws Exception { final String testName = "testReadLockDoesNotExcludeReaders"; final ZKInterProcessReadWriteLock readWriteLock = getReadWriteLock(testName); final CountDownLatch locksAcquiredLatch = new CountDownLatch(NUM_THREADS); final AtomicInteger locksHeld = new AtomicInteger(0); List<Future<Void>> results = Lists.newArrayList(); for (int i = 0; i < NUM_THREADS; ++i) { final String threadDesc = testName + i; results.add(executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { ZKInterProcessReadLock readLock = readWriteLock.readLock(Bytes.toBytes(threadDesc)); readLock.acquire(); try { locksHeld.incrementAndGet(); locksAcquiredLatch.countDown(); Thread.sleep(1000); } finally { readLock.release(); locksHeld.decrementAndGet(); } return null; } })); } locksAcquiredLatch.await(); assertEquals(locksHeld.get(), NUM_THREADS); MultithreadedTestUtil.assertOnFutures(results); } |
GroupingTableMap extends MapReduceBase implements TableMap<ImmutableBytesWritable,Result> { protected ImmutableBytesWritable createGroupKey(byte[][] vals) { if(vals == null) { return null; } StringBuilder sb = new StringBuilder(); for(int i = 0; i < vals.length; i++) { if(i > 0) { sb.append(" "); } sb.append(Bytes.toString(vals[i])); } return new ImmutableBytesWritable(Bytes.toBytes(sb.toString())); } @SuppressWarnings("unchecked") static void initJob(String table, String columns, String groupColumns,
Class<? extends TableMap> mapper, JobConf job); @Override void configure(JobConf job); void map(ImmutableBytesWritable key, Result value,
OutputCollector<ImmutableBytesWritable,Result> output,
Reporter reporter); static final String GROUP_COLUMNS; } | @Test @SuppressWarnings({ "deprecation" }) public void shouldReturnNullFromCreateGroupKey() throws Exception { GroupingTableMap gTableMap = null; try { gTableMap = new GroupingTableMap(); assertNull(gTableMap.createGroupKey(null)); } finally { if(gTableMap != null) gTableMap.close(); } } |
IdentityTableMap extends MapReduceBase implements TableMap<ImmutableBytesWritable, Result> { public void map(ImmutableBytesWritable key, Result value, OutputCollector<ImmutableBytesWritable,Result> output, Reporter reporter) throws IOException { output.collect(key, value); } IdentityTableMap(); @SuppressWarnings("unchecked") static void initJob(String table, String columns,
Class<? extends TableMap> mapper, JobConf job); void map(ImmutableBytesWritable key, Result value,
OutputCollector<ImmutableBytesWritable,Result> output,
Reporter reporter); } | @Test @SuppressWarnings({ "deprecation", "unchecked" }) public void shouldCollectPredefinedTimes() throws IOException { int recordNumber = 999; Result resultMock = mock(Result.class); IdentityTableMap identityTableMap = null; try { Reporter reporterMock = mock(Reporter.class); identityTableMap = new IdentityTableMap(); ImmutableBytesWritable bytesWritableMock = mock(ImmutableBytesWritable.class); OutputCollector<ImmutableBytesWritable, Result> outputCollectorMock = mock(OutputCollector.class); for (int i = 0; i < recordNumber; i++) identityTableMap.map(bytesWritableMock, resultMock, outputCollectorMock, reporterMock); verify(outputCollectorMock, times(recordNumber)).collect( Mockito.any(ImmutableBytesWritable.class), Mockito.any(Result.class)); } finally { if (identityTableMap != null) identityTableMap.close(); } } |
RowCounter extends Configured implements Tool { static int printUsage() { System.out.println(NAME + " <outputdir> <tablename> <column1> [<column2>...]"); return -1; } JobConf createSubmittableJob(String[] args); int run(final String[] args); static void main(String[] args); } | @Test @SuppressWarnings("deprecation") public void shouldPrintUsage() throws Exception { String expectedOutput = "rowcounter <outputdir> <tablename> <column1> [<column2>...]"; String result = new OutputReader(System.out) { @Override void doRead() { assertEquals(-1, RowCounter.printUsage()); } }.read(); assertTrue(result.startsWith(expectedOutput)); } |
RowCounter extends Configured implements Tool { public int run(final String[] args) throws Exception { if (args.length < 3) { System.err.println("ERROR: Wrong number of parameters: " + args.length); return printUsage(); } JobClient.runJob(createSubmittableJob(args)); return 0; } JobConf createSubmittableJob(String[] args); int run(final String[] args); static void main(String[] args); } | @Test @SuppressWarnings("deprecation") public void shouldExitAndPrintUsageSinceParameterNumberLessThanThree() throws Exception { final String[] args = new String[] { "one", "two" }; String line = "ERROR: Wrong number of parameters: " + args.length; String result = new OutputReader(System.err) { @Override void doRead() throws Exception { assertEquals(-1, new RowCounter().run(args)); } }.read(); assertTrue(result.startsWith(line)); } |
RowCounter extends Configured implements Tool { public JobConf createSubmittableJob(String[] args) throws IOException { JobConf c = new JobConf(getConf(), getClass()); c.setJobName(NAME); StringBuilder sb = new StringBuilder(); final int columnoffset = 2; for (int i = columnoffset; i < args.length; i++) { if (i > columnoffset) { sb.append(" "); } sb.append(args[i]); } TableMapReduceUtil.initTableMapJob(args[1], sb.toString(), RowCounterMapper.class, ImmutableBytesWritable.class, Result.class, c); c.setNumReduceTasks(0); FileOutputFormat.setOutputPath(c, new Path(args[0])); return c; } JobConf createSubmittableJob(String[] args); int run(final String[] args); static void main(String[] args); } | @Test @SuppressWarnings({ "deprecation" }) public void shouldCreateAndRunSubmittableJob() throws Exception { RowCounter rCounter = new RowCounter(); rCounter.setConf(HBaseConfiguration.create()); String[] args = new String[] { "\temp", "tableA", "column1", "column2", "column3" }; JobConf jobConfig = rCounter.createSubmittableJob(args); assertNotNull(jobConfig); assertEquals(0, jobConfig.getNumReduceTasks()); assertEquals("rowcounter", jobConfig.getJobName()); assertEquals(jobConfig.getMapOutputValueClass(), Result.class); assertEquals(jobConfig.getMapperClass(), RowCounterMapper.class); assertEquals(jobConfig.get(TableInputFormat.COLUMN_LIST), Joiner.on(' ') .join("column1", "column2", "column3")); assertEquals(jobConfig.getMapOutputKeyClass(), ImmutableBytesWritable.class); } |
HMasterCommandLine extends ServerCommandLine { public int run(String args[]) throws Exception { Options opt = new Options(); opt.addOption("localRegionServers", true, "RegionServers to start in master process when running standalone"); opt.addOption("masters", true, "Masters to start in this process"); opt.addOption("minRegionServers", true, "Minimum RegionServers needed to host user tables"); opt.addOption("backup", false, "Do not try to become HMaster until the primary fails"); CommandLine cmd; try { cmd = new GnuParser().parse(opt, args); } catch (ParseException e) { LOG.error("Could not parse: ", e); usage(null); return 1; } if (cmd.hasOption("minRegionServers")) { String val = cmd.getOptionValue("minRegionServers"); getConf().setInt("hbase.regions.server.count.min", Integer.valueOf(val)); LOG.debug("minRegionServers set to " + val); } if (cmd.hasOption("minServers")) { String val = cmd.getOptionValue("minServers"); getConf().setInt("hbase.regions.server.count.min", Integer.valueOf(val)); LOG.debug("minServers set to " + val); } if (cmd.hasOption("backup")) { getConf().setBoolean(HConstants.MASTER_TYPE_BACKUP, true); } if (cmd.hasOption("localRegionServers")) { String val = cmd.getOptionValue("localRegionServers"); getConf().setInt("hbase.regionservers", Integer.valueOf(val)); LOG.debug("localRegionServers set to " + val); } if (cmd.hasOption("masters")) { String val = cmd.getOptionValue("masters"); getConf().setInt("hbase.masters", Integer.valueOf(val)); LOG.debug("masters set to " + val); } @SuppressWarnings("unchecked") List<String> remainingArgs = cmd.getArgList(); if (remainingArgs.size() != 1) { usage(null); return 1; } String command = remainingArgs.get(0); if ("start".equals(command)) { return startMaster(); } else if ("stop".equals(command)) { return stopMaster(); } else if ("clear".equals(command)) { return (ZNodeClearer.clear(getConf()) ? 0 : 1); } else { usage("Invalid command: " + command); return 1; } } HMasterCommandLine(Class<? extends HMaster> masterClass); int run(String args[]); } | @Test public void testRun() throws Exception { HMasterCommandLine masterCommandLine = new HMasterCommandLine(HMaster.class); masterCommandLine.setConf(TESTING_UTIL.getConfiguration()); assertEquals(0, masterCommandLine.run(new String [] {"clear"})); } |
ActiveMasterManager extends ZooKeeperListener { boolean blockUntilBecomingActiveMaster( int checkInterval, MonitoredTask startupStatus) { String backupZNode = ZKUtil.joinZNode( this.watcher.backupMasterAddressesZNode, this.sn.toString()); while (!(master.isAborted() || master.isStopped())) { startupStatus.setStatus("Trying to register in ZK as active master"); try { if (MasterAddressTracker.setMasterAddress(this.watcher, this.watcher.getMasterAddressZNode(), this.sn)) { if (ZKUtil.checkExists(this.watcher, backupZNode) != -1) { LOG.info("Deleting ZNode for " + backupZNode + " from backup master directory"); ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode); } ZNodeClearer.writeMyEphemeralNodeOnDisk(this.sn.toString()); startupStatus.setStatus("Successfully registered as active master."); this.clusterHasActiveMaster.set(true); LOG.info("Registered Active Master=" + this.sn); return true; } this.clusterHasActiveMaster.set(true); String msg; byte[] bytes = ZKUtil.getDataAndWatch(this.watcher, this.watcher.getMasterAddressZNode()); if (bytes == null) { msg = ("A master was detected, but went down before its address " + "could be read. Attempting to become the next active master"); } else { ServerName currentMaster; try { currentMaster = ServerName.parseFrom(bytes); } catch (DeserializationException e) { LOG.warn("Failed parse", e); continue; } if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) { msg = ("Current master has this master's address, " + currentMaster + "; master was restarted? Deleting node."); ZKUtil.deleteNode(this.watcher, this.watcher.getMasterAddressZNode()); ZNodeClearer.deleteMyEphemeralNodeOnDisk(); } else { msg = "Another master is the active master, " + currentMaster + "; waiting to become the next active master"; } } LOG.info(msg); startupStatus.setStatus(msg); } catch (KeeperException ke) { master.abort("Received an unexpected KeeperException, aborting", ke); return false; } synchronized (this.clusterHasActiveMaster) { while (clusterHasActiveMaster.get() && !master.isStopped()) { try { clusterHasActiveMaster.wait(checkInterval); } catch (InterruptedException e) { LOG.debug("Interrupted waiting for master to die", e); } } if (clusterShutDown.get()) { this.master.stop( "Cluster went down before this master became active"); } } } return false; } ActiveMasterManager(ZooKeeperWatcher watcher, ServerName sn, Server master); @Override void nodeCreated(String path); @Override void nodeDeleted(String path); void stop(); } | @Test public void testRestartMaster() throws IOException, KeeperException { ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), "testActiveMasterManagerFromZK", null, true); try { ZKUtil.deleteNode(zk, zk.getMasterAddressZNode()); ZKUtil.deleteNode(zk, zk.clusterStateZNode); } catch(KeeperException.NoNodeException nne) {} ServerName master = ServerName.valueOf("localhost", 1, System.currentTimeMillis()); DummyMaster dummyMaster = new DummyMaster(zk,master); ClusterStatusTracker clusterStatusTracker = dummyMaster.getClusterStatusTracker(); ActiveMasterManager activeMasterManager = dummyMaster.getActiveMasterManager(); assertFalse(activeMasterManager.clusterHasActiveMaster.get()); MonitoredTask status = Mockito.mock(MonitoredTask.class); clusterStatusTracker.setClusterUp(); activeMasterManager.blockUntilBecomingActiveMaster(100, status); assertTrue(activeMasterManager.clusterHasActiveMaster.get()); assertMaster(zk, master); DummyMaster secondDummyMaster = new DummyMaster(zk,master); ActiveMasterManager secondActiveMasterManager = secondDummyMaster.getActiveMasterManager(); assertFalse(secondActiveMasterManager.clusterHasActiveMaster.get()); activeMasterManager.blockUntilBecomingActiveMaster(100, status); assertTrue(activeMasterManager.clusterHasActiveMaster.get()); assertMaster(zk, master); } |
FavoredNodeAssignmentHelper { void placePrimaryRSAsRoundRobin(Map<ServerName, List<HRegionInfo>> assignmentMap, Map<HRegionInfo, ServerName> primaryRSMap, List<HRegionInfo> regions) { List<String> rackList = new ArrayList<String>(rackToRegionServerMap.size()); rackList.addAll(rackToRegionServerMap.keySet()); int rackIndex = random.nextInt(rackList.size()); int maxRackSize = 0; for (Map.Entry<String,List<ServerName>> r : rackToRegionServerMap.entrySet()) { if (r.getValue().size() > maxRackSize) { maxRackSize = r.getValue().size(); } } int numIterations = 0; int firstServerIndex = random.nextInt(maxRackSize); int serverIndex = firstServerIndex; for (HRegionInfo regionInfo : regions) { List<ServerName> currentServerList; String rackName; while (true) { rackName = rackList.get(rackIndex); numIterations++; currentServerList = rackToRegionServerMap.get(rackName); if (serverIndex >= currentServerList.size()) { if (numIterations % rackList.size() == 0) { if (++serverIndex >= maxRackSize) serverIndex = 0; } if ((++rackIndex) >= rackList.size()) { rackIndex = 0; } } else break; } ServerName currentServer = currentServerList.get(serverIndex); primaryRSMap.put(regionInfo, currentServer); List<HRegionInfo> regionsForServer = assignmentMap.get(currentServer); if (regionsForServer == null) { regionsForServer = new ArrayList<HRegionInfo>(); assignmentMap.put(currentServer, regionsForServer); } regionsForServer.add(regionInfo); if (numIterations % rackList.size() == 0) { ++serverIndex; } if ((++rackIndex) >= rackList.size()) { rackIndex = 0; } } } FavoredNodeAssignmentHelper(final List<ServerName> servers, Configuration conf); FavoredNodeAssignmentHelper(final List<ServerName> servers,
final RackManager rackManager); static void updateMetaWithFavoredNodesInfo(
Map<HRegionInfo, List<ServerName>> regionToFavoredNodes,
CatalogTracker catalogTracker); static void updateMetaWithFavoredNodesInfo(
Map<HRegionInfo, List<ServerName>> regionToFavoredNodes,
Configuration conf); static ServerName[] getFavoredNodesList(byte[] favoredNodes); static byte[] getFavoredNodes(List<ServerName> serverAddrList); Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryWithRestrictions(
Map<HRegionInfo, ServerName> primaryRSMap); void initialize(); static String getFavoredNodesAsString(List<ServerName> nodes); static final byte [] FAVOREDNODES_QUALIFIER; final static short FAVORED_NODES_NUM; } | @Test public void testPlacePrimaryRSAsRoundRobin() { primaryRSPlacement(6, null, 10, 10, 10); primaryRSPlacement(600, null, 10, 10, 10); } |
FavoredNodeAssignmentHelper { Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryRS( Map<HRegionInfo, ServerName> primaryRSMap) { Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = new HashMap<HRegionInfo, ServerName[]>(); for (Map.Entry<HRegionInfo, ServerName> entry : primaryRSMap.entrySet()) { HRegionInfo regionInfo = entry.getKey(); ServerName primaryRS = entry.getValue(); try { ServerName[] favoredNodes; String primaryRack = rackManager.getRack(primaryRS); if (getTotalNumberOfRacks() == 1) { favoredNodes = singleRackCase(regionInfo, primaryRS, primaryRack); } else { favoredNodes = multiRackCase(regionInfo, primaryRS, primaryRack); } if (favoredNodes != null) { secondaryAndTertiaryMap.put(regionInfo, favoredNodes); LOG.debug("Place the secondary and tertiary region server for region " + regionInfo.getRegionNameAsString()); } } catch (Exception e) { LOG.warn("Cannot place the favored nodes for region " + regionInfo.getRegionNameAsString() + " because " + e, e); continue; } } return secondaryAndTertiaryMap; } FavoredNodeAssignmentHelper(final List<ServerName> servers, Configuration conf); FavoredNodeAssignmentHelper(final List<ServerName> servers,
final RackManager rackManager); static void updateMetaWithFavoredNodesInfo(
Map<HRegionInfo, List<ServerName>> regionToFavoredNodes,
CatalogTracker catalogTracker); static void updateMetaWithFavoredNodesInfo(
Map<HRegionInfo, List<ServerName>> regionToFavoredNodes,
Configuration conf); static ServerName[] getFavoredNodesList(byte[] favoredNodes); static byte[] getFavoredNodes(List<ServerName> serverAddrList); Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryWithRestrictions(
Map<HRegionInfo, ServerName> primaryRSMap); void initialize(); static String getFavoredNodesAsString(List<ServerName> nodes); static final byte [] FAVOREDNODES_QUALIFIER; final static short FAVORED_NODES_NUM; } | @Test public void testSecondaryAndTertiaryPlacementWithSingleRack() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 10); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, List<HRegionInfo>> primaryRSMapAndHelper = secondaryAndTertiaryRSPlacementHelper(60000, rackToServerCount); FavoredNodeAssignmentHelper helper = primaryRSMapAndHelper.getSecond(); Map<HRegionInfo, ServerName> primaryRSMap = primaryRSMapAndHelper.getFirst(); List<HRegionInfo> regions = primaryRSMapAndHelper.getThird(); Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = helper.placeSecondaryAndTertiaryRS(primaryRSMap); for (HRegionInfo region : regions) { ServerName[] secondaryAndTertiaryServers = secondaryAndTertiaryMap.get(region); assertTrue(!secondaryAndTertiaryServers[0].equals(primaryRSMap.get(region))); assertTrue(!secondaryAndTertiaryServers[1].equals(primaryRSMap.get(region))); assertTrue(!secondaryAndTertiaryServers[0].equals(secondaryAndTertiaryServers[1])); } }
@Test public void testSecondaryAndTertiaryPlacementWithSingleServer() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 1); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, List<HRegionInfo>> primaryRSMapAndHelper = secondaryAndTertiaryRSPlacementHelper(1, rackToServerCount); FavoredNodeAssignmentHelper helper = primaryRSMapAndHelper.getSecond(); Map<HRegionInfo, ServerName> primaryRSMap = primaryRSMapAndHelper.getFirst(); List<HRegionInfo> regions = primaryRSMapAndHelper.getThird(); Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = helper.placeSecondaryAndTertiaryRS(primaryRSMap); assertTrue(secondaryAndTertiaryMap.get(regions.get(0)) == null); }
@Test public void testSecondaryAndTertiaryPlacementWithMultipleRacks() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 10); rackToServerCount.put("rack2", 10); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, List<HRegionInfo>> primaryRSMapAndHelper = secondaryAndTertiaryRSPlacementHelper(60000, rackToServerCount); FavoredNodeAssignmentHelper helper = primaryRSMapAndHelper.getSecond(); Map<HRegionInfo, ServerName> primaryRSMap = primaryRSMapAndHelper.getFirst(); assertTrue(primaryRSMap.size() == 60000); Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = helper.placeSecondaryAndTertiaryRS(primaryRSMap); assertTrue(secondaryAndTertiaryMap.size() == 60000); for (Map.Entry<HRegionInfo, ServerName[]> entry : secondaryAndTertiaryMap.entrySet()) { ServerName[] allServersForRegion = entry.getValue(); String primaryRSRack = rackManager.getRack(primaryRSMap.get(entry.getKey())); String secondaryRSRack = rackManager.getRack(allServersForRegion[0]); String tertiaryRSRack = rackManager.getRack(allServersForRegion[1]); assertTrue(!primaryRSRack.equals(secondaryRSRack)); assertTrue(secondaryRSRack.equals(tertiaryRSRack)); } }
@Test public void testSecondaryAndTertiaryPlacementWithLessThanTwoServersInRacks() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 1); rackToServerCount.put("rack2", 1); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, List<HRegionInfo>> primaryRSMapAndHelper = secondaryAndTertiaryRSPlacementHelper(6, rackToServerCount); FavoredNodeAssignmentHelper helper = primaryRSMapAndHelper.getSecond(); Map<HRegionInfo, ServerName> primaryRSMap = primaryRSMapAndHelper.getFirst(); List<HRegionInfo> regions = primaryRSMapAndHelper.getThird(); assertTrue(primaryRSMap.size() == 6); Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = helper.placeSecondaryAndTertiaryRS(primaryRSMap); for (HRegionInfo region : regions) { assertTrue(secondaryAndTertiaryMap.get(region) == null); } }
@Test public void testSecondaryAndTertiaryPlacementWithMoreThanOneServerInPrimaryRack() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 2); rackToServerCount.put("rack2", 1); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, List<HRegionInfo>> primaryRSMapAndHelper = secondaryAndTertiaryRSPlacementHelper(6, rackToServerCount); FavoredNodeAssignmentHelper helper = primaryRSMapAndHelper.getSecond(); Map<HRegionInfo, ServerName> primaryRSMap = primaryRSMapAndHelper.getFirst(); List<HRegionInfo> regions = primaryRSMapAndHelper.getThird(); assertTrue(primaryRSMap.size() == 6); Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = helper.placeSecondaryAndTertiaryRS(primaryRSMap); for (HRegionInfo region : regions) { ServerName s = primaryRSMap.get(region); ServerName secondaryRS = secondaryAndTertiaryMap.get(region)[0]; ServerName tertiaryRS = secondaryAndTertiaryMap.get(region)[1]; if (rackManager.getRack(s).equals("rack1")) { assertTrue(rackManager.getRack(secondaryRS).equals("rack2") && rackManager.getRack(tertiaryRS).equals("rack1")); } if (rackManager.getRack(s).equals("rack2")) { assertTrue(rackManager.getRack(secondaryRS).equals("rack1") && rackManager.getRack(tertiaryRS).equals("rack1")); } } } |
BaseLoadBalancer implements LoadBalancer { @Override public Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); if (servers == null || servers.isEmpty()) { LOG.warn("Wanted to do random assignment but no servers to assign to"); return null; } Map<HRegionInfo, ServerName> assignments = new TreeMap<HRegionInfo, ServerName>(); List<ServerName> backupMasters = normalizeServers(servers); for (HRegionInfo region : regions) { assignments.put(region, randomAssignment(region, servers, backupMasters)); } return assignments; } @Override void setConf(Configuration conf); void excludeServer(ServerName serverName); Set<ServerName> getExcludedServers(); @Override Configuration getConf(); @Override void setClusterStatus(ClusterStatus st); @Override void setMasterServices(MasterServices masterServices); @Override Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override ServerName randomAssignment(HRegionInfo regionInfo, List<ServerName> servers); @Override Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions,
List<ServerName> servers); @Override void initialize(); @Override void regionOnline(HRegionInfo regionInfo, ServerName sn); @Override void regionOffline(HRegionInfo regionInfo); @Override boolean isStopped(); @Override void stop(String why); static final String BACKUP_MASTER_WEIGHT_KEY; static final int DEFAULT_BACKUP_MASTER_WEIGHT; } | @Test public void testImmediateAssignment() throws Exception { List<ServerName> tmp = getListOfServerNames(randomServers(1, 0)); tmp.add(master); ServerName sn = loadBalancer.randomAssignment(HRegionInfo.FIRST_META_REGIONINFO, tmp); assertEquals(master, sn); HRegionInfo hri = randomRegions(1, -1).get(0); sn = loadBalancer.randomAssignment(hri, tmp); assertNotEquals(master, sn); tmp = new ArrayList<ServerName>(); tmp.add(master); sn = loadBalancer.randomAssignment(hri, tmp); assertEquals(master, sn); for (int[] mock : regionsAndServersMocks) { LOG.debug("testImmediateAssignment with " + mock[0] + " regions and " + mock[1] + " servers"); List<HRegionInfo> regions = randomRegions(mock[0]); List<ServerAndLoad> servers = randomServers(mock[1], 0); List<ServerName> list = getListOfServerNames(servers); Map<HRegionInfo, ServerName> assignments = loadBalancer.immediateAssignment(regions, list); assertImmediateAssignment(regions, list, assignments); returnRegions(regions); returnServers(list); } } |
BaseLoadBalancer implements LoadBalancer { @Override public Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); if (regions == null || regions.isEmpty()) { return null; } List<ServerName> backupMasters = normalizeServers(servers); int numServers = servers == null ? 0 : servers.size(); int numBackupMasters = backupMasters == null ? 0 : backupMasters.size(); if (numServers == 0 && numBackupMasters == 0) { LOG.warn("Wanted to do round robin assignment but no servers to assign to"); return null; } Map<ServerName, List<HRegionInfo>> assignments = new TreeMap<ServerName, List<HRegionInfo>>(); if (numServers + numBackupMasters == 1) { ServerName server = numServers > 0 ? servers.get(0) : backupMasters.get(0); assignments.put(server, new ArrayList<HRegionInfo>(regions)); return assignments; } List<HRegionInfo> masterRegions = null; if (numServers > 0 && servers.contains(masterServerName)) { masterRegions = new ArrayList<HRegionInfo>(); if (numServers == 1) { numServers = 0; } } int total = regions.size(); int numRegions = total * numBackupMasters / (numServers * backupMasterWeight + numBackupMasters); if (numRegions > 0) { roundRobinAssignment(regions, 0, numRegions, backupMasters, masterRegions, assignments); } int remainder = total - numRegions; if (remainder > 0) { roundRobinAssignment(regions, numRegions, remainder, servers, masterRegions, assignments); } if (masterRegions != null && !masterRegions.isEmpty()) { assignments.put(masterServerName, masterRegions); } return assignments; } @Override void setConf(Configuration conf); void excludeServer(ServerName serverName); Set<ServerName> getExcludedServers(); @Override Configuration getConf(); @Override void setClusterStatus(ClusterStatus st); @Override void setMasterServices(MasterServices masterServices); @Override Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override ServerName randomAssignment(HRegionInfo regionInfo, List<ServerName> servers); @Override Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions,
List<ServerName> servers); @Override void initialize(); @Override void regionOnline(HRegionInfo regionInfo, ServerName sn); @Override void regionOffline(HRegionInfo regionInfo); @Override boolean isStopped(); @Override void stop(String why); static final String BACKUP_MASTER_WEIGHT_KEY; static final int DEFAULT_BACKUP_MASTER_WEIGHT; } | @Test public void testBulkAssignment() throws Exception { List<ServerName> tmp = getListOfServerNames(randomServers(5, 0)); List<HRegionInfo> hris = randomRegions(20); hris.add(HRegionInfo.FIRST_META_REGIONINFO); tmp.add(master); Map<ServerName, List<HRegionInfo>> plans = loadBalancer.roundRobinAssignment(hris, tmp); assertTrue(plans.get(master).contains(HRegionInfo.FIRST_META_REGIONINFO)); assertEquals(1, plans.get(master).size()); int totalRegion = 0; for (List<HRegionInfo> regions: plans.values()) { totalRegion += regions.size(); } assertEquals(hris.size(), totalRegion); for (int[] mock : regionsAndServersMocks) { LOG.debug("testBulkAssignment with " + mock[0] + " regions and " + mock[1] + " servers"); List<HRegionInfo> regions = randomRegions(mock[0]); List<ServerAndLoad> servers = randomServers(mock[1], 0); List<ServerName> list = getListOfServerNames(servers); Map<ServerName, List<HRegionInfo>> assignments = loadBalancer.roundRobinAssignment(regions, list); float average = (float) regions.size() / servers.size(); int min = (int) Math.floor(average); int max = (int) Math.ceil(average); if (assignments != null && !assignments.isEmpty()) { for (List<HRegionInfo> regionList : assignments.values()) { assertTrue(regionList.size() == min || regionList.size() == max); } } returnRegions(regions); returnServers(list); } } |
BaseLoadBalancer implements LoadBalancer { @Override public Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); if (regions == null || regions.isEmpty()) { return null; } List<ServerName> backupMasters = normalizeServers(servers); int numServers = servers == null ? 0 : servers.size(); int numBackupMasters = backupMasters == null ? 0 : backupMasters.size(); if (numServers == 0 && numBackupMasters == 0) { LOG.warn("Wanted to do retain assignment but no servers to assign to"); return null; } Map<ServerName, List<HRegionInfo>> assignments = new TreeMap<ServerName, List<HRegionInfo>>(); if (numServers + numBackupMasters == 1) { ServerName server = numServers > 0 ? servers.get(0) : backupMasters.get(0); assignments.put(server, new ArrayList<HRegionInfo>(regions.keySet())); return assignments; } ArrayListMultimap<String, ServerName> serversByHostname = ArrayListMultimap.create(); for (ServerName server : servers) { assignments.put(server, new ArrayList<HRegionInfo>()); if (!server.equals(masterServerName)) { serversByHostname.put(server.getHostname(), server); } } if (numBackupMasters > 0) { for (ServerName server : backupMasters) { assignments.put(server, new ArrayList<HRegionInfo>()); } } Set<String> oldHostsNoLongerPresent = Sets.newTreeSet(); boolean masterIncluded = servers.contains(masterServerName); int numRandomAssignments = 0; int numRetainedAssigments = 0; for (Map.Entry<HRegionInfo, ServerName> entry : regions.entrySet()) { HRegionInfo region = entry.getKey(); ServerName oldServerName = entry.getValue(); List<ServerName> localServers = new ArrayList<ServerName>(); if (oldServerName != null) { localServers = serversByHostname.get(oldServerName.getHostname()); } if (masterIncluded && shouldBeOnMaster(region)) { assignments.get(masterServerName).add(region); if (localServers.contains(masterServerName)) { numRetainedAssigments++; } else { numRandomAssignments++; } } else if (localServers.isEmpty()) { ServerName randomServer = randomAssignment(region, servers, backupMasters); assignments.get(randomServer).add(region); numRandomAssignments++; if (oldServerName != null) oldHostsNoLongerPresent.add(oldServerName.getHostname()); } else if (localServers.size() == 1) { assignments.get(localServers.get(0)).add(region); numRetainedAssigments++; } else { int size = localServers.size(); ServerName target = localServers.contains(oldServerName) ? oldServerName : localServers.get(RANDOM .nextInt(size)); assignments.get(target).add(region); numRetainedAssigments++; } } String randomAssignMsg = ""; if (numRandomAssignments > 0) { randomAssignMsg = numRandomAssignments + " regions were assigned " + "to random hosts, since the old hosts for these regions are no " + "longer present in the cluster. These hosts were:\n " + Joiner.on("\n ").join(oldHostsNoLongerPresent); } LOG.info("Reassigned " + regions.size() + " regions. " + numRetainedAssigments + " retained the pre-restart assignment. " + randomAssignMsg); return assignments; } @Override void setConf(Configuration conf); void excludeServer(ServerName serverName); Set<ServerName> getExcludedServers(); @Override Configuration getConf(); @Override void setClusterStatus(ClusterStatus st); @Override void setMasterServices(MasterServices masterServices); @Override Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions,
List<ServerName> servers); @Override ServerName randomAssignment(HRegionInfo regionInfo, List<ServerName> servers); @Override Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions,
List<ServerName> servers); @Override void initialize(); @Override void regionOnline(HRegionInfo regionInfo, ServerName sn); @Override void regionOffline(HRegionInfo regionInfo); @Override boolean isStopped(); @Override void stop(String why); static final String BACKUP_MASTER_WEIGHT_KEY; static final int DEFAULT_BACKUP_MASTER_WEIGHT; } | @Test public void testRetainAssignment() throws Exception { List<ServerAndLoad> servers = randomServers(10, 10); List<HRegionInfo> regions = randomRegions(100); Map<HRegionInfo, ServerName> existing = new TreeMap<HRegionInfo, ServerName>(); for (int i = 0; i < regions.size(); i++) { ServerName sn = servers.get(i % servers.size()).getServerName(); ServerName snWithOldStartCode = ServerName.valueOf(sn.getHostname(), sn.getPort(), sn.getStartcode() - 10); existing.put(regions.get(i), snWithOldStartCode); } List<ServerName> listOfServerNames = getListOfServerNames(servers); Map<ServerName, List<HRegionInfo>> assignment = loadBalancer.retainAssignment(existing, listOfServerNames); assertRetainedAssignment(existing, listOfServerNames, assignment); List<ServerAndLoad> servers2 = new ArrayList<ServerAndLoad>(servers); servers2.add(randomServer(10)); servers2.add(randomServer(10)); listOfServerNames = getListOfServerNames(servers2); assignment = loadBalancer.retainAssignment(existing, listOfServerNames); assertRetainedAssignment(existing, listOfServerNames, assignment); List<ServerAndLoad> servers3 = new ArrayList<ServerAndLoad>(servers); servers3.remove(0); servers3.remove(0); listOfServerNames = getListOfServerNames(servers3); assignment = loadBalancer.retainAssignment(existing, listOfServerNames); assertRetainedAssignment(existing, listOfServerNames, assignment); } |
StochasticLoadBalancer extends BaseLoadBalancer { @Override public void setClusterStatus(ClusterStatus st) { super.setClusterStatus(st); regionFinder.setClusterStatus(st); updateRegionLoad(); for(CostFromRegionLoadFunction cost : regionLoadFunctions) { cost.setClusterStatus(st); } } @Override void setConf(Configuration conf); @Override void setClusterStatus(ClusterStatus st); @Override void setMasterServices(MasterServices masterServices); @Override List<RegionPlan> balanceCluster(Map<ServerName, List<HRegionInfo>> clusterState); } | @Test public void testKeepRegionLoad() throws Exception { ServerName sn = ServerName.valueOf("test:8080", 100); int numClusterStatusToAdd = 20000; for (int i = 0; i < numClusterStatusToAdd; i++) { ServerLoad sl = mock(ServerLoad.class); RegionLoad rl = mock(RegionLoad.class); when(rl.getStores()).thenReturn(i); Map<byte[], RegionLoad> regionLoadMap = new TreeMap<byte[], RegionLoad>(Bytes.BYTES_COMPARATOR); regionLoadMap.put(Bytes.toBytes(REGION_KEY), rl); when(sl.getRegionsLoad()).thenReturn(regionLoadMap); ClusterStatus clusterStatus = mock(ClusterStatus.class); when(clusterStatus.getServers()).thenReturn(Arrays.asList(sn)); when(clusterStatus.getLoad(sn)).thenReturn(sl); loadBalancer.setClusterStatus(clusterStatus); } assertTrue(loadBalancer.loads.get(REGION_KEY) != null); assertTrue(loadBalancer.loads.get(REGION_KEY).size() == 15); Queue<RegionLoad> loads = loadBalancer.loads.get(REGION_KEY); int i = 0; while(loads.size() > 0) { RegionLoad rl = loads.remove(); assertEquals(i + (numClusterStatusToAdd - 15), rl.getStores()); i ++; } } |
StochasticLoadBalancer extends BaseLoadBalancer { @Override public List<RegionPlan> balanceCluster(Map<ServerName, List<HRegionInfo>> clusterState) { List<RegionPlan> plans = balanceMasterRegions(clusterState); if (plans != null) { return plans; } filterExcludedServers(clusterState); if (!needsBalance(new ClusterLoadState(masterServerName, getBackupMasters(), backupMasterWeight, clusterState))) { return null; } long startTime = EnvironmentEdgeManager.currentTimeMillis(); Cluster cluster = new Cluster(masterServerName, clusterState, loads, regionFinder, getBackupMasters(), tablesOnMaster); double currentCost = computeCost(cluster, Double.MAX_VALUE); double initCost = currentCost; double newCost = currentCost; long computedMaxSteps = Math.min(this.maxSteps, ((long)cluster.numRegions * (long)this.stepsPerRegion * (long)cluster.numServers)); long step; for (step = 0; step < computedMaxSteps; step++) { int pickerIdx = RANDOM.nextInt(pickers.length); RegionPicker p = pickers[pickerIdx]; Pair<Pair<Integer, Integer>, Pair<Integer, Integer>> picks = p.pick(cluster); int leftServer = picks.getFirst().getFirst(); int leftRegion = picks.getFirst().getSecond(); int rightServer = picks.getSecond().getFirst(); int rightRegion = picks.getSecond().getSecond(); if (rightServer < 0 || leftServer < 0) { continue; } if (leftRegion < 0 && rightRegion < 0) { continue; } cluster.moveOrSwapRegion(leftServer, rightServer, leftRegion, rightRegion); newCost = computeCost(cluster, currentCost); if (newCost < currentCost) { currentCost = newCost; } else { cluster.moveOrSwapRegion(leftServer, rightServer, rightRegion, leftRegion); } if (EnvironmentEdgeManager.currentTimeMillis() - startTime > maxRunningTime) { break; } } long endTime = EnvironmentEdgeManager.currentTimeMillis(); metricsBalancer.balanceCluster(endTime - startTime); if (initCost > currentCost) { plans = createRegionPlans(cluster); if (LOG.isDebugEnabled()) { LOG.debug("Finished computing new load balance plan. Computation took " + (endTime - startTime) + "ms to try " + step + " different iterations. Found a solution that moves " + plans.size() + " regions; Going from a computed cost of " + initCost + " to a new cost of " + currentCost); } return plans; } if (LOG.isDebugEnabled()) { LOG.debug("Could not find a better load balance plan. Tried " + step + " different configurations in " + (endTime - startTime) + "ms, and did not find anything with a computed cost less than " + initCost); } return null; } @Override void setConf(Configuration conf); @Override void setClusterStatus(ClusterStatus st); @Override void setMasterServices(MasterServices masterServices); @Override List<RegionPlan> balanceCluster(Map<ServerName, List<HRegionInfo>> clusterState); } | @Test public void testBalanceCluster() throws Exception { for (int[] mockCluster : clusterStateMocks) { Map<ServerName, List<HRegionInfo>> servers = mockClusterServers(mockCluster); List<ServerAndLoad> list = convertToList(servers); LOG.info("Mock Cluster : " + printMock(list) + " " + printStats(list)); List<RegionPlan> plans = loadBalancer.balanceCluster(servers); List<ServerAndLoad> balancedCluster = reconcile(list, plans, servers); LOG.info("Mock Balance : " + printMock(balancedCluster)); assertClusterAsBalanced(balancedCluster); List<RegionPlan> secondPlans = loadBalancer.balanceCluster(servers); assertNull(secondPlans); for (Map.Entry<ServerName, List<HRegionInfo>> entry : servers.entrySet()) { returnRegions(entry.getValue()); returnServer(entry.getKey()); } } }
@Test(timeout = 60000) public void testLosingRs() throws Exception { int numNodes = 3; int numRegions = 20; int numRegionsPerServer = 3; int numTables = 2; Map<ServerName, List<HRegionInfo>> serverMap = createServerMap(numNodes, numRegions, numRegionsPerServer, numTables); List<ServerAndLoad> list = convertToList(serverMap); List<RegionPlan> plans = loadBalancer.balanceCluster(serverMap); assertNotNull(plans); List<ServerAndLoad> balancedCluster = reconcile(list, plans, serverMap); assertClusterAsBalanced(balancedCluster); ServerName sn = serverMap.keySet().toArray(new ServerName[serverMap.size()])[0]; ServerName deadSn = ServerName.valueOf(sn.getHostname(), sn.getPort(), sn.getStartcode() - 100); serverMap.put(deadSn, new ArrayList<HRegionInfo>(0)); plans = loadBalancer.balanceCluster(serverMap); assertNull(plans); } |
AssignmentManager extends ZooKeeperListener { public void balance(final RegionPlan plan) { HRegionInfo hri = plan.getRegionInfo(); TableName tableName = hri.getTable(); if (tableStateManager.isTableState(tableName, ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) { LOG.info("Ignored moving region of disabling/disabled table " + tableName); return; } String encodedName = hri.getEncodedName(); ReentrantLock lock = locker.acquireLock(encodedName); try { if (!regionStates.isRegionOnline(hri)) { RegionState state = regionStates.getRegionState(encodedName); LOG.info("Ignored moving region not assigned: " + hri + ", " + (state == null ? "not in region states" : state)); return; } synchronized (this.regionPlans) { this.regionPlans.put(plan.getRegionName(), plan); } unassign(hri, false, plan.getDestination()); } finally { lock.unlock(); } } AssignmentManager(Server server, ServerManager serverManager,
CatalogTracker catalogTracker, final LoadBalancer balancer,
final ExecutorService service, MetricsMaster metricsMaster,
final TableLockManager tableLockManager); void registerListener(final AssignmentListener listener); boolean unregisterListener(final AssignmentListener listener); TableStateManager getTableStateManager(); RegionStates getRegionStates(); RegionPlan getRegionReopenPlan(HRegionInfo hri); void addPlan(String encodedName, RegionPlan plan); void addPlans(Map<String, RegionPlan> plans); void setRegionsToReopen(List <HRegionInfo> regions); Pair<Integer, Integer> getReopenStatus(TableName tableName); boolean isFailoverCleanupDone(); Lock acquireRegionLock(final String encodedName); void removeClosedRegion(HRegionInfo hri); @Override void nodeCreated(String path); @Override void nodeDataChanged(String path); @Override void nodeDeleted(final String path); @Override void nodeChildrenChanged(String path); void regionOffline(final HRegionInfo regionInfo); void offlineDisabledRegion(HRegionInfo regionInfo); void assign(HRegionInfo region, boolean setOfflineInZK); void assign(HRegionInfo region,
boolean setOfflineInZK, boolean forceNewPlan); void unassign(HRegionInfo region); void unassign(HRegionInfo region, boolean force, ServerName dest); void unassign(HRegionInfo region, boolean force); void deleteClosingOrClosedNode(HRegionInfo region, ServerName sn); int getNumRegionsOpened(); boolean waitForAssignment(HRegionInfo regionInfo); void assignMeta(); void assign(Map<HRegionInfo, ServerName> regions); void assign(List<HRegionInfo> regions); void updateRegionsInTransitionMetrics(); void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri); boolean waitOnRegionToClearRegionsInTransition(final HRegionInfo hri, long timeOut); boolean isCarryingMeta(ServerName serverName); List<HRegionInfo> processServerShutdown(final ServerName sn); void balance(final RegionPlan plan); void stop(); void shutdown(); LoadBalancer getBalancer(); static final ServerName HBCK_CODE_SERVERNAME; @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="MS_SHOULD_BE_FINAL")
static boolean TEST_SKIP_SPLIT_HANDLING; } | @Test public void testBalance() throws IOException, KeeperException, DeserializationException, InterruptedException, CoordinatedStateException { ExecutorService executor = startupMasterExecutor("testBalanceExecutor"); CatalogTracker ct = Mockito.mock(CatalogTracker.class); LoadBalancer balancer = LoadBalancerFactory.getLoadBalancer(server .getConfiguration()); AssignmentManager am = new AssignmentManager(this.server, this.serverManager, ct, balancer, executor, null, master.getTableLockManager()); am.failoverCleanupDone.set(true); try { this.watcher.registerListenerFirst(am); am.regionOnline(REGIONINFO, SERVERNAME_A); RegionPlan plan = new RegionPlan(REGIONINFO, SERVERNAME_A, SERVERNAME_B); am.balance(plan); RegionStates regionStates = am.getRegionStates(); assertTrue(regionStates.isRegionInTransition(REGIONINFO) && regionStates.isRegionInState(REGIONINFO, State.FAILED_CLOSE)); regionStates.updateRegionState(REGIONINFO, State.PENDING_CLOSE); int versionid = ZKAssign.transitionNodeClosed(this.watcher, REGIONINFO, SERVERNAME_A, -1); assertNotSame(versionid, -1); Mocking.waitForRegionPendingOpenInRIT(am, REGIONINFO.getEncodedName()); versionid = ZKAssign.getVersion(this.watcher, REGIONINFO); assertNotSame(-1, versionid); versionid = ZKAssign.transitionNode(server.getZooKeeper(), REGIONINFO, SERVERNAME_B, EventType.M_ZK_REGION_OFFLINE, EventType.RS_ZK_REGION_OPENING, versionid); assertNotSame(-1, versionid); versionid = ZKAssign.transitionNodeOpened(this.watcher, REGIONINFO, SERVERNAME_B, versionid); assertNotSame(-1, versionid); while(regionStates.isRegionInTransition(REGIONINFO)) Threads.sleep(1); } finally { executor.shutdown(); am.shutdown(); ZKAssign.deleteAllNodes(this.watcher); } } |
StaticUserWebFilter extends FilterInitializer { static String getUsernameFromConf(Configuration conf) { String oldStyleUgi = conf.get(DEPRECATED_UGI_KEY); if (oldStyleUgi != null) { LOG.warn(DEPRECATED_UGI_KEY + " should not be used. Instead, use " + HBASE_HTTP_STATIC_USER + "."); String[] parts = oldStyleUgi.split(","); return parts[0]; } else { return conf.get(HBASE_HTTP_STATIC_USER, DEFAULT_HBASE_HTTP_STATIC_USER); } } @Override void initFilter(FilterContainer container, Configuration conf); } | @Test public void testOldStyleConfiguration() { Configuration conf = new Configuration(); conf.set("dfs.web.ugi", "joe,group1,group2"); assertEquals("joe", StaticUserWebFilter.getUsernameFromConf(conf)); }
@Test public void testConfiguration() { Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.HADOOP_HTTP_STATIC_USER, "dr.stack"); assertEquals("dr.stack", StaticUserWebFilter.getUsernameFromConf(conf)); } |
AssignmentManager extends ZooKeeperListener { public void shutdown() { synchronized (zkEventWorkerWaitingList){ zkEventWorkerWaitingList.clear(); } threadPoolExecutorService.shutdownNow(); zkEventWorkers.shutdownNow(); regionStateStore.stop(); } AssignmentManager(Server server, ServerManager serverManager,
CatalogTracker catalogTracker, final LoadBalancer balancer,
final ExecutorService service, MetricsMaster metricsMaster,
final TableLockManager tableLockManager); void registerListener(final AssignmentListener listener); boolean unregisterListener(final AssignmentListener listener); TableStateManager getTableStateManager(); RegionStates getRegionStates(); RegionPlan getRegionReopenPlan(HRegionInfo hri); void addPlan(String encodedName, RegionPlan plan); void addPlans(Map<String, RegionPlan> plans); void setRegionsToReopen(List <HRegionInfo> regions); Pair<Integer, Integer> getReopenStatus(TableName tableName); boolean isFailoverCleanupDone(); Lock acquireRegionLock(final String encodedName); void removeClosedRegion(HRegionInfo hri); @Override void nodeCreated(String path); @Override void nodeDataChanged(String path); @Override void nodeDeleted(final String path); @Override void nodeChildrenChanged(String path); void regionOffline(final HRegionInfo regionInfo); void offlineDisabledRegion(HRegionInfo regionInfo); void assign(HRegionInfo region, boolean setOfflineInZK); void assign(HRegionInfo region,
boolean setOfflineInZK, boolean forceNewPlan); void unassign(HRegionInfo region); void unassign(HRegionInfo region, boolean force, ServerName dest); void unassign(HRegionInfo region, boolean force); void deleteClosingOrClosedNode(HRegionInfo region, ServerName sn); int getNumRegionsOpened(); boolean waitForAssignment(HRegionInfo regionInfo); void assignMeta(); void assign(Map<HRegionInfo, ServerName> regions); void assign(List<HRegionInfo> regions); void updateRegionsInTransitionMetrics(); void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri); boolean waitOnRegionToClearRegionsInTransition(final HRegionInfo hri, long timeOut); boolean isCarryingMeta(ServerName serverName); List<HRegionInfo> processServerShutdown(final ServerName sn); void balance(final RegionPlan plan); void stop(); void shutdown(); LoadBalancer getBalancer(); static final ServerName HBCK_CODE_SERVERNAME; @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="MS_SHOULD_BE_FINAL")
static boolean TEST_SKIP_SPLIT_HANDLING; } | @Test public void testShutdownHandler() throws KeeperException, IOException, CoordinatedStateException, ServiceException { ExecutorService executor = startupMasterExecutor("testShutdownHandler"); CatalogTracker ct = Mockito.mock(CatalogTracker.class); AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager( this.server, this.serverManager); try { processServerShutdownHandler(ct, am, false); } finally { executor.shutdown(); am.shutdown(); ZKAssign.deleteAllNodes(this.watcher); } } |
ClusterStatusPublisher extends Chore { protected List<ServerName> generateDeadServersListToSend() { long since = EnvironmentEdgeManager.currentTimeMillis() - messagePeriod * 2; for (Pair<ServerName, Long> dead : getDeadServers(since)) { lastSent.putIfAbsent(dead.getFirst(), 0); } List<Map.Entry<ServerName, Integer>> entries = new ArrayList<Map.Entry<ServerName, Integer>>(); entries.addAll(lastSent.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<ServerName, Integer>>() { @Override public int compare(Map.Entry<ServerName, Integer> o1, Map.Entry<ServerName, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); int max = entries.size() > MAX_SERVER_PER_MESSAGE ? MAX_SERVER_PER_MESSAGE : entries.size(); List<ServerName> res = new ArrayList<ServerName>(max); for (int i = 0; i < max; i++) { Map.Entry<ServerName, Integer> toSend = entries.get(i); if (toSend.getValue() >= (NB_SEND - 1)) { lastSent.remove(toSend.getKey()); } else { lastSent.replace(toSend.getKey(), toSend.getValue(), toSend.getValue() + 1); } res.add(toSend.getKey()); } return res; } ClusterStatusPublisher(HMaster master, Configuration conf,
Class<? extends Publisher> publisherClass); protected ClusterStatusPublisher(); static final String STATUS_PUBLISHER_CLASS; static final Class<? extends ClusterStatusPublisher.Publisher> DEFAULT_STATUS_PUBLISHER_CLASS; static final String STATUS_PUBLISH_PERIOD; static final int DEFAULT_STATUS_PUBLISH_PERIOD; final static int MAX_SERVER_PER_MESSAGE; final static int NB_SEND; } | @Test public void testEmpty() { ClusterStatusPublisher csp = new ClusterStatusPublisher() { @Override protected List<Pair<ServerName, Long>> getDeadServers(long since) { return new ArrayList<Pair<ServerName, Long>>(); } }; Assert.assertTrue(csp.generateDeadServersListToSend().isEmpty()); }
@Test public void testMaxSend() { ClusterStatusPublisher csp = new ClusterStatusPublisher() { @Override protected List<Pair<ServerName, Long>> getDeadServers(long since) { List<Pair<ServerName, Long>> res = new ArrayList<Pair<ServerName, Long>>(); switch ((int) EnvironmentEdgeManager.currentTimeMillis()) { case 2: res.add(new Pair<ServerName, Long>(ServerName.valueOf("hn", 10, 10), 1L)); break; case 1000: break; } return res; } }; mee.setValue(2); for (int i = 0; i < ClusterStatusPublisher.NB_SEND; i++) { Assert.assertEquals("i=" + i, 1, csp.generateDeadServersListToSend().size()); } mee.setValue(1000); Assert.assertTrue(csp.generateDeadServersListToSend().isEmpty()); }
@Test public void testOrder() { ClusterStatusPublisher csp = new ClusterStatusPublisher() { @Override protected List<Pair<ServerName, Long>> getDeadServers(long since) { List<Pair<ServerName, Long>> res = new ArrayList<Pair<ServerName, Long>>(); for (int i = 0; i < 25; i++) { res.add(new Pair<ServerName, Long>(ServerName.valueOf("hn" + i, 10, 10), 20L)); } return res; } }; mee.setValue(3); List<ServerName> allSNS = csp.generateDeadServersListToSend(); Assert.assertEquals(10, ClusterStatusPublisher.MAX_SERVER_PER_MESSAGE); Assert.assertEquals(10, allSNS.size()); List<ServerName> nextMes = csp.generateDeadServersListToSend(); Assert.assertEquals(10, nextMes.size()); for (ServerName sn : nextMes) { if (!allSNS.contains(sn)) { allSNS.add(sn); } } Assert.assertEquals(20, allSNS.size()); nextMes = csp.generateDeadServersListToSend(); Assert.assertEquals(10, nextMes.size()); for (ServerName sn : nextMes) { if (!allSNS.contains(sn)) { allSNS.add(sn); } } Assert.assertEquals(25, allSNS.size()); nextMes = csp.generateDeadServersListToSend(); Assert.assertEquals(10, nextMes.size()); for (ServerName sn : nextMes) { if (!allSNS.contains(sn)) { allSNS.add(sn); } } Assert.assertEquals(25, allSNS.size()); } |
CatalogJanitor extends Chore { boolean cleanParent(final HRegionInfo parent, Result rowContent) throws IOException { boolean result = false; if (rowContent.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) { return result; } PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughterRegions(rowContent); Pair<Boolean, Boolean> a = checkDaughterInFs(parent, daughters.getFirst()); Pair<Boolean, Boolean> b = checkDaughterInFs(parent, daughters.getSecond()); if (hasNoReferences(a) && hasNoReferences(b)) { LOG.debug("Deleting region " + parent.getRegionNameAsString() + " because daughter splits no longer hold references"); FileSystem fs = this.services.getMasterFileSystem().getFileSystem(); if (LOG.isTraceEnabled()) LOG.trace("Archiving parent region: " + parent); HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, parent); MetaEditor.deleteRegion(this.server.getCatalogTracker(), parent); result = true; } return result; } CatalogJanitor(final Server server, final MasterServices services); boolean setEnabled(final boolean enabled); boolean cleanMergeQualifier(final HRegionInfo region); } | @Test public void testCleanParent() throws IOException, InterruptedException { HBaseTestingUtility htu = new HBaseTestingUtility(); setRootDirAndCleanIt(htu, "testCleanParent"); Server server = new MockServer(htu); try { MasterServices services = new MockMasterServices(server); CatalogJanitor janitor = new CatalogJanitor(server, services); HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("table")); htd.addFamily(new HColumnDescriptor("f")); HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("eee")); HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc")); HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"), Bytes.toBytes("eee")); Result r = createResult(parent, splita, splitb); Path rootdir = services.getMasterFileSystem().getRootDir(); Path tabledir = FSUtils.getTableDir(rootdir, htd.getTableName()); Path storedir = HStore.getStoreHomedir(tabledir, splita, htd.getColumnFamilies()[0].getName()); Reference ref = Reference.createTopReference(Bytes.toBytes("ccc")); long now = System.currentTimeMillis(); Path p = new Path(storedir, Long.toString(now) + "." + parent.getEncodedName()); FileSystem fs = services.getMasterFileSystem().getFileSystem(); Path path = ref.write(fs, p); assertTrue(fs.exists(path)); assertFalse(janitor.cleanParent(parent, r)); assertTrue(fs.delete(p, true)); assertTrue(janitor.cleanParent(parent, r)); } finally { server.stop("shutdown"); } }
@Test public void testArchiveOldRegion() throws Exception { String table = "table"; HBaseTestingUtility htu = new HBaseTestingUtility(); setRootDirAndCleanIt(htu, "testCleanParent"); Server server = new MockServer(htu); MasterServices services = new MockMasterServices(server); CatalogJanitor janitor = new CatalogJanitor(server, services); HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table)); htd.addFamily(new HColumnDescriptor("f")); HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("eee")); HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc")); HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"), Bytes.toBytes("eee")); Result parentMetaRow = createResult(parent, splita, splitb); FileSystem fs = FileSystem.get(htu.getConfiguration()); Path rootdir = services.getMasterFileSystem().getRootDir(); FSUtils.setRootDir(fs.getConf(), rootdir); Path tabledir = FSUtils.getTableDir(rootdir, htd.getTableName()); Path storedir = HStore.getStoreHomedir(tabledir, parent, htd.getColumnFamilies()[0].getName()); Path storeArchive = HFileArchiveUtil.getStoreArchivePath(services.getConfiguration(), parent, tabledir, htd.getColumnFamilies()[0].getName()); LOG.debug("Table dir:" + tabledir); LOG.debug("Store dir:" + storedir); LOG.debug("Store archive dir:" + storeArchive); FileStatus[] mockFiles = addMockStoreFiles(2, services, storedir); FileStatus[] storeFiles = fs.listStatus(storedir); int index = 0; for (FileStatus file : storeFiles) { LOG.debug("Have store file:" + file.getPath()); assertEquals("Got unexpected store file", mockFiles[index].getPath(), storeFiles[index].getPath()); index++; } assertTrue(janitor.cleanParent(parent, parentMetaRow)); LOG.debug("Finished cleanup of parent region"); FileStatus[] archivedStoreFiles = fs.listStatus(storeArchive); logFiles("archived files", storeFiles); logFiles("archived files", archivedStoreFiles); assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs); FSUtils.delete(fs, rootdir, true); services.stop("Test finished"); server.stop("Test finished"); janitor.join(); }
@Test public void testDuplicateHFileResolution() throws Exception { String table = "table"; HBaseTestingUtility htu = new HBaseTestingUtility(); setRootDirAndCleanIt(htu, "testCleanParent"); Server server = new MockServer(htu); MasterServices services = new MockMasterServices(server); CatalogJanitor janitor = new CatalogJanitor(server, services); HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table)); htd.addFamily(new HColumnDescriptor("f")); HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("eee")); HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc")); HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"), Bytes.toBytes("eee")); Result r = createResult(parent, splita, splitb); FileSystem fs = FileSystem.get(htu.getConfiguration()); Path rootdir = services.getMasterFileSystem().getRootDir(); FSUtils.setRootDir(fs.getConf(), rootdir); Path tabledir = FSUtils.getTableDir(rootdir, parent.getTable()); Path storedir = HStore.getStoreHomedir(tabledir, parent, htd.getColumnFamilies()[0].getName()); System.out.println("Old root:" + rootdir); System.out.println("Old table:" + tabledir); System.out.println("Old store:" + storedir); Path storeArchive = HFileArchiveUtil.getStoreArchivePath(services.getConfiguration(), parent, tabledir, htd.getColumnFamilies()[0].getName()); System.out.println("Old archive:" + storeArchive); addMockStoreFiles(2, services, storedir); FileStatus[] storeFiles = fs.listStatus(storedir); assertTrue(janitor.cleanParent(parent, r)); FileStatus[] archivedStoreFiles = fs.listStatus(storeArchive); assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs); addMockStoreFiles(2, services, storedir); assertTrue(janitor.cleanParent(parent, r)); archivedStoreFiles = fs.listStatus(storeArchive); assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs, true); services.stop("Test finished"); server.stop("shutdown"); janitor.join(); } |
SplitLogManager extends ZooKeeperListener { Task findOrCreateOrphanTask(String path) { Task orphanTask = new Task(); Task task; task = tasks.putIfAbsent(path, orphanTask); if (task == null) { LOG.info("creating orphan task " + path); SplitLogCounters.tot_mgr_orphan_task_acquired.incrementAndGet(); task = orphanTask; } return task; } SplitLogManager(ZooKeeperWatcher zkw, final Configuration conf,
Stoppable stopper, MasterServices master, ServerName serverName); SplitLogManager(ZooKeeperWatcher zkw, Configuration conf, Stoppable stopper,
MasterServices master, ServerName serverName, TaskFinisher tf); long splitLogDistributed(final Path logDir); long splitLogDistributed(final List<Path> logDirs); long splitLogDistributed(final Set<ServerName> serverNames, final List<Path> logDirs,
PathFilter filter); static void deleteRecoveringRegionZNodes(ZooKeeperWatcher watcher, List<String> regions); @Override void nodeDataChanged(String path); void stop(); static long parseLastFlushedSequenceIdFrom(final byte[] bytes); static boolean isRegionMarkedRecoveringInZK(ZooKeeperWatcher zkw, String regionEncodedName); static RegionStoreSequenceIds getRegionFlushedSequenceId(ZooKeeperWatcher zkw,
String serverName, String encodedRegionName); void setRecoveryMode(boolean isForInitialization); RecoveryMode getRecoveryMode(); static final int DEFAULT_TIMEOUT; static final int DEFAULT_ZK_RETRIES; static final int DEFAULT_MAX_RESUBMIT; static final int DEFAULT_UNASSIGNED_TIMEOUT; public boolean ignoreZKDeleteForTesting; } | @Test public void testOrphanTaskAcquisition() throws Exception { LOG.info("TestOrphanTaskAcquisition"); String tasknode = ZKSplitLog.getEncodedNodeName(zkw, "orphan/test/slash"); SplitLogTask slt = new SplitLogTask.Owned(DUMMY_MASTER, this.mode); zkw.getRecoverableZooKeeper().create(tasknode, slt.toByteArray(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); slm = new SplitLogManager(zkw, conf, stopper, master, DUMMY_MASTER); waitForCounter(tot_mgr_orphan_task_acquired, 0, 1, to/2); Task task = slm.findOrCreateOrphanTask(tasknode); assertTrue(task.isOrphan()); waitForCounter(tot_mgr_heartbeat, 0, 1, to/2); assertFalse(task.isUnassigned()); long curt = System.currentTimeMillis(); assertTrue((task.last_update <= curt) && (task.last_update > (curt - 1000))); LOG.info("waiting for manager to resubmit the orphan task"); waitForCounter(tot_mgr_resubmit, 0, 1, to + to/2); assertTrue(task.isUnassigned()); waitForCounter(tot_mgr_rescan, 0, 1, to + to/2); }
@Test public void testUnassignedOrphan() throws Exception { LOG.info("TestUnassignedOrphan - an unassigned task is resubmitted at" + " startup"); String tasknode = ZKSplitLog.getEncodedNodeName(zkw, "orphan/test/slash"); SplitLogTask slt = new SplitLogTask.Unassigned(DUMMY_MASTER, this.mode); zkw.getRecoverableZooKeeper().create(tasknode, slt.toByteArray(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); int version = ZKUtil.checkExists(zkw, tasknode); slm = new SplitLogManager(zkw, conf, stopper, master, DUMMY_MASTER); waitForCounter(tot_mgr_orphan_task_acquired, 0, 1, to/2); Task task = slm.findOrCreateOrphanTask(tasknode); assertTrue(task.isOrphan()); assertTrue(task.isUnassigned()); waitForCounter(tot_mgr_rescan, 0, 1, to/2); Task task2 = slm.findOrCreateOrphanTask(tasknode); assertTrue(task == task2); LOG.debug("task = " + task); assertEquals(1L, tot_mgr_resubmit.get()); assertEquals(1, task.incarnation); assertEquals(0, task.unforcedResubmits.get()); assertTrue(task.isOrphan()); assertTrue(task.isUnassigned()); assertTrue(ZKUtil.checkExists(zkw, tasknode) > version); } |
SplitLogManager extends ZooKeeperListener { void handleDeadWorker(ServerName workerName) { synchronized (deadWorkersLock) { if (deadWorkers == null) { deadWorkers = new HashSet<ServerName>(100); } deadWorkers.add(workerName); } LOG.info("dead splitlog worker " + workerName); } SplitLogManager(ZooKeeperWatcher zkw, final Configuration conf,
Stoppable stopper, MasterServices master, ServerName serverName); SplitLogManager(ZooKeeperWatcher zkw, Configuration conf, Stoppable stopper,
MasterServices master, ServerName serverName, TaskFinisher tf); long splitLogDistributed(final Path logDir); long splitLogDistributed(final List<Path> logDirs); long splitLogDistributed(final Set<ServerName> serverNames, final List<Path> logDirs,
PathFilter filter); static void deleteRecoveringRegionZNodes(ZooKeeperWatcher watcher, List<String> regions); @Override void nodeDataChanged(String path); void stop(); static long parseLastFlushedSequenceIdFrom(final byte[] bytes); static boolean isRegionMarkedRecoveringInZK(ZooKeeperWatcher zkw, String regionEncodedName); static RegionStoreSequenceIds getRegionFlushedSequenceId(ZooKeeperWatcher zkw,
String serverName, String encodedRegionName); void setRecoveryMode(boolean isForInitialization); RecoveryMode getRecoveryMode(); static final int DEFAULT_TIMEOUT; static final int DEFAULT_ZK_RETRIES; static final int DEFAULT_MAX_RESUBMIT; static final int DEFAULT_UNASSIGNED_TIMEOUT; public boolean ignoreZKDeleteForTesting; } | @Test public void testDeadWorker() throws Exception { LOG.info("testDeadWorker"); conf.setLong("hbase.splitlog.max.resubmit", 0); slm = new SplitLogManager(zkw, conf, stopper, master, DUMMY_MASTER); TaskBatch batch = new TaskBatch(); String tasknode = submitTaskAndWait(batch, "foo/1"); int version = ZKUtil.checkExists(zkw, tasknode); final ServerName worker1 = ServerName.valueOf("worker1,1,1"); SplitLogTask slt = new SplitLogTask.Owned(worker1, this.mode); ZKUtil.setData(zkw, tasknode, slt.toByteArray()); if (tot_mgr_heartbeat.get() == 0) waitForCounter(tot_mgr_heartbeat, 0, 1, to/2); slm.handleDeadWorker(worker1); if (tot_mgr_resubmit.get() == 0) waitForCounter(tot_mgr_resubmit, 0, 1, to+to/2); if (tot_mgr_resubmit_dead_server_task.get() == 0) { waitForCounter(tot_mgr_resubmit_dead_server_task, 0, 1, to + to/2); } int version1 = ZKUtil.checkExists(zkw, tasknode); assertTrue(version1 > version); byte[] taskstate = ZKUtil.getData(zkw, tasknode); slt = SplitLogTask.parseFrom(taskstate); assertTrue(slt.isUnassigned(DUMMY_MASTER)); return; } |
SplitLogManager extends ZooKeeperListener { public long splitLogDistributed(final Path logDir) throws IOException { List<Path> logDirs = new ArrayList<Path>(); logDirs.add(logDir); return splitLogDistributed(logDirs); } SplitLogManager(ZooKeeperWatcher zkw, final Configuration conf,
Stoppable stopper, MasterServices master, ServerName serverName); SplitLogManager(ZooKeeperWatcher zkw, Configuration conf, Stoppable stopper,
MasterServices master, ServerName serverName, TaskFinisher tf); long splitLogDistributed(final Path logDir); long splitLogDistributed(final List<Path> logDirs); long splitLogDistributed(final Set<ServerName> serverNames, final List<Path> logDirs,
PathFilter filter); static void deleteRecoveringRegionZNodes(ZooKeeperWatcher watcher, List<String> regions); @Override void nodeDataChanged(String path); void stop(); static long parseLastFlushedSequenceIdFrom(final byte[] bytes); static boolean isRegionMarkedRecoveringInZK(ZooKeeperWatcher zkw, String regionEncodedName); static RegionStoreSequenceIds getRegionFlushedSequenceId(ZooKeeperWatcher zkw,
String serverName, String encodedRegionName); void setRecoveryMode(boolean isForInitialization); RecoveryMode getRecoveryMode(); static final int DEFAULT_TIMEOUT; static final int DEFAULT_ZK_RETRIES; static final int DEFAULT_MAX_RESUBMIT; static final int DEFAULT_UNASSIGNED_TIMEOUT; public boolean ignoreZKDeleteForTesting; } | @Test public void testEmptyLogDir() throws Exception { LOG.info("testEmptyLogDir"); slm = new SplitLogManager(zkw, conf, stopper, master, DUMMY_MASTER); FileSystem fs = TEST_UTIL.getTestFileSystem(); Path emptyLogDirPath = new Path(fs.getWorkingDirectory(), UUID.randomUUID().toString()); fs.mkdirs(emptyLogDirPath); slm.splitLogDistributed(emptyLogDirPath); assertFalse(fs.exists(emptyLogDirPath)); } |
SplitLogManager extends ZooKeeperListener { void removeStaleRecoveringRegionsFromZK(final Set<ServerName> failedServers) throws KeeperException, InterruptedIOException { Set<String> knownFailedServers = new HashSet<String>(); if (failedServers != null) { for (ServerName tmpServerName : failedServers) { knownFailedServers.add(tmpServerName.getServerName()); } } this.recoveringRegionLock.lock(); try { List<String> tasks = ZKUtil.listChildrenNoWatch(watcher, watcher.splitLogZNode); if (tasks != null) { for (String t : tasks) { byte[] data; try { data = ZKUtil.getData(this.watcher, ZKUtil.joinZNode(watcher.splitLogZNode, t)); } catch (InterruptedException e) { throw new InterruptedIOException(); } if (data != null) { SplitLogTask slt = null; try { slt = SplitLogTask.parseFrom(data); } catch (DeserializationException e) { LOG.warn("Failed parse data for znode " + t, e); } if (slt != null && slt.isDone()) { continue; } } t = ZKSplitLog.getFileName(t); ServerName serverName = HLogUtil.getServerNameFromHLogDirectoryName(new Path(t)); if (serverName != null) { knownFailedServers.add(serverName.getServerName()); } else { LOG.warn("Found invalid WAL log file name:" + t); } } } List<String> regions = ZKUtil.listChildrenNoWatch(watcher, watcher.recoveringRegionsZNode); if (regions != null) { for (String region : regions) { String nodePath = ZKUtil.joinZNode(watcher.recoveringRegionsZNode, region); List<String> regionFailedServers = ZKUtil.listChildrenNoWatch(watcher, nodePath); if (regionFailedServers == null || regionFailedServers.isEmpty()) { ZKUtil.deleteNode(watcher, nodePath); continue; } boolean needMoreRecovery = false; for (String tmpFailedServer : regionFailedServers) { if (knownFailedServers.contains(tmpFailedServer)) { needMoreRecovery = true; break; } } if (!needMoreRecovery) { ZKUtil.deleteNodeRecursively(watcher, nodePath); } } } } finally { this.recoveringRegionLock.unlock(); } } SplitLogManager(ZooKeeperWatcher zkw, final Configuration conf,
Stoppable stopper, MasterServices master, ServerName serverName); SplitLogManager(ZooKeeperWatcher zkw, Configuration conf, Stoppable stopper,
MasterServices master, ServerName serverName, TaskFinisher tf); long splitLogDistributed(final Path logDir); long splitLogDistributed(final List<Path> logDirs); long splitLogDistributed(final Set<ServerName> serverNames, final List<Path> logDirs,
PathFilter filter); static void deleteRecoveringRegionZNodes(ZooKeeperWatcher watcher, List<String> regions); @Override void nodeDataChanged(String path); void stop(); static long parseLastFlushedSequenceIdFrom(final byte[] bytes); static boolean isRegionMarkedRecoveringInZK(ZooKeeperWatcher zkw, String regionEncodedName); static RegionStoreSequenceIds getRegionFlushedSequenceId(ZooKeeperWatcher zkw,
String serverName, String encodedRegionName); void setRecoveryMode(boolean isForInitialization); RecoveryMode getRecoveryMode(); static final int DEFAULT_TIMEOUT; static final int DEFAULT_ZK_RETRIES; static final int DEFAULT_MAX_RESUBMIT; static final int DEFAULT_UNASSIGNED_TIMEOUT; public boolean ignoreZKDeleteForTesting; } | @Test(timeout = 300000) public void testRecoveryRegionRemovedFromZK() throws Exception { LOG.info("testRecoveryRegionRemovedFromZK"); conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false); String nodePath = ZKUtil.joinZNode(zkw.recoveringRegionsZNode, HRegionInfo.FIRST_META_REGIONINFO.getEncodedName()); ZKUtil.createSetData(zkw, nodePath, ZKUtil.positionToByteArray(0L)); slm = new SplitLogManager(zkw, conf, stopper, master, DUMMY_MASTER); slm.removeStaleRecoveringRegionsFromZK(null); List<String> recoveringRegions = zkw.getRecoverableZooKeeper().getChildren(zkw.recoveringRegionsZNode, false); assertTrue("Recovery regions isn't cleaned", recoveringRegions.isEmpty()); } |
CleanerChore extends Chore { @Override protected void chore() { try { FileStatus[] files = FSUtils.listStatus(this.fs, this.oldFileDir); checkAndDeleteEntries(files); } catch (IOException e) { e = RemoteExceptionHandler.checkIOException(e); LOG.warn("Error while cleaning the logs", e); } } CleanerChore(String name, final int sleepPeriod, final Stoppable s, Configuration conf,
FileSystem fs, Path oldFileDir, String confKey); @Override void cleanup(); } | @Test public void testSavesFilesOnRequest() throws Exception { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); Path testDir = UTIL.getDataTestDir(); FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, NeverDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); Path parent = new Path(testDir, "parent"); Path file = new Path(parent, "someFile"); fs.mkdirs(parent); fs.create(file).close(); assertTrue("Test file didn't get created.", fs.exists(file)); chore.chore(); assertTrue("File didn't get deleted", fs.exists(file)); assertTrue("Empty directory didn't get deleted", fs.exists(parent)); }
@Test public void testDeletesEmptyDirectories() throws Exception { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); Path testDir = UTIL.getDataTestDir(); FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); Path parent = new Path(testDir, "parent"); Path child = new Path(parent, "child"); Path emptyChild = new Path(parent, "emptyChild"); Path file = new Path(child, "someFile"); fs.mkdirs(child); fs.mkdirs(emptyChild); fs.create(file).close(); Path topFile = new Path(testDir, "topFile"); fs.create(topFile).close(); assertTrue("Test file didn't get created.", fs.exists(file)); assertTrue("Test file didn't get created.", fs.exists(topFile)); chore.chore(); assertFalse("File didn't get deleted", fs.exists(topFile)); assertFalse("File didn't get deleted", fs.exists(file)); assertFalse("Empty directory didn't get deleted", fs.exists(child)); assertFalse("Empty directory didn't get deleted", fs.exists(parent)); }
@Test public void testDoesNotCheckDirectories() throws Exception { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); Path testDir = UTIL.getDataTestDir(); FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); AlwaysDelete delegate = (AlwaysDelete) chore.cleanersChain.get(0); AlwaysDelete spy = Mockito.spy(delegate); chore.cleanersChain.set(0, spy); Path parent = new Path(testDir, "parent"); Path file = new Path(parent, "someFile"); fs.mkdirs(parent); assertTrue("Test parent didn't get created.", fs.exists(parent)); fs.create(file).close(); assertTrue("Test file didn't get created.", fs.exists(file)); FileStatus fStat = fs.getFileStatus(parent); chore.chore(); Mockito.verify(spy, Mockito.never()).isFileDeletable(fStat); Mockito.reset(spy); }
@Test public void testStoppedCleanerDoesNotDeleteFiles() throws Exception { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); Path testDir = UTIL.getDataTestDir(); FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); Path topFile = new Path(testDir, "topFile"); fs.create(topFile).close(); assertTrue("Test file didn't get created.", fs.exists(topFile)); stop.stop("testing stop"); chore.chore(); assertTrue("File got deleted while chore was stopped", fs.exists(topFile)); }
@Test public void testCleanerDoesNotDeleteDirectoryWithLateAddedFiles() throws IOException { Stoppable stop = new StoppableImplementation(); Configuration conf = UTIL.getConfiguration(); final Path testDir = UTIL.getDataTestDir(); final FileSystem fs = UTIL.getTestFileSystem(); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); AlwaysDelete delegate = (AlwaysDelete) chore.cleanersChain.get(0); AlwaysDelete spy = Mockito.spy(delegate); chore.cleanersChain.set(0, spy); final Path parent = new Path(testDir, "parent"); Path file = new Path(parent, "someFile"); fs.mkdirs(parent); fs.create(file).close(); assertTrue("Test file didn't get created.", fs.exists(file)); final Path addedFile = new Path(parent, "addedFile"); Mockito.doAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { fs.create(addedFile).close(); FSUtils.logFileSystemState(fs, testDir, LOG); return (Boolean) invocation.callRealMethod(); } }).when(spy).isFileDeletable(Mockito.any(FileStatus.class)); chore.chore(); assertTrue("Added file unexpectedly deleted", fs.exists(addedFile)); assertTrue("Parent directory deleted unexpectedly", fs.exists(parent)); assertFalse("Original file unexpectedly retained", fs.exists(file)); Mockito.verify(spy, Mockito.times(1)).isFileDeletable(Mockito.any(FileStatus.class)); Mockito.reset(spy); } |
CleanerChore extends Chore { @VisibleForTesting boolean checkAndDeleteDirectory(Path dir) { if (LOG.isTraceEnabled()) { LOG.trace("Checking directory: " + dir); } try { FileStatus[] children = FSUtils.listStatus(fs, dir); boolean allChildrenDeleted = checkAndDeleteEntries(children); if (!allChildrenDeleted) return false; } catch (IOException e) { e = RemoteExceptionHandler.checkIOException(e); LOG.warn("Error while listing directory: " + dir, e); return false; } try { return fs.delete(dir, false); } catch (IOException e) { if (LOG.isTraceEnabled()) { LOG.trace("Couldn't delete directory: " + dir, e); } return false; } } CleanerChore(String name, final int sleepPeriod, final Stoppable s, Configuration conf,
FileSystem fs, Path oldFileDir, String confKey); @Override void cleanup(); } | @Test public void testNoExceptionFromDirectoryWithRacyChildren() throws Exception { Stoppable stop = new StoppableImplementation(); HBaseTestingUtility localUtil = new HBaseTestingUtility(); Configuration conf = localUtil.getConfiguration(); final Path testDir = UTIL.getDataTestDir(); final FileSystem fs = UTIL.getTestFileSystem(); LOG.debug("Writing test data to: " + testDir); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); AlwaysDelete delegate = (AlwaysDelete) chore.cleanersChain.get(0); AlwaysDelete spy = Mockito.spy(delegate); chore.cleanersChain.set(0, spy); final Path parent = new Path(testDir, "parent"); Path file = new Path(parent, "someFile"); fs.mkdirs(parent); fs.create(file).close(); assertTrue("Test file didn't get created.", fs.exists(file)); final Path racyFile = new Path(parent, "addedFile"); Mockito.doAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { fs.create(racyFile).close(); FSUtils.logFileSystemState(fs, testDir, LOG); return (Boolean) invocation.callRealMethod(); } }).when(spy).isFileDeletable(Mockito.any(FileStatus.class)); if (chore.checkAndDeleteDirectory(parent)) { throw new Exception( "Reported success deleting directory, should have failed when adding file mid-iteration"); } assertTrue("Added file unexpectedly deleted", fs.exists(racyFile)); assertTrue("Parent directory deleted unexpectedly", fs.exists(parent)); assertFalse("Original file unexpectedly retained", fs.exists(file)); Mockito.verify(spy, Mockito.times(1)).isFileDeletable(Mockito.any(FileStatus.class)); } |
SnapshotFileCache implements Stoppable { public synchronized boolean contains(String fileName) throws IOException { boolean hasFile = this.cache.contains(fileName); if (!hasFile) { refreshCache(); hasFile = this.cache.contains(fileName); } return hasFile; } SnapshotFileCache(Configuration conf, long cacheRefreshPeriod, String refreshThreadName,
SnapshotFileInspector inspectSnapshotFiles); SnapshotFileCache(FileSystem fs, Path rootDir, long cacheRefreshPeriod,
long cacheRefreshDelay, String refreshThreadName, SnapshotFileInspector inspectSnapshotFiles); void triggerCacheRefreshForTesting(); synchronized boolean contains(String fileName); @Override void stop(String why); @Override boolean isStopped(); } | @Test public void testJustFindLogsDirectory() throws Exception { long period = Long.MAX_VALUE; Path snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir); SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000, "test-snapshot-file-cache-refresh", new SnapshotFileCache.SnapshotFileInspector() { public Collection<String> filesUnderSnapshot(final Path snapshotDir) throws IOException { return SnapshotReferenceUtil.getHLogNames(fs, snapshotDir); } }); SnapshotDescription desc = SnapshotDescription.newBuilder().setName("snapshot").build(); Path snapshot = SnapshotDescriptionUtils.getCompletedSnapshotDir(desc, rootDir); SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshot, fs); Path file1 = new Path(new Path(new Path(snapshot, "7e91021"), "fam"), "file1"); fs.createNewFile(file1); Path logs = getSnapshotHLogsDir(snapshot, "server"); Path log = new Path(logs, "me.hbase.com%2C58939%2C1350424310315.1350424315552"); fs.createNewFile(log); FSUtils.logFileSystemState(fs, rootDir, LOG); assertFalse("Cache found '" + file1 + "', but it shouldn't have.", cache.contains(file1.getName())); assertTrue("Cache didn't find:" + log, cache.contains(log.getName())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.