protected void setUpLogExpectations(boolean debug) { mockStatic(LogFactoryCompat.class); LogCompat log = createMock(LogCompat.class); expect(LogFactoryCompat.getLog(AbstractBackendResource.class)).andReturn(log); expect(log.isDebugEnabled()).andReturn(debug).anyTimes(); replayAll(); }
public class DateMapper { protected static final LogCompat LOG = LogFactoryCompat.getLog(DateMapper.class); protected static final String DATATYPE_FACTORY_CREATION_FAILED = "DatatypeFactory creation failed"; private static DatatypeFactory datatypeFactory; /** * Class-level synchronization to avoid potential thread-safety issues with statically shared * DatatypeFactory. */ @Mapping(from = Date.class, to = XMLGregorianCalendar.class) public static synchronized XMLGregorianCalendar map(Date date, XMLGregorianCalendar template) { GregorianCalendar calendar = template != null ? template.toGregorianCalendar() : new GregorianCalendar(); calendar.setTime(date); DatatypeFactory factory = getDatatypeFactory(); return factory != null ? factory.newXMLGregorianCalendar(calendar) : null; } @Mapping(from = Integer.class, to = XMLGregorianCalendar.class) public static synchronized XMLGregorianCalendar map( BigDecimal secondsAgo, XMLGregorianCalendar template) { GregorianCalendar calendar = template != null ? template.toGregorianCalendar() : new GregorianCalendar(TimeZone.getTimeZone("UTC")); DatatypeFactory factory = getDatatypeFactory(); XMLGregorianCalendar ret = null; if (factory != null) { ret = factory.newXMLGregorianCalendar(calendar); ret.add(factory.newDuration(false, 0, 0, 0, 0, 0, secondsAgo.intValue())); } return ret; } /** @pre called with class-level mutex held */ private static DatatypeFactory getDatatypeFactory() { if (datatypeFactory == null) { try { datatypeFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException dce) { LOG.warn(DATATYPE_FACTORY_CREATION_FAILED, dce); } } return datatypeFactory; } }
public class MaintananceVdsCommand<T extends MaintananceVdsParameters> extends VdsCommand<T> { private final boolean _isInternal; private List<VM> vms; public MaintananceVdsCommand(T parameters) { super(parameters); _isInternal = parameters.getIsInternal(); } @Override protected void executeCommand() { if (getVds().getstatus() == VDSStatus.Maintenance) { // nothing to do setSucceeded(true); } else { setSucceeded(MigrateAllVms()); /** if non responsive move directly to maintenance */ if (getVds().getstatus() == VDSStatus.NonResponsive || getVds().getstatus() == VDSStatus.Problematic || getVds().getstatus() == VDSStatus.Down) { Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.SetVdsStatus, new SetVdsStatusVDSCommandParameters(getVdsId(), VDSStatus.Maintenance)); } } } protected void orderListOfRunningVmsOnVds(Guid vdsId) { vms = DbFacade.getInstance().getVmDAO().getAllRunningForVds(vdsId); Collections.sort(vms, Collections.reverseOrder(new VmsComparer())); } protected boolean MigrateAllVms() { return MigrateAllVms(false); } protected boolean MigrateAllVms(boolean HAOnly) { orderListOfRunningVmsOnVds(getVdsId()); boolean succeeded = true; for (VM vm : vms) { // if HAOnly is true check that vm is HA (auto_startup should be // true) if (vm.getstatus() != VMStatus.MigratingFrom && (!HAOnly || (HAOnly && vm.getauto_startup()))) { MigrateVmParameters tempVar = new MigrateVmParameters(false, vm.getvm_guid()); tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew); VdcReturnValueBase result = Backend.getInstance().runInternalAction(VdcActionType.InternalMigrateVm, tempVar); if (!result.getCanDoAction() || !(((Boolean) result.getActionReturnValue()).booleanValue())) { succeeded = false; AppendCustomValue("failedVms", vm.getvm_name(), ","); log.errorFormat( "ResourceManager::vdsMaintenance - Failed migrating desktop '{0}'", vm.getvm_name()); } } } return succeeded; } @Override protected boolean canDoAction() { return CanMaintananceVds(getVdsId(), getReturnValue().getCanDoActionMessages()); } @Override public AuditLogType getAuditLogTypeValue() { if (_isInternal) { if (getSucceeded()) { return AuditLogType.VDS_MAINTENANCE; } else { return AuditLogType.VDS_MAINTENANCE_FAILED; } } else { if (getSucceeded()) { return AuditLogType.USER_VDS_MAINTENANCE; } else { return AuditLogType.USER_VDS_MAINTENANCE_MIGRATION_FAILED; } } } public boolean CanMaintananceVds(Guid vdsId, java.util.ArrayList<String> reasons) { boolean returnValue = true; // VDS vds = ResourceManager.Instance.getVds(vdsId); VDS vds = DbFacade.getInstance().getVdsDAO().get(vdsId); // we can get here when vds status was set already to Maintenance if ((vds.getstatus() != VDSStatus.Maintenance) && (vds.getstatus() != VDSStatus.NonResponsive) && (vds.getstatus() != VDSStatus.Up) && (vds.getstatus() != VDSStatus.Error) && (vds.getstatus() != VDSStatus.PreparingForMaintenance) && (vds.getstatus() != VDSStatus.Down)) { returnValue = false; reasons.add(VdcBllMessages.VDS_CANNOT_MAINTENANCE_VDS_IS_NOT_OPERATIONAL.toString()); } orderListOfRunningVmsOnVds(vdsId); for (VM vm : vms) { if (vm.getMigrationSupport() != MigrationSupport.MIGRATABLE) { reasons.add(VdcBllMessages.VDS_CANNOT_MAINTENANCE_IT_INCLUDES_NON_MIGRATABLE_VM.toString()); return false; } } return returnValue; } public static void ProcessStorageOnVdsInactive(VDS vds) { // Clear the problematic timers since the VDS is in maintenance so it doesn't make sense to // check it // anymore. IrsBrokerCommand.clearVdsFromCache( vds.getstorage_pool_id(), vds.getvds_id(), vds.getvds_name()); if (!vds.getstorage_pool_id().equals(Guid.Empty) && StoragePoolStatus.Uninitialized != DbFacade.getInstance().getStoragePoolDAO().get(vds.getstorage_pool_id()).getstatus() && Backend.getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters( vds.getvds_id(), vds.getstorage_pool_id(), vds.getvds_spm_id())) .getSucceeded()) { StoragePoolParametersBase tempVar = new StoragePoolParametersBase(vds.getstorage_pool_id()); tempVar.setVdsId(vds.getvds_id()); tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew); Backend.getInstance() .runInternalAction(VdcActionType.DisconnectHostFromStoragePoolServers, tempVar); } } private static LogCompat log = LogFactoryCompat.getLog(MaintananceVdsCommand.class); }
public class LdapTestsSetup { private Configuration testProperties; private IPAGroupDaoImpl ipaGroupDao = new IPAGroupDaoImpl(); private IPAPersonDaoImpl ipaPersonDao = new IPAPersonDaoImpl(); private ADPersonDaoImpl adPersonDao = new ADPersonDaoImpl(); private ADGroupDaoImpl adGroupDao = new ADGroupDaoImpl(); private LdapTemplate ipaLdapTemplate; private LdapTemplate adLdapTemplate; private LdapContextSource ipaLdapContext; private LdapContextSource adLdapContext; private Map<String, Person> users = new HashMap<String, Person>(); private Map<String, Group> groups = new HashMap<String, Group>(); private Map<String, String> ldapConfiguration = new HashMap<String, String>(); private static LogCompat log = LogFactoryCompat.getLog(LdapTestsSetup.class); public LdapTestsSetup() { String confFile = System.getenv("LDAP_TESTER_PROPERTIES_FILE"); if (confFile == null) { confFile = "ldap.integ/ldap-test.properties"; } try { testProperties = new PropertiesConfiguration(confFile); Configuration usersSubset = testProperties.subset("users"); HierarchicalConfiguration usersConfig = ConfigurationUtils.convertToHierarchical(usersSubset); List<ConfigurationNode> childrens = usersConfig.getRootNode().getChildren(); for (ConfigurationNode node : childrens) { String name = node.getName(); users.put(name, new Person(usersSubset.subset(name))); } Configuration groupsSubset = testProperties.subset("groups"); HierarchicalConfiguration groupsConfig = ConfigurationUtils.convertToHierarchical(groupsSubset); childrens = groupsConfig.getRootNode().getChildren(); for (ConfigurationNode node : childrens) { String name = node.getName(); groups.put(name, new Group(groupsSubset.subset(name))); } Configuration ldapConfigurationSubset = testProperties.subset("configuration"); HierarchicalConfiguration ldapConfig = ConfigurationUtils.convertToHierarchical(ldapConfigurationSubset); childrens = ldapConfig.getRootNode().getChildren(); for (ConfigurationNode node : childrens) { String key = node.getName(); String value = (String) node.getValue(); ldapConfiguration.put(key, value); } } catch (ConfigurationException ex) { String message = "Problem loading configuration: " + ex.getMessage(); log.error(message); throw new IllegalStateException(message); } } public void setup() throws Exception { setIpaLdapContext(ContextSourceFactory.getIPAContextSource(ldapConfiguration)); getIpaLdapContext().afterPropertiesSet(); setAdLdapContext(ContextSourceFactory.getADContextSource(ldapConfiguration)); getAdLdapContext().afterPropertiesSet(); ipaLdapTemplate = new LdapTemplate(getIpaLdapContext()); adLdapTemplate = new LdapTemplate(getAdLdapContext()); ipaPersonDao.setLdapTemplate(ipaLdapTemplate); ipaGroupDao.setLdapTemplate(ipaLdapTemplate); adPersonDao.setLdapTemplate(adLdapTemplate); adGroupDao.setLdapTemplate(adLdapTemplate); } public void populateUsersAndGroups() throws ConfigurationException, URISyntaxException { for (Person p : users.values()) { ipaPersonDao.create(p); adPersonDao.create(p); } List<String> list = new ArrayList<String>(groups.keySet()); Collections.sort(list); for (String groupName : list) { Group group = groups.get(groupName); ipaGroupDao.create(group); adGroupDao.create(group); System.out.println(groupName); } } public Person getUser(String userName) { return users.get(userName); } public Group getGroup(String groupName) { return groups.get(groupName); } public void cleanup() { for (Person p : users.values()) { ipaPersonDao.delete(p); adPersonDao.delete(p); } for (Group g : groups.values()) { ipaGroupDao.delete(g); adGroupDao.delete(g); } } public IPAGroupDaoImpl getIpaGroupDao() { return ipaGroupDao; } public IPAPersonDaoImpl getIpaPersonDao() { return ipaPersonDao; } public ADPersonDaoImpl getAdPersonDao() { return adPersonDao; } public ADGroupDaoImpl getAdGroupDao() { return adGroupDao; } public void setIpaLdapContext(LdapContextSource ipaLdapContext) { this.ipaLdapContext = ipaLdapContext; } public LdapContextSource getIpaLdapContext() { return ipaLdapContext; } public void setAdLdapContext(LdapContextSource adLdapContext) { this.adLdapContext = adLdapContext; } public LdapContextSource getAdLdapContext() { return adLdapContext; } }
/** Implements a GSSAPI directory context authentication strategy to be used with LDAP */ public class GSSAPIDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { private static final String GSS_API_AUTHENTICATION = "GSSAPI"; private static final String LOGIN_MODULE_POLICY_NAME = "RHEVKerberosAuth"; private static LogCompat log = LogFactoryCompat.getLog(GSSAPIDirContextAuthenticationStrategy.class); private LoginContext loginContext; private String password; private String userName; private String realm; private boolean explicitAuth; public void setExplicitAuth(boolean explicitAuth) { this.explicitAuth = explicitAuth; } public LoginContext getLoginContext() { return loginContext; } /** * @param password * @param userName * @param explicitAuth */ public GSSAPIDirContextAuthenticationStrategy( String userName, String password, String realm, boolean explicitAuth) { this.userName = userName; this.password = password; this.realm = realm; this.explicitAuth = explicitAuth; } /* * (non-Javadoc) * * @see * org.springframework.ldap.core.support.DirContextAuthenticationStrategy * #setupEnvironment(java.util.Hashtable, java.lang.String, * java.lang.String) */ @Override public void setupEnvironment(Hashtable env, String userDn, String password) throws NamingException { env.put(Context.SECURITY_AUTHENTICATION, GSS_API_AUTHENTICATION); String qopValue = Config.<String>GetValue(ConfigValues.SASL_QOP); env.put("javax.security.sasl.qop", qopValue); } /* * (non-Javadoc) * * @see * org.springframework.ldap.core.support.DirContextAuthenticationStrategy * #processContextAfterCreation(javax.naming.directory.DirContext, * java.lang.String, java.lang.String) */ @Override public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) throws NamingException { return ctx; } public void authenticate() throws EngineDirectoryServiceException { UsersDomainsCacheManager usersDomainsCacheManager = UsersDomainsCacheManagerService.getInstance(); UserDomainInfo userDomainInfo = usersDomainsCacheManager.associateUserWithDomain(this.userName, this.realm.toLowerCase()); loginContext = null; synchronized (userDomainInfo) { // In case authentication is performed in an implicit way (as a // result of internal command) try and get // login context from cache if (!explicitAuth) { loginContext = userDomainInfo.getLoginContext(); } if (!validLoginContext()) { explicitAuth(userDomainInfo); } } } private void explicitAuth(UserDomainInfo userDomainInfo) throws EngineDirectoryServiceException { GSSAPICallbackHandler callbackHandler = new GSSAPICallbackHandler(userName, password); authenticateToKDC(callbackHandler, userDomainInfo); } private void authenticateToKDC( GSSAPICallbackHandler callbackHandler, UserDomainInfo userDomainInfo) throws EngineDirectoryServiceException { try { loginContext = new LoginContext(LOGIN_MODULE_POLICY_NAME, callbackHandler); loginContext.login(); userDomainInfo.setLoginContext(loginContext); if (log.isDebugEnabled()) { log.debug("Successful login for user " + userName); } } catch (LoginException ex) { // JAAS throws login exception due to various reasons. // We check if the login exception matches a case where the user // provided wrong authentication details, or // if there was another error - in case the user provided wrong // authentication details, we will abort the kdc search loginContext = null; KerberosReturnCodeParser parser = new KerberosReturnCodeParser(); AuthenticationResult result = parser.parse(ex.getMessage()); if (result == AuthenticationResult.OTHER || result == null) { // An error our error parser does not recognize log.error("Error from Kerberos: " + ex.getMessage()); } else { StringBuilder error = new StringBuilder(); error.append(result.getDetailedMessage()); log.error(error.toString()); } throw new EngineDirectoryServiceException(result); } } private boolean validLoginContext() { if (loginContext == null) return false; Subject subject = loginContext.getSubject(); if (subject == null) return false; Set<KerberosTicket> privateCreds = subject.getPrivateCredentials(KerberosTicket.class); if (privateCreds == null || privateCreds.size() == 0) return false; Iterator<KerberosTicket> iterator = privateCreds.iterator(); KerberosTicket ticket = iterator.next(); return ticket.isCurrent(); } }