Shireesh Anjal has uploaded a new change for review. Change subject: gluster: Refactor GetGlusterServersForImportQuery ......................................................................
gluster: Refactor GetGlusterServersForImportQuery Extracted methods related to fetching gluster peers of a given server into a new utility class GlusterUtil Also added few more tests in GetGlusterServersForImportQueryTest Change-Id: Ib4620c19997c10b202ef5dc5abdbeee9f245937d Signed-off-by: Shireesh Anjal <[email protected]> --- M backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQuery.java M backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQueryTest.java A backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/gluster/GlusterUtil.java A backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/gluster/GlusterUtilTest.java 4 files changed, 373 insertions(+), 171 deletions(-) git pull ssh://gerrit.ovirt.org:29418/ovirt-engine refs/changes/77/13977/1 diff --git a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQuery.java b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQuery.java index 3f34340..48bea59 100644 --- a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQuery.java +++ b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQuery.java @@ -1,31 +1,16 @@ package org.ovirt.engine.core.bll.gluster; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.AccessControlException; -import java.security.PublicKey; -import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.naming.AuthenticationException; -import javax.xml.parsers.ParserConfigurationException; -import org.apache.commons.lang.StringUtils; -import org.ovirt.engine.core.common.config.Config; -import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.queries.gluster.GlusterServersQueryParameters; import org.ovirt.engine.core.dal.VdcBllMessages; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dao.VdsStaticDAO; -import org.ovirt.engine.core.utils.XmlUtils; -import org.ovirt.engine.core.utils.crypt.OpenSSHUtils; -import org.ovirt.engine.core.utils.ssh.ConstraintByteArrayOutputStream; +import org.ovirt.engine.core.utils.gluster.GlusterUtil; import org.ovirt.engine.core.utils.ssh.SSHClient; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; /** * Query to fetch list of gluster servers via ssh using the given serverName and password. @@ -39,43 +24,37 @@ */ public class GetGlusterServersForImportQuery<P extends GlusterServersQueryParameters> extends GlusterQueriesCommandBase<P> { - private static final String PEER = "peer"; - private static final String HOST_NAME = "hostname"; - private static final String STATE = "state"; - private static final int PEER_IN_CLUSTER = 3; - private static final int PORT = 22; - private static final String ROOT = "root"; - public GetGlusterServersForImportQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { + getQueryReturnValue().setSucceeded(true); + // Check whether the given server is already part of the cluster if (getVdsStaticDao().getByHostName(getParameters().getServerName()) != null || getVdsStaticDao().getAllWithIpAddress(getParameters().getServerName()).size() > 0) { - setReturnMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); + setErrorMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); return; } SSHClient client = null; try { - client = connect(getParameters().getServerName()); - validateFingerprint(client, getParameters().getFingerprint()); - authenticate(client, ROOT, getParameters().getPassword()); - String serversXml = executeCommand(client); - - Map<String, String> serverFingerPrint = extractServers(serversXml); + Map<String, String> serverFingerPrint = + getGlusterUtil().getPeers(getParameters().getServerName(), + getParameters().getPassword(), + getParameters().getFingerprint()); // Check if any of the server in the map is already part of some other cluster. if (!validateServers(serverFingerPrint.keySet())) { - setReturnMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); + setErrorMessage(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString()); } + getQueryReturnValue().setReturnValue(serverFingerPrint); } catch (AuthenticationException ae) { - setReturnMessage(VdcBllMessages.SSH_AUTHENTICATION_FAILED.toString()); + setErrorMessage(VdcBllMessages.SSH_AUTHENTICATION_FAILED.toString()); } catch (Exception e) { throw new RuntimeException(e); @@ -86,7 +65,11 @@ } } - private void setReturnMessage(String errorMessage) { + protected GlusterUtil getGlusterUtil() { + return GlusterUtil.getInstance(); + } + + private void setErrorMessage(String errorMessage) { getQueryReturnValue().setSucceeded(false); getQueryReturnValue().setExceptionString(errorMessage); } @@ -102,100 +85,6 @@ } } return true; - } - - protected Map<String, String> extractServers(String serversXml) throws ParserConfigurationException, - SAXException, IOException { - if (StringUtils.isNotEmpty(serversXml)) { - return getServerFingerprints(XmlUtils.loadXmlDoc(serversXml).getElementsByTagName(PEER)); - } else { - throw new RuntimeException("Could not get the peer list form the host: " + getParameters().getServerName()); - } - } - - private Map<String, String> getServerFingerprints(NodeList listOfPeers) { - Map<String, String> fingerprints = new HashMap<String, String>(); - // Add current server finger print also in the map - fingerprints.put(getParameters().getServerName(), getParameters().getFingerprint()); - for (int i = 0; i < listOfPeers.getLength(); i++) { - Node firstPeer = listOfPeers.item(i); - if (firstPeer.getNodeType() == Node.ELEMENT_NODE) { - Element firstHostElement = (Element) firstPeer; - int state = XmlUtils.getIntValue(firstHostElement, STATE); - // Add the server only if the state is 3 - if (state == PEER_IN_CLUSTER) { - String hostName = XmlUtils.getTextValue(firstHostElement, HOST_NAME); - fingerprints.put(hostName, getFingerprint(hostName)); - } - } - } - return fingerprints; - } - - protected void validateFingerprint(SSHClient client, String fingerprint) { - if (!fingerprint.equals(getFingerprint(client))) { - throw new AccessControlException( - String.format( - "SSH Fingerprint of server '%1$s' did not match expected fingerprint '%2$s'", - client.getDisplayHost(), - fingerprint - )); - } - } - - // This is required for mock during Junit test - protected SSHClient createSSHClient() { - return new SSHClient(); - } - - protected SSHClient connect(String serverName) { - SSHClient client = createSSHClient(); - Integer timeout = Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds) * 1000; - client.setHardTimeout(timeout); - client.setSoftTimeout(timeout); - client.setHost(serverName, PORT); - try { - client.connect(); - return client; - } catch (Exception e) { - log.debug(String.format("Could not connect to server %1$s: %2$s", serverName, e.getMessage())); - throw new RuntimeException(e); - } - } - - protected void authenticate(SSHClient client, String userId, String password) throws Exception { - client.setUser(userId); - client.setPassword(password); - client.authenticate(); - } - - protected String executeCommand(SSHClient client) throws Exception { - ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); - String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); - client.executeCommand(command, null, out, null); - return new String(out.toByteArray(), "UTF-8"); - } - - private String getFingerprint(String hostName) { - SSHClient client = null; - try { - client = connect(hostName); - return getFingerprint(client); - } finally { - if(client != null) { - client.disconnect(); - } - } - } - - private String getFingerprint(SSHClient client) { - PublicKey hostKey = client.getHostKey(); - if (hostKey == null) { - log.error("Could not get server key"); - return null; - } - - return OpenSSHUtils.getKeyFingerprintString(hostKey); } protected VdsStaticDAO getVdsStaticDao() { diff --git a/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQueryTest.java b/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQueryTest.java index dfc82ad..5cd96e9 100644 --- a/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQueryTest.java +++ b/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/gluster/GetGlusterServersForImportQueryTest.java @@ -1,98 +1,124 @@ package org.ovirt.engine.core.bll.gluster; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doNothing; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; -import static org.ovirt.engine.core.utils.MockConfigRule.mockConfig; -import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; +import javax.naming.AuthenticationException; + import org.junit.Before; -import org.junit.ClassRule; import org.junit.Test; import org.ovirt.engine.core.bll.AbstractQueryTest; import org.ovirt.engine.core.common.businessentities.VdsStatic; -import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.queries.gluster.GlusterServersQueryParameters; import org.ovirt.engine.core.compat.Guid; +import org.ovirt.engine.core.dal.VdcBllMessages; import org.ovirt.engine.core.dao.VdsStaticDAO; -import org.ovirt.engine.core.utils.MockConfigRule; -import org.ovirt.engine.core.utils.ssh.SSHClient; +import org.ovirt.engine.core.utils.gluster.GlusterUtil; public class GetGlusterServersForImportQueryTest extends AbstractQueryTest<GlusterServersQueryParameters, GetGlusterServersForImportQuery<GlusterServersQueryParameters>> { - private static final String SERVER_NAME1 = "testserver1"; private static final String SERVER_NAME2 = "testserver2"; private static final String NEW_SERVER = "testserver3"; + private static final String EXISTING_SERVER = "testserver4"; private static final String PASSWORD = "password"; - private Map<String, String> EXPECTED_MAP = new HashMap<String, String>(); + private static final String WRONG_PASSWORD = "wrong_password"; + private static final Map<String, String> EXPECTED_MAP = new HashMap<String, String>(); private static final String FINGER_PRINT1 = "31:e2:1b:7e:89:86:99:c3:f7:1e:57:35:fe:9b:5c:31"; - private static final int CONNECT_TO_SERVER_TIMEOUT = 20; - private static final String GLUSTER_PEER_STATUS_CMD = "gluster peer status --xml"; - private static final String OUTPUT_XML = - "<cliOutput><peerStatus><peer><uuid>85c42b0d-c2b7-424a-ae72-5174c25da40b</uuid><hostname>testserver1</hostname><connected>1</connected><state>3</state></peer>" - + - "<peer><uuid>85c42b0d-c2b7-424a-ae72-5174c25da40b</uuid><hostname>testserver2</hostname><connected>1</connected><state>3</state></peer></peerStatus></cliOutput>"; - private SSHClient clientMock; - private VdsStaticDAO vdsStaticDaoMock; + private static final String FINGER_PRINT2 = "31:e2:1b:7e:89:86:99:c3:f7:1e:57:35:fe:9b:5c:32"; - @ClassRule - public static MockConfigRule mcr = new MockConfigRule( - mockConfig(ConfigValues.ConnectToServerTimeoutInSeconds, CONNECT_TO_SERVER_TIMEOUT), - mockConfig(ConfigValues.GlusterPeerStatusCommand, GLUSTER_PEER_STATUS_CMD)); + private VdsStaticDAO vdsStaticDao; + private GlusterUtil glusterUtil; @Before @Override public void setUp() throws Exception { super.setUp(); setupMock(); - setupExpectedFingerPrint(); } - private void setupMock() { - vdsStaticDaoMock = mock(VdsStaticDAO.class); - doReturn(vdsStaticDaoMock).when(getQuery()).getVdsStaticDao(); - doReturn(getVdsStatic().get(0)).when(vdsStaticDaoMock).getByHostName(NEW_SERVER); - doReturn(getVdsStatic()).when(vdsStaticDaoMock).getAllWithIpAddress(NEW_SERVER); + private void setupMock() throws AuthenticationException { + vdsStaticDao = mock(VdsStaticDAO.class); + doReturn(vdsStaticDao).when(getQuery()).getVdsStaticDao(); + doReturn(null).when(vdsStaticDao).getByHostName(NEW_SERVER); + doReturn(getVdsStatic()).when(vdsStaticDao).getByHostName(EXISTING_SERVER); - clientMock = mock(SSHClient.class); - doReturn(clientMock).when(getQuery()).createSSHClient(); + glusterUtil = mock(GlusterUtil.class); + doReturn(glusterUtil).when(getQuery()).getGlusterUtil(); + + EXPECTED_MAP.put(SERVER_NAME1, FINGER_PRINT1); + EXPECTED_MAP.put(SERVER_NAME2, FINGER_PRINT2); + doReturn(EXPECTED_MAP).when(glusterUtil).getPeers(NEW_SERVER, PASSWORD, FINGER_PRINT1); + doThrow(AuthenticationException.class).when(glusterUtil).getPeers(NEW_SERVER, WRONG_PASSWORD, FINGER_PRINT1); } - private List<VdsStatic> getVdsStatic() { + private VdsStatic getVdsStatic() { VdsStatic vds = new VdsStatic(); vds.setId(new Guid()); vds.setHostName(NEW_SERVER); - return Collections.singletonList(vds); + return vds; } - private void setupExpectedFingerPrint() throws Exception { - doReturn(SERVER_NAME1).when(getQueryParameters()).getServerName(); - doReturn(PASSWORD).when(getQueryParameters()).getPassword(); + private void mockQueryParameters(String server, String password) { + doReturn(server).when(getQueryParameters()).getServerName(); + doReturn(password).when(getQueryParameters()).getPassword(); doReturn(FINGER_PRINT1).when(getQueryParameters()).getFingerprint(); - doReturn(clientMock).when(getQuery()).connect(SERVER_NAME1); - doReturn(OUTPUT_XML).when(getQuery()).executeCommand(clientMock); - doNothing().when(getQuery()).authenticate(clientMock, "root", PASSWORD); - doNothing().when(getQuery()).validateFingerprint(clientMock, FINGER_PRINT1); - - EXPECTED_MAP.put(SERVER_NAME1, FINGER_PRINT1); - EXPECTED_MAP.put(SERVER_NAME2, FINGER_PRINT1); - doReturn(EXPECTED_MAP).when(getQuery()).extractServers(OUTPUT_XML); } @SuppressWarnings("unchecked") @Test - public void testExecuteQueryCommand() { + public void testQuerySuccess() { + mockQueryParameters(NEW_SERVER, PASSWORD); + getQuery().executeQueryCommand(); + + assertTrue(getQuery().getQueryReturnValue().getSucceeded()); + Map<String, String> serverFingerprintMap = (Map<String, String>) getQuery().getQueryReturnValue().getReturnValue(); assertNotNull(serverFingerprintMap); assertEquals(EXPECTED_MAP, serverFingerprintMap); } + + @Test + public void testQueryFailsIfServerExists() { + mockQueryParameters(EXISTING_SERVER, PASSWORD); + + getQuery().executeQueryCommand(); + + assertFalse(getQuery().getQueryReturnValue().getSucceeded()); + assertEquals(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString(), + getQuery().getQueryReturnValue().getExceptionString()); + } + + @Test + public void testQueryFailsIfPeerExists() { + mockQueryParameters(NEW_SERVER, PASSWORD); + doReturn(getVdsStatic()).when(vdsStaticDao).getByHostName(SERVER_NAME1); + + getQuery().executeQueryCommand(); + + assertFalse(getQuery().getQueryReturnValue().getSucceeded()); + assertEquals(VdcBllMessages.SERVER_ALREADY_EXISTS_IN_ANOTHER_CLUSTER.toString(), + getQuery().getQueryReturnValue().getExceptionString()); + } + + @Test + public void testQueryFailsIfWrongPassword() { + mockQueryParameters(NEW_SERVER, WRONG_PASSWORD); + + getQuery().executeQueryCommand(); + + assertFalse(getQuery().getQueryReturnValue().getSucceeded()); + assertEquals(VdcBllMessages.SSH_AUTHENTICATION_FAILED.toString(), + getQuery().getQueryReturnValue().getExceptionString()); + } } diff --git a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/gluster/GlusterUtil.java b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/gluster/GlusterUtil.java new file mode 100644 index 0000000..66e9483 --- /dev/null +++ b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/gluster/GlusterUtil.java @@ -0,0 +1,207 @@ +package org.ovirt.engine.core.utils.gluster; + +import java.io.ByteArrayOutputStream; +import java.security.AccessControlException; +import java.security.PublicKey; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.naming.AuthenticationException; + +import org.apache.commons.lang.StringUtils; +import org.ovirt.engine.core.common.config.Config; +import org.ovirt.engine.core.common.config.ConfigValues; +import org.ovirt.engine.core.utils.XmlUtils; +import org.ovirt.engine.core.utils.crypt.OpenSSHUtils; +import org.ovirt.engine.core.utils.log.Log; +import org.ovirt.engine.core.utils.log.LogFactory; +import org.ovirt.engine.core.utils.ssh.ConstraintByteArrayOutputStream; +import org.ovirt.engine.core.utils.ssh.SSHClient; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class GlusterUtil { + private static GlusterUtil instance = new GlusterUtil(); + private Log log = LogFactory.getLog(getClass()); + private static final int SSH_PORT = 22; + private static final String ROOT = "root"; + private static final String PEER = "peer"; + private static final String HOST_NAME = "hostname"; + private static final String STATE = "state"; + private static final int PEER_IN_CLUSTER = 3; + + private GlusterUtil() { + + } + + public static GlusterUtil getInstance() { + return instance; + } + + /** + * Fetches gluster peers of the given server + * + * @param server + * Server whose peers are to be fetched + * @param rootPassword + * Root password of the server + * @return Set of peers of the server + * @throws AuthenticationException + * If SSH authentication with given root password fails + */ + public Set<String> getPeers(String server, String rootPassword) throws AuthenticationException { + SSHClient client = null; + + try { + client = connect(server); + authenticate(client, ROOT, rootPassword); + String serversXml = executePeerStatusCommand(client); + return extractServers(serversXml).keySet(); + } finally { + if (client != null) { + client.disconnect(); + } + } + } + + /** + * Fetches gluster peers of the given server + * + * @param server + * Server whose peers are to be fetched + * @param rootPassword + * Root password of the server + * @param fingerprint + * pre-approved fingerprint of the server. This is validated against the server before attempting + * authentication using the root password. + * @return Map of peers of the server with key = peer name and value = SSH fingerprint of the peer + * @throws AuthenticationException + * If SSH authentication with given root password fails + */ + public Map<String, String> getPeers(String server, String rootPassword, String fingerprint) + throws AuthenticationException { + SSHClient client = null; + + try { + client = connect(server); + validateFingerprint(client, fingerprint); + authenticate(client, ROOT, rootPassword); + String serversXml = executePeerStatusCommand(client); + return extractServers(serversXml); + } finally { + if (client != null) { + client.disconnect(); + } + } + } + + // This is required for mock during Junit test + protected SSHClient createSSHClient() { + return new SSHClient(); + } + + protected SSHClient connect(String serverName) { + SSHClient client = createSSHClient(); + Integer timeout = Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds) * 1000; + client.setHardTimeout(timeout); + client.setSoftTimeout(timeout); + client.setHost(serverName, SSH_PORT); + try { + client.connect(); + return client; + } catch (Exception e) { + log.debug(String.format("Could not connect to server %1$s: %2$s", serverName, e.getMessage())); + throw new RuntimeException(e); + } + } + + protected void validateFingerprint(SSHClient client, String fingerprint) { + if (!fingerprint.equals(getFingerprint(client))) { + throw new AccessControlException( + String.format( + "SSH Fingerprint of server '%1$s' did not match expected fingerprint '%2$s'", + client.getDisplayHost(), + fingerprint + )); + } + } + + protected void authenticate(SSHClient client, String userId, String password) throws AuthenticationException { + client.setUser(userId); + client.setPassword(password); + try { + client.authenticate(); + } catch (AuthenticationException e) { + throw e; + } catch (Exception e) { + log.errorFormat("Exception during authentication!", e); + throw new RuntimeException(e); + } + } + + protected String executePeerStatusCommand(SSHClient client) { + ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); + String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); + try { + client.executeCommand(command, null, out, null); + return new String(out.toByteArray(), "UTF-8"); + } catch (Exception e) { + log.errorFormat("Error while executing command {0} on server {1}!", command, client.getHost(), e); + throw new RuntimeException(e); + } + } + + protected String getFingerprint(SSHClient client) { + PublicKey hostKey = client.getHostKey(); + if (hostKey == null) { + log.error("Could not get server key"); + return null; + } + + return OpenSSHUtils.getKeyFingerprintString(hostKey); + } + + public String getFingerprint(String hostName) { + SSHClient client = null; + try { + client = connect(hostName); + return getFingerprint(client); + } finally { + if (client != null) { + client.disconnect(); + } + } + } + + private Map<String, String> getServerFingerprints(NodeList listOfPeers) { + Map<String, String> fingerprints = new HashMap<String, String>(); + for (int i = 0; i < listOfPeers.getLength(); i++) { + Node firstPeer = listOfPeers.item(i); + if (firstPeer.getNodeType() == Node.ELEMENT_NODE) { + Element firstHostElement = (Element) firstPeer; + int state = XmlUtils.getIntValue(firstHostElement, STATE); + // Add the server only if the state is 3 + if (state == PEER_IN_CLUSTER) { + String hostName = XmlUtils.getTextValue(firstHostElement, HOST_NAME); + fingerprints.put(hostName, getFingerprint(hostName)); + } + } + } + return fingerprints; + } + + protected Map<String, String> extractServers(String serversXml) { + if (StringUtils.isEmpty(serversXml)) { + throw new RuntimeException("Could not get the peer list!"); + } + + try { + return getServerFingerprints(XmlUtils.loadXmlDoc(serversXml).getElementsByTagName(PEER)); + } catch (Exception e) { + log.errorFormat("Error while parsing peer list xml [{0}]!", serversXml, e); + throw new RuntimeException(e); + } + } +} diff --git a/backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/gluster/GlusterUtilTest.java b/backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/gluster/GlusterUtilTest.java new file mode 100644 index 0000000..ffcd3f5 --- /dev/null +++ b/backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/gluster/GlusterUtilTest.java @@ -0,0 +1,80 @@ +package org.ovirt.engine.core.utils.gluster; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; + +import java.util.Map; +import java.util.Set; + +import javax.naming.AuthenticationException; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.ovirt.engine.core.utils.ssh.SSHClient; + +@RunWith(MockitoJUnitRunner.class) +public class GlusterUtilTest { + private static final String SERVER_NAME1 = "testserver1"; + private static final String SERVER_NAME2 = "testserver2"; + private static final String USER = "root"; + private static final String PASSWORD = "password"; + private static final String WRONG_PASSWORD = "wrong_password"; + private static final String FINGER_PRINT1 = "31:e2:1b:7e:89:86:99:c3:f7:1e:57:35:fe:9b:5c:31"; + private static final String FINGER_PRINT2 = "31:e2:1b:7e:89:86:99:c3:f7:1e:57:35:fe:9b:5c:32"; + private static final String OUTPUT_XML = + "<cliOutput><peerStatus><peer><uuid>85c42b0d-c2b7-424a-ae72-5174c25da40b</uuid><hostname>testserver1</hostname><connected>1</connected><state>3</state></peer>" + + + "<peer><uuid>85c42b0d-c2b7-424a-ae72-5174c25da40b</uuid><hostname>testserver2</hostname><connected>1</connected><state>3</state></peer></peerStatus></cliOutput>"; + + @Mock + private SSHClient client; + + @Spy + private GlusterUtil glusterUtil; + + @Before + public void setUp() throws Exception { + setupMock(); + } + + private void setupMock() throws AuthenticationException { + doReturn(client).when(glusterUtil).connect(SERVER_NAME1); + doReturn(FINGER_PRINT1).when(glusterUtil).getFingerprint(client); + doReturn(FINGER_PRINT1).when(glusterUtil).getFingerprint(SERVER_NAME1); + doReturn(FINGER_PRINT2).when(glusterUtil).getFingerprint(SERVER_NAME2); + doReturn(OUTPUT_XML).when(glusterUtil).executePeerStatusCommand(client); + doNothing().when(glusterUtil).authenticate(client, USER, PASSWORD); + doThrow(AuthenticationException.class).when(glusterUtil).authenticate(client, USER, WRONG_PASSWORD); + } + + @Test + public void testGetPeersWithFingerprint() throws AuthenticationException { + Map<String, String> peers = glusterUtil.getPeers(SERVER_NAME1, PASSWORD, FINGER_PRINT1); + assertNotNull(peers); + peers.containsKey(SERVER_NAME1); + assertEquals(FINGER_PRINT1, peers.get(SERVER_NAME1)); + peers.containsKey(SERVER_NAME2); + assertEquals(FINGER_PRINT2, peers.get(SERVER_NAME2)); + } + + @Test + public void testGetPeers() throws AuthenticationException { + Set<String> peers = glusterUtil.getPeers(SERVER_NAME1, PASSWORD); + assertNotNull(peers); + assertTrue(peers.contains(SERVER_NAME1)); + assertTrue(peers.contains(SERVER_NAME2)); + } + + @Test(expected = AuthenticationException.class) + public void testGetPeersWithWrongPassword() throws AuthenticationException { + glusterUtil.getPeers(SERVER_NAME1, WRONG_PASSWORD); + } +} -- To view, visit http://gerrit.ovirt.org/13977 To unsubscribe, visit http://gerrit.ovirt.org/settings Gerrit-MessageType: newchange Gerrit-Change-Id: Ib4620c19997c10b202ef5dc5abdbeee9f245937d Gerrit-PatchSet: 1 Gerrit-Project: ovirt-engine Gerrit-Branch: master Gerrit-Owner: Shireesh Anjal <[email protected]> _______________________________________________ Engine-patches mailing list [email protected] http://lists.ovirt.org/mailman/listinfo/engine-patches
