From 74a152df8d76a71e501d0e10659f00bbc7e37b89 Mon Sep 17 00:00:00 2001 From: prachi Date: Thu, 26 Apr 2012 15:08:36 -0700 Subject: [PATCH] - Changes to Configuring hibernate to connect to multiple databases: cloudbridge and cloudstack - This avoids making multiple API calls just to list ServiceOfferings --- awsapi/.classpath | 8 + awsapi/conf/CloudStack.cfg.xml | 28 +++ .../com/cloud/bridge/persist/EntityDao.java | 28 +-- .../cloud/bridge/persist/PersistContext.java | 149 +++++++++++----- .../dao/CloudStackConfigurationDao.java | 41 +++++ .../bridge/persist/dao/CloudStackDao.java | 80 --------- .../persist/dao/CloudStackSvcOfferingDao.java | 41 +++++ .../persist/dao/UserCredentialsDao.java | 164 +++--------------- .../cloud/bridge/service/EC2MainServlet.java | 6 +- .../bridge/service/core/ec2/EC2Engine.java | 42 ++--- .../bridge/util/CloudStackSessionFactory.java | 109 ++++++++++++ .../models/CloudStackConfiguration.hbm.xml | 19 ++ .../stack/models/CloudStackConfiguration.java | 56 ++++++ .../models/CloudStackServiceOffering.hbm.xml | 16 ++ .../models/CloudStackServiceOffering.java | 18 +- deps/.classpath | 115 ++++++------ 16 files changed, 566 insertions(+), 354 deletions(-) create mode 100644 awsapi/.classpath create mode 100644 awsapi/conf/CloudStack.cfg.xml create mode 100644 awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDao.java delete mode 100644 awsapi/src/com/cloud/bridge/persist/dao/CloudStackDao.java create mode 100644 awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDao.java create mode 100644 awsapi/src/com/cloud/bridge/util/CloudStackSessionFactory.java create mode 100644 awsapi/src/com/cloud/stack/models/CloudStackConfiguration.hbm.xml create mode 100644 awsapi/src/com/cloud/stack/models/CloudStackConfiguration.java create mode 100644 awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.hbm.xml diff --git a/awsapi/.classpath b/awsapi/.classpath new file mode 100644 index 00000000000..9dce8941421 --- /dev/null +++ b/awsapi/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/awsapi/conf/CloudStack.cfg.xml b/awsapi/conf/CloudStack.cfg.xml new file mode 100644 index 00000000000..d34d2f55367 --- /dev/null +++ b/awsapi/conf/CloudStack.cfg.xml @@ -0,0 +1,28 @@ + + + + + + com.mysql.jdbc.Driver + 20 + false + + + 2 + + update + true + org.hibernate.dialect.MySQLDialect + + true + + + + + + + + diff --git a/awsapi/src/com/cloud/bridge/persist/EntityDao.java b/awsapi/src/com/cloud/bridge/persist/EntityDao.java index 0bab9ea6e86..ba19cceb5fd 100644 --- a/awsapi/src/com/cloud/bridge/persist/EntityDao.java +++ b/awsapi/src/com/cloud/bridge/persist/EntityDao.java @@ -29,38 +29,44 @@ import com.cloud.bridge.util.QueryHelper; public class EntityDao { private Class clazz; - public EntityDao(Class clazz) { + private boolean isCloudStackSession = false; + + public EntityDao(Class clazz){ + this(clazz, false); + } + + public EntityDao(Class clazz, boolean isCloudStackSession) { this.clazz = clazz; - + this.isCloudStackSession = isCloudStackSession; // Note : beginTransaction can be called multiple times - PersistContext.beginTransaction(); + PersistContext.beginTransaction(isCloudStackSession); } @SuppressWarnings("unchecked") public T get(Serializable id) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); return (T)session.get(clazz, id); } public T save(T entity) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); session.saveOrUpdate(entity); return entity; } public T update(T entity) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); session.saveOrUpdate(entity); return entity; } public void delete(T entity) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); session.delete(entity); } public T queryEntity(String hql, Object[] params) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); Query query = session.createQuery(hql); query.setMaxResults(1); QueryHelper.bindParameters(query, params); @@ -68,7 +74,7 @@ public class EntityDao { } public List queryEntities(String hql, Object[] params) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); Query query = session.createQuery(hql); QueryHelper.bindParameters(query, params); @@ -76,7 +82,7 @@ public class EntityDao { } public List queryEntities(String hql, int offset, int limit, Object[] params) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); Query query = session.createQuery(hql); QueryHelper.bindParameters(query, params); query.setFirstResult(offset); @@ -85,7 +91,7 @@ public class EntityDao { } public int executeUpdate(String hql, Object[] params) { - Session session = PersistContext.getSession(); + Session session = PersistContext.getSession(isCloudStackSession); Query query = session.createQuery(hql); QueryHelper.bindParameters(query, params); diff --git a/awsapi/src/com/cloud/bridge/persist/PersistContext.java b/awsapi/src/com/cloud/bridge/persist/PersistContext.java index 81001b32a8f..e721a1ddd2f 100644 --- a/awsapi/src/com/cloud/bridge/persist/PersistContext.java +++ b/awsapi/src/com/cloud/bridge/persist/PersistContext.java @@ -28,6 +28,7 @@ import org.hibernate.Session; import org.hibernate.Transaction; import com.cloud.bridge.util.CloudSessionFactory; +import com.cloud.bridge.util.CloudStackSessionFactory; import com.cloud.bridge.util.Tuple; /** @@ -48,78 +49,144 @@ public class PersistContext { protected final static Logger logger = Logger.getLogger(PersistContext.class); private static final CloudSessionFactory sessionFactory; - + private static final ThreadLocal threadSession = new ThreadLocal(); private static final ThreadLocal threadTransaction = new ThreadLocal(); private static final ThreadLocal> threadStore = new ThreadLocal>(); + private static final CloudStackSessionFactory cloudStackSessionFactory; + private static final ThreadLocal threadCloudStackSession = new ThreadLocal(); + private static final ThreadLocal threadCloudStackTransaction = new ThreadLocal(); + static { try { sessionFactory = CloudSessionFactory.getInstance(); + cloudStackSessionFactory = CloudStackSessionFactory.getInstance(); } catch(HibernateException e) { logger.error("Exception " + e.getMessage(), e); throw new PersistException(e); } } + public static Session getSession(boolean cloudStackSession) { + Session s = null; + try { + if(cloudStackSession){ + s = threadCloudStackSession.get(); + if(s == null) { + s = cloudStackSessionFactory.openSession(); + threadCloudStackSession.set(s); + } + }else{ + s = threadSession.get(); + if(s == null) { + s = sessionFactory.openSession(); + threadSession.set(s); + } + } + } catch(HibernateException e) { + logger.error("Exception " + e.getMessage(), e); + throw new PersistException(e); + } + return s; + } + public static Session getSession() { - Session s = threadSession.get(); - try { - if(s == null) { - s = sessionFactory.openSession(); - threadSession.set(s); - } - } catch(HibernateException e) { - logger.error("Exception " + e.getMessage(), e); - throw new PersistException(e); - } - return s; + return getSession(false); } public static void closeSession() { + closeSession(false); + } + + public static void closeSession(boolean cloudStackSession) { + try { + if(cloudStackSession){ + Session s = (Session) threadCloudStackSession.get(); + threadCloudStackSession.set(null); + if (s != null && s.isOpen()) + s.close(); + }else{ + Session s = (Session) threadSession.get(); + threadSession.set(null); + + if (s != null && s.isOpen()) + s.close(); + } + }catch(HibernateException e) { + logger.error("Exception " + e.getMessage(), e); + throw new PersistException(e); + } + } + + public static void beginTransaction(boolean cloudStackTxn) { + Transaction tx = null; try { - Session s = (Session) threadSession.get(); - threadSession.set(null); - - if (s != null && s.isOpen()) - s.close(); + if(cloudStackTxn){ + tx = threadCloudStackTransaction.get(); + }else{ + tx = threadTransaction.get(); + } + + if (tx == null) { + tx = getSession(cloudStackTxn).beginTransaction(); + if(cloudStackTxn){ + threadCloudStackTransaction.set(tx); + }else{ + threadTransaction.set(tx); + } + } } catch(HibernateException e) { logger.error("Exception " + e.getMessage(), e); throw new PersistException(e); } } - + public static void beginTransaction() { - Transaction tx = threadTransaction.get(); - try { - if (tx == null) { - tx = getSession().beginTransaction(); - threadTransaction.set(tx); + beginTransaction(false); + } + + public static void commitTransaction(boolean cloudStackTxn) { + Transaction tx = null; + + if(cloudStackTxn){ + tx = threadCloudStackTransaction.get(); + }else{ + tx = threadTransaction.get(); + } + + try { + if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ){ + tx.commit(); } - } catch(HibernateException e) { + if(cloudStackTxn){ + threadCloudStackTransaction.set(null); + }else{ + threadTransaction.set(null); + } + } catch (HibernateException e) { logger.error("Exception " + e.getMessage(), e); + + rollbackTransaction(cloudStackTxn); throw new PersistException(e); } } public static void commitTransaction() { - Transaction tx = threadTransaction.get(); - try { - if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) - tx.commit(); - threadTransaction.set(null); - } catch (HibernateException e) { - logger.error("Exception " + e.getMessage(), e); - - rollbackTransaction(); - throw new PersistException(e); - } + commitTransaction(false); } - public static void rollbackTransaction() { - Transaction tx = (Transaction) threadTransaction.get(); + public static void rollbackTransaction(boolean cloudStackTxn) { + Transaction tx = null; + + if(cloudStackTxn){ + tx = (Transaction)threadCloudStackTransaction.get(); + threadCloudStackTransaction.set(null); + }else{ + tx = (Transaction)threadTransaction.get(); + threadTransaction.set(null); + } try { - threadTransaction.set(null); if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { tx.rollback(); } @@ -127,10 +194,14 @@ public class PersistContext { logger.error("Exception " + e.getMessage(), e); throw new PersistException(e); } finally { - closeSession(); + closeSession(cloudStackTxn); } } + public static void rollbackTransaction() { + rollbackTransaction(false); + } + public static void flush() { commitTransaction(); beginTransaction(); diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDao.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDao.java new file mode 100644 index 00000000000..65af77aea61 --- /dev/null +++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDao.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.cloud.bridge.persist.dao; + +import org.apache.log4j.Logger; + +import com.cloud.bridge.persist.EntityDao; +import com.cloud.stack.models.CloudStackConfiguration; + + +public class CloudStackConfigurationDao extends EntityDao { + public static final Logger logger = Logger.getLogger(CloudStackConfigurationDao.class); + + public CloudStackConfigurationDao() { + super(CloudStackConfiguration.class, true); + } + + + public String getConfigValue( String configName ){ + CloudStackConfiguration config = queryEntity("from CloudStackConfiguration where name=?", new Object[] {configName}); + if(config != null){ + return config.getValue(); + } + return null; + } + + +} diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackDao.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackDao.java deleted file mode 100644 index 81f4ceb4678..00000000000 --- a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackDao.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.cloud.bridge.persist.dao; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Properties; - -import org.apache.log4j.Logger; - -import com.cloud.bridge.util.ConfigurationHelper; - - -public class CloudStackDao extends BaseDao { - public static final Logger logger = Logger.getLogger(CloudStackDao.class); - - private Connection conn = null; - - public CloudStackDao() { - } - - - public String getConfigValue( String configName ){ - String value = null; - try { - openConnection(); - PreparedStatement statement = conn.prepareStatement ( "SELECT value FROM `cloud`.`configuration` where name = ?" ); - statement.setString( 1, configName ); - statement.executeQuery(); - ResultSet rs = statement.getResultSet (); - if (rs.next()) { - value = rs.getString(1); - } - - }catch (Exception e) { - logger.warn("Failed to access CloudStack DB, got error: ", e); - } finally { - try{ - closeConnection(); - }catch(SQLException e){ - - } - } - return value; - } - - private void openConnection() - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - if (null == conn) { - Class.forName( "com.mysql.jdbc.Driver" ).newInstance(); - conn = DriverManager.getConnection( "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + cloud_dbName, dbUser, dbPassword ); - } - } - - private void closeConnection() throws SQLException { - if (null != conn) conn.close(); - conn = null; - } - -} diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDao.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDao.java new file mode 100644 index 00000000000..96c6ec721e7 --- /dev/null +++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDao.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.cloud.bridge.persist.dao; + +import org.apache.log4j.Logger; + +import com.cloud.bridge.persist.EntityDao; +import com.cloud.stack.models.CloudStackConfiguration; +import com.cloud.stack.models.CloudStackServiceOffering; + + +public class CloudStackSvcOfferingDao extends EntityDao { + public static final Logger logger = Logger.getLogger(CloudStackSvcOfferingDao.class); + + public CloudStackSvcOfferingDao() { + super(CloudStackServiceOffering.class, true); + } + + + public CloudStackServiceOffering getSvcOfferingByName( String name ){ + return queryEntity("from CloudStackServiceOffering where name=?", new Object[] {name}); + } + + public CloudStackServiceOffering getSvcOfferingById( String id ){ + return queryEntity("from CloudStackServiceOffering where id=?", new Object[] {id}); + } + +} diff --git a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java index 02c6607ac96..f4ba3d1d565 100644 --- a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java +++ b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java @@ -15,165 +15,51 @@ */ package com.cloud.bridge.persist.dao; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - import org.apache.log4j.Logger; import com.cloud.bridge.model.UserCredentials; +import com.cloud.bridge.persist.EntityDao; import com.cloud.bridge.service.exception.NoSuchObjectException; -public class UserCredentialsDao extends BaseDao{ +public class UserCredentialsDao extends EntityDao{ public static final Logger logger = Logger.getLogger(UserCredentialsDao.class); - private Connection conn = null; - public UserCredentialsDao() { + super(UserCredentials.class); } - public void setUserKeys( String cloudAccessKey, String cloudSecretKey ) - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { + public void setUserKeys( String cloudAccessKey, String cloudSecretKey ){ UserCredentials user = getByAccessKey( cloudAccessKey ); - PreparedStatement statement = null; - - openConnection(); - try { - if ( null == user ) { - // -> do an insert since the user does not exist yet - statement = conn.prepareStatement ( "INSERT INTO usercredentials (AccessKey, SecretKey) VALUES(?,?)" ); - statement.setString( 1, cloudAccessKey ); - statement.setString( 2, cloudSecretKey ); - } - else { - // -> do an update since the user exists - statement = conn.prepareStatement ( "UPDATE usercredentials SET SecretKey=? WHERE AccessKey=?" ); - statement.setString( 1, cloudSecretKey ); - statement.setString( 2, cloudAccessKey ); - } - int count = statement.executeUpdate(); - statement.close(); - - } finally { - closeConnection(); - } + if ( null == user ) { + // -> do an insert since the user does not exist yet + user = new UserCredentials(); + user.setAccessKey(cloudAccessKey); + user.setSecretKey(cloudSecretKey); + save(user); + } + else { + // -> do an update since the user exists + user.setAccessKey(cloudAccessKey); + user.setSecretKey(cloudSecretKey); + update(user); + } } - public void setCertificateId( String cloudAccessKey, String certId ) - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { + public void setCertificateId( String cloudAccessKey, String certId ){ UserCredentials user = getByAccessKey( cloudAccessKey ); - PreparedStatement statement = null; - if (null == user) throw new NoSuchObjectException( "Cloud API Access Key [" + cloudAccessKey + "] is unknown" ); - - openConnection(); - try { - statement = conn.prepareStatement ( "UPDATE usercredentials SET CertUniqueId=? WHERE AccessKey=?" ); - statement.setString( 1, certId ); - statement.setString( 2, cloudAccessKey ); - int count = statement.executeUpdate(); - statement.close(); - - } finally { - closeConnection(); - } + user.setCertUniqueId(certId); + update(user); } - public UserCredentials getByAccessKey( String cloudAccessKey ) - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - openConnection(); - - UserCredentials user = null; - - try { - PreparedStatement statement = conn.prepareStatement ( "SELECT SecretKey, CertUniqueId FROM usercredentials WHERE AccessKey=?" ); - statement.setString( 1, cloudAccessKey ); - statement.executeQuery(); - ResultSet rs = statement.getResultSet (); - if (rs.next()) { - user = new UserCredentials(); - user.setAccessKey( cloudAccessKey ); - user.setSecretKey( rs.getString( "SecretKey" )); - user.setCertUniqueId( rs.getString( "CertUniqueId" )); - } - - } finally { - closeConnection(); - } - return user; - } - - public UserCredentials getByCertUniqueId( String certId ) - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - openConnection(); - - UserCredentials user = null; - - try { - PreparedStatement statement = conn.prepareStatement ( "SELECT AccessKey, SecretKey FROM usercredentials WHERE CertUniqueId=?" ); - statement.setString( 1, certId ); - statement.executeQuery(); - ResultSet rs = statement.getResultSet (); - if (rs.next()) { - user = new UserCredentials(); - user.setAccessKey( rs.getString( "AccessKey" )); - user.setSecretKey( rs.getString( "SecretKey" )); - user.setCertUniqueId( certId ); - } - - } finally { - closeConnection(); - } - return user; + public UserCredentials getByAccessKey( String cloudAccessKey ){ + return queryEntity("FROM UserCredentials WHERE AccessKey=?", new Object[] {cloudAccessKey}); } - private void openConnection() - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - if (null == conn) { - Class.forName( "com.mysql.jdbc.Driver" ).newInstance(); - conn = DriverManager.getConnection( "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + awsapi_dbName, dbUser, dbPassword ); - } - } - - private void closeConnection() throws SQLException { - if (null != conn) conn.close(); - conn = null; - } - - public static void preCheckTableExistence() { - UserCredentialsDao dao = new UserCredentialsDao(); - try { - dao.checkTableExistence(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void checkTableExistence() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - openConnection(); - - try { - PreparedStatement statement = conn.prepareStatement ( "SELECT * FROM usercredentials " ); - statement.executeQuery(); - ResultSet rs = statement.getResultSet (); - if (rs.next()) { - return; - } - return; - - } catch(Exception e) { - Statement statement = conn.createStatement(); - statement.execute( "create table usercredentials(id integer auto_increment primary key, AccessKey varchar(1000), SecretKey varchar(1000), CertUniqueId varchar(1000))" ); - statement.close(); - } - finally{ - closeConnection(); - } - } + public UserCredentials getByCertUniqueId( String certId ){ + return queryEntity("FROM UserCredentials WHERE CertUniqueId=?", new Object[] {certId}); + } } diff --git a/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java b/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java index 86489125d63..3e23fcd5ac5 100644 --- a/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java +++ b/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java @@ -9,7 +9,7 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import com.cloud.bridge.persist.dao.CloudStackDao; +import com.cloud.bridge.persist.dao.CloudStackConfigurationDao; import com.cloud.bridge.persist.dao.UserCredentialsDao; import com.cloud.bridge.util.ConfigurationHelper; @@ -28,10 +28,8 @@ public class EC2MainServlet extends HttpServlet{ */ public void init( ServletConfig config ) throws ServletException { ConfigurationHelper.preConfigureConfigPathFromServletContext(config.getServletContext()); - UserCredentialsDao.preCheckTableExistence(); // check if API is enabled - - CloudStackDao csDao = new CloudStackDao(); + CloudStackConfigurationDao csDao = new CloudStackConfigurationDao(); String value = csDao.getConfigValue(ENABLE_EC2_API); if(value != null){ isEC2APIEnabled = Boolean.valueOf(value); diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java index 53d50732c13..80e9bc74217 100644 --- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java +++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java @@ -33,6 +33,7 @@ import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.xml.sax.SAXException; +import com.cloud.bridge.persist.dao.CloudStackSvcOfferingDao; import com.cloud.bridge.persist.dao.OfferingDao; import com.cloud.bridge.service.UserContext; import com.cloud.bridge.service.exception.EC2ServiceException; @@ -1560,30 +1561,19 @@ public class EC2Engine { /** - * + * Convert from the Amazon instanceType strings to Cloud serviceOfferingId + * */ - private CloudStackServiceOffering getCSServiceOfferingId(String instanceType) throws Exception{ + private CloudStackServiceOffering getCSServiceOfferingId(String instanceType){ try { if (null == instanceType) instanceType = "m1.small"; - - List svcOfferings = getApi().listServiceOfferings(null, null, null, null, null, - null, null); - if(svcOfferings == null || svcOfferings.isEmpty()){ - logger.debug("No ServiceOffering found to be defined by name: "+instanceType ); - return null; - } + CloudStackSvcOfferingDao dao = new CloudStackSvcOfferingDao(); + return dao.getSvcOfferingByName(instanceType); - for(CloudStackServiceOffering offering : svcOfferings){ - if(instanceType.equalsIgnoreCase(offering.getName())){ - return offering; - } - } - - return null; } catch(Exception e) { - logger.error( "listServiceOfferings - ", e); + logger.error( "Error while retrieving ServiceOffering information by name - ", e); throw new EC2ServiceException(ServerError.InternalError, e.getMessage()); } } @@ -1596,22 +1586,18 @@ public class EC2Engine { * @return A valid value for the Amazon defined instanceType * @throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException */ - private String serviceOfferingIdToInstanceType( String serviceOfferingId ) - throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { - + private String serviceOfferingIdToInstanceType( String serviceOfferingId ){ try{ - List svcOfferings = getApi().listServiceOfferings(null, serviceOfferingId, null, null, null, - null, null); - - if(svcOfferings == null || svcOfferings.isEmpty()){ - logger.warn( "No instanceType match for serverOfferingId: [" + serviceOfferingId + "]" ); + CloudStackSvcOfferingDao dao = new CloudStackSvcOfferingDao(); + CloudStackServiceOffering offering = dao.getSvcOfferingById(serviceOfferingId); + if(offering == null){ + logger.warn( "No instanceType match for serviceOfferingId: [" + serviceOfferingId + "]" ); return "m1.small"; } - - else return svcOfferings.get(0).getName(); + return offering.getName(); } catch(Exception e) { - logger.error( "serviceOfferingIdToInstanceType - ", e); + logger.error( "sError while retrieving ServiceOffering information by id - ", e); throw new EC2ServiceException(ServerError.InternalError, e.getMessage()); } } diff --git a/awsapi/src/com/cloud/bridge/util/CloudStackSessionFactory.java b/awsapi/src/com/cloud/bridge/util/CloudStackSessionFactory.java new file mode 100644 index 00000000000..13f8fedbf2d --- /dev/null +++ b/awsapi/src/com/cloud/bridge/util/CloudStackSessionFactory.java @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2011 Citrix Systems, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.cloud.bridge.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Properties; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; +import org.jasypt.properties.EncryptableProperties; +import org.apache.log4j.Logger; + + +/** + * @author Kelven Yang + */ +public class CloudStackSessionFactory { + private static CloudStackSessionFactory instance; + public static final Logger logger = Logger.getLogger(CloudStackSessionFactory.class); + + private SessionFactory factory; + + private CloudStackSessionFactory() { + Configuration cfg = new Configuration(); + File file = ConfigurationHelper.findConfigurationFile("CloudStack.cfg.xml"); + + File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties"); + Properties dbProp = null; + String dbName = null; + String dbHost = null; + String dbUser = null; + String dbPassword = null; + String dbPort = null; + + if (null != propertiesFile) { + + if(EncryptionSecretKeyCheckerUtil.useEncryption()){ + StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor(); + dbProp = new EncryptableProperties(encryptor); + } else { + dbProp = new Properties(); + } + + try { + dbProp.load( new FileInputStream( propertiesFile )); + } catch (FileNotFoundException e) { + logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); + } catch (IOException e) { + logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); + } + } + + + // + // we are packaging hibernate mapping files along with the class files, + // make sure class loader use the same class path when initializing hibernate mapping. + // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner) + // + if(file != null && dbProp != null){ + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + cfg.configure(file); + + dbHost = dbProp.getProperty( "db.cloud.host" ); + dbName = dbProp.getProperty( "db.cloud.name" ); + dbUser = dbProp.getProperty( "db.cloud.username" ); + dbPassword = dbProp.getProperty( "db.cloud.password" ); + dbPort = dbProp.getProperty( "db.cloud.port" ); + + cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName); + cfg.setProperty("hibernate.connection.username", dbUser); + cfg.setProperty("hibernate.connection.password", dbPassword); + + + factory = cfg.buildSessionFactory(); + }else{ + logger.warn("Unable to open load db configuration"); + throw new RuntimeException("nable to open load db configuration"); + } + } + + public synchronized static CloudStackSessionFactory getInstance() { + if(instance == null) { + instance = new CloudStackSessionFactory(); + } + return instance; + } + + public Session openSession() { + return factory.openSession(); + } +} diff --git a/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.hbm.xml b/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.hbm.xml new file mode 100644 index 00000000000..e644eb0da56 --- /dev/null +++ b/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.hbm.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.java b/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.java new file mode 100644 index 00000000000..99237f4c70e --- /dev/null +++ b/awsapi/src/com/cloud/stack/models/CloudStackConfiguration.java @@ -0,0 +1,56 @@ +package com.cloud.stack.models; + +import java.io.Serializable; + +import com.google.gson.annotations.SerializedName; + +public class CloudStackConfiguration implements Serializable { + + private static final long serialVersionUID = 1L; + + @SerializedName(ApiConstants.CATEGORY) + private String category; + + @SerializedName(ApiConstants.NAME) + private String name; + + @SerializedName(ApiConstants.VALUE) + private String value; + + @SerializedName(ApiConstants.DESCRIPTION) + private String description; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + +} diff --git a/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.hbm.xml b/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.hbm.xml new file mode 100644 index 00000000000..f3c5d4d17f3 --- /dev/null +++ b/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.hbm.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.java b/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.java index 0b6f87622a4..5b2e5028179 100644 --- a/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.java +++ b/awsapi/src/com/cloud/stack/models/CloudStackServiceOffering.java @@ -49,7 +49,7 @@ public class CloudStackServiceOffering { private Long memory; @SerializedName(ApiConstants.NAME) private String name; - @SerializedName(ApiConstants.OFFER_HA) + @SerializedName(ApiConstants.OFFER_HA) private Boolean offerHa; @SerializedName(ApiConstants.STORAGE_TYPE) private String storageType; @@ -72,6 +72,10 @@ public class CloudStackServiceOffering { return id; } + public void setId(String id) { + this.id = id; + } + /** * @return the cpuNumber */ @@ -121,7 +125,11 @@ public class CloudStackServiceOffering { return domainId; } - /** + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + /** * @return the hostTags */ public String getHostTags() { @@ -155,7 +163,11 @@ public class CloudStackServiceOffering { public String getName() { return name; } - + + public void setName(String name) { + this.name = name; + } + /** * @return the offerHa */ diff --git a/deps/.classpath b/deps/.classpath index b9eb504b959..f704a0575c8 100755 --- a/deps/.classpath +++ b/deps/.classpath @@ -1,50 +1,65 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +