diff --git a/core/src/com/cloud/agent/IAgentControl.java b/core/src/com/cloud/agent/IAgentControl.java index 3b0380a4458..bb68d98a96d 100644 --- a/core/src/com/cloud/agent/IAgentControl.java +++ b/core/src/com/cloud/agent/IAgentControl.java @@ -10,17 +10,17 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent; - - +package com.cloud.agent; + + import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.AgentControlCommand; import com.cloud.exception.AgentControlChannelException; - -public interface IAgentControl { - void registerControlListener(IAgentControlListener listener); - void unregisterControlListener(IAgentControlListener listener); - - AgentControlAnswer sendRequest(AgentControlCommand cmd, int timeoutInMilliseconds) throws AgentControlChannelException; - void postRequest(AgentControlCommand cmd) throws AgentControlChannelException; -} + +public interface IAgentControl { + void registerControlListener(IAgentControlListener listener); + void unregisterControlListener(IAgentControlListener listener); + + AgentControlAnswer sendRequest(AgentControlCommand cmd, int timeoutInMilliseconds) throws AgentControlChannelException; + void postRequest(AgentControlCommand cmd) throws AgentControlChannelException; +} diff --git a/core/src/com/cloud/agent/IAgentControlListener.java b/core/src/com/cloud/agent/IAgentControlListener.java index efe5878c93c..775eff71437 100644 --- a/core/src/com/cloud/agent/IAgentControlListener.java +++ b/core/src/com/cloud/agent/IAgentControlListener.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.agent; - +package com.cloud.agent; + import com.cloud.agent.api.AgentControlAnswer; import com.cloud.agent.api.AgentControlCommand; import com.cloud.agent.api.Answer; import com.cloud.agent.transport.Request; import com.cloud.agent.transport.Response; - -public interface IAgentControlListener { - public Answer processControlRequest(Request request, AgentControlCommand cmd); - public void processControlResponse(Response response, AgentControlAnswer answer); -} + +public interface IAgentControlListener { + public Answer processControlRequest(Request request, AgentControlCommand cmd); + public void processControlResponse(Response response, AgentControlAnswer answer); +} diff --git a/core/src/com/cloud/alert/AlertAdapter.java b/core/src/com/cloud/alert/AlertAdapter.java index 9d706c61aeb..040f346c240 100644 --- a/core/src/com/cloud/alert/AlertAdapter.java +++ b/core/src/com/cloud/alert/AlertAdapter.java @@ -10,9 +10,9 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert; - +package com.cloud.alert; + import com.cloud.utils.component.Adapter; - -public interface AlertAdapter extends Adapter { -} + +public interface AlertAdapter extends Adapter { +} diff --git a/core/src/com/cloud/alert/AlertVO.java b/core/src/com/cloud/alert/AlertVO.java index 11aad6b8421..546d2145721 100755 --- a/core/src/com/cloud/alert/AlertVO.java +++ b/core/src/com/cloud/alert/AlertVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.alert; - +package com.cloud.alert; + import java.util.Date; import java.util.UUID; @@ -26,77 +26,77 @@ import javax.persistence.TemporalType; import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="alert") -public class AlertVO implements Alert, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="type") + +@Entity +@Table(name="alert") +public class AlertVO implements Alert, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="type") private short type; - + @Column(name="cluster_id") private Long clusterId = null; - - @Column(name="pod_id") - private Long podId = null; - - @Column(name="data_center_id") - private long dataCenterId = 0; - - @Column(name="subject", length=999) - private String subject; - - @Column(name="sent_count") - private int sentCount = 0; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="last_sent", updatable=true, nullable=true) - private Date lastSent; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="resolved", updatable=true, nullable=true) + + @Column(name="pod_id") + private Long podId = null; + + @Column(name="data_center_id") + private long dataCenterId = 0; + + @Column(name="subject", length=999) + private String subject; + + @Column(name="sent_count") + private int sentCount = 0; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="last_sent", updatable=true, nullable=true) + private Date lastSent; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="resolved", updatable=true, nullable=true) private Date resolved; @Column(name="uuid") private String uuid; - + public AlertVO() { this.uuid = UUID.randomUUID().toString(); - } - public AlertVO(Long id) { - this.id = id; + } + public AlertVO(Long id) { + this.id = id; this.uuid = UUID.randomUUID().toString(); - } - + } + @Override - public long getId() { - return id; - } + public long getId() { + return id; + } @Override - public short getType() { - return type; - } - - public void setType(short type) { - this.type = type; - } - + public short getType() { + return type; + } + + public void setType(short type) { + this.type = type; + } + @Override - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + public Long getClusterId() { return clusterId; } @@ -104,57 +104,57 @@ public class AlertVO implements Alert, Identity { this.clusterId = clusterId; } @Override - public Long getPodId() { - return podId; - } - - public void setPodId(Long podId) { - this.podId = podId; - } - + public Long getPodId() { + return podId; + } + + public void setPodId(Long podId) { + this.podId = podId; + } + @Override - public long getDataCenterId() { - return dataCenterId; - } - - public void setDataCenterId(long dataCenterId) { - this.dataCenterId = dataCenterId; - } - + public long getDataCenterId() { + return dataCenterId; + } + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + @Override - public int getSentCount() { - return sentCount; - } - - public void setSentCount(int sentCount) { - this.sentCount = sentCount; - } - + public int getSentCount() { + return sentCount; + } + + public void setSentCount(int sentCount) { + this.sentCount = sentCount; + } + @Override - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + @Override - public Date getLastSent() { - return lastSent; - } - - public void setLastSent(Date lastSent) { - this.lastSent = lastSent; - } - + public Date getLastSent() { + return lastSent; + } + + public void setLastSent(Date lastSent) { + this.lastSent = lastSent; + } + @Override - public Date getResolved() { - return resolved; - } - - public void setResolved(Date resolved) { - this.resolved = resolved; + public Date getResolved() { + return resolved; + } + + public void setResolved(Date resolved) { + this.resolved = resolved; } @Override @@ -164,5 +164,5 @@ public class AlertVO implements Alert, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} + } +} diff --git a/core/src/com/cloud/async/AsyncJobVO.java b/core/src/com/cloud/async/AsyncJobVO.java index 48bb8cb71d2..b7a33f30c58 100644 --- a/core/src/com/cloud/async/AsyncJobVO.java +++ b/core/src/com/cloud/async/AsyncJobVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - +package com.cloud.async; + import java.util.Date; import java.util.UUID; @@ -28,82 +28,82 @@ import javax.persistence.TemporalType; import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="async_job") -public class AsyncJobVO implements AsyncJob { - public static final int CALLBACK_POLLING = 0; - public static final int CALLBACK_EMAIL = 1; - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id = null; - - @Column(name="user_id") - private long userId; - - @Column(name="account_id") - private long accountId; - - @Column(name="session_key") - private String sessionKey; - - @Column(name="job_cmd") - private String cmd; - - @Column(name="job_cmd_originator") - private String cmdOriginator; - - @Column(name="job_cmd_ver") - private int cmdVersion; - - @Column(name="job_cmd_info", length=65535) - private String cmdInfo; - - @Column(name="callback_type") - private int callbackType; - - @Column(name="callback_address") - private String callbackAddress; - - @Column(name="job_status") - private int status; - - @Column(name="job_process_status") - private int processStatus; - - @Column(name="job_result_code") - private int resultCode; - - @Column(name="job_result", length=65535) - private String result; + +@Entity +@Table(name="async_job") +public class AsyncJobVO implements AsyncJob { + public static final int CALLBACK_POLLING = 0; + public static final int CALLBACK_EMAIL = 1; + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id = null; + + @Column(name="user_id") + private long userId; - @Enumerated(value=EnumType.STRING) - @Column(name="instance_type", length=64) - private Type instanceType; - - @Column(name="instance_id", length=64) - private Long instanceId; - - @Column(name="job_init_msid") - private Long initMsid; - - @Column(name="job_complete_msid") - private Long completeMsid; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - @Column(name="last_updated") - @Temporal(TemporalType.TIMESTAMP) - private Date lastUpdated; - - @Column(name="last_polled") - @Temporal(TemporalType.TIMESTAMP) - private Date lastPolled; - - @Column(name=GenericDao.REMOVED_COLUMN) + @Column(name="account_id") + private long accountId; + + @Column(name="session_key") + private String sessionKey; + + @Column(name="job_cmd") + private String cmd; + + @Column(name="job_cmd_originator") + private String cmdOriginator; + + @Column(name="job_cmd_ver") + private int cmdVersion; + + @Column(name="job_cmd_info", length=65535) + private String cmdInfo; + + @Column(name="callback_type") + private int callbackType; + + @Column(name="callback_address") + private String callbackAddress; + + @Column(name="job_status") + private int status; + + @Column(name="job_process_status") + private int processStatus; + + @Column(name="job_result_code") + private int resultCode; + + @Column(name="job_result", length=65535) + private String result; + + @Enumerated(value=EnumType.STRING) + @Column(name="instance_type", length=64) + private Type instanceType; + + @Column(name="instance_id", length=64) + private Long instanceId; + + @Column(name="job_init_msid") + private Long initMsid; + + @Column(name="job_complete_msid") + private Long completeMsid; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name="last_updated") + @Temporal(TemporalType.TIMESTAMP) + private Date lastUpdated; + + @Column(name="last_polled") + @Temporal(TemporalType.TIMESTAMP) + private Date lastPolled; + + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @Column(name="uuid") @@ -114,228 +114,228 @@ public class AsyncJobVO implements AsyncJob { @Transient private boolean fromPreviousSession = false; - - public AsyncJobVO() { + + public AsyncJobVO() { this.uuid = UUID.randomUUID().toString(); - } - - public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo) { - this.userId = userId; - this.accountId = accountId; - this.cmd = cmd; - this.cmdInfo = cmdInfo; + } + + public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo) { + this.userId = userId; + this.accountId = accountId; + this.cmd = cmd; + this.cmdInfo = cmdInfo; this.callbackType = CALLBACK_POLLING; - this.uuid = UUID.randomUUID().toString(); - } - - public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo, - int callbackType, String callbackAddress) { - - this(userId, accountId, cmd, cmdInfo); - this.callbackType = callbackType; - this.callbackAddress = callbackAddress; this.uuid = UUID.randomUUID().toString(); - } - + } + + public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo, + int callbackType, String callbackAddress) { + + this(userId, accountId, cmd, cmdInfo); + this.callbackType = callbackType; + this.callbackAddress = callbackAddress; + this.uuid = UUID.randomUUID().toString(); + } + @Override - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + @Override - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } - + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + @Override - public long getAccountId() { - return accountId; - } - - public void setAccountId(long accountId) { - this.accountId = accountId; - } - + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + @Override - public String getCmd() { - return cmd; - } - - public void setCmd(String cmd) { - this.cmd = cmd; - } - - @Override - public int getCmdVersion() { - return cmdVersion; - } - - public void setCmdVersion(int version) { - cmdVersion = version; - } - - @Override - public String getCmdInfo() { - return cmdInfo; - } - - public void setCmdInfo(String cmdInfo) { - this.cmdInfo = cmdInfo; - } - - @Override - public int getCallbackType() { - return callbackType; - } - - public void setCallbackType(int callbackType) { - this.callbackType = callbackType; - } - - @Override - public String getCallbackAddress() { - return callbackAddress; - } - - public void setCallbackAddress(String callbackAddress) { - this.callbackAddress = callbackAddress; - } - - @Override - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - @Override - public int getProcessStatus() { - return processStatus; - } - - public void setProcessStatus(int status) { - processStatus = status; - } - - @Override - public int getResultCode() { - return resultCode; - } - - public void setResultCode(int resultCode) { - this.resultCode = resultCode; - } - - @Override - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - @Override - public Long getInitMsid() { - return initMsid; - } - - public void setInitMsid(Long initMsid) { - this.initMsid = initMsid; - } - - @Override - public Long getCompleteMsid() { - return completeMsid; - } - - public void setCompleteMsid(Long completeMsid) { - this.completeMsid = completeMsid; - } - - @Override - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - @Override - public Date getLastUpdated() { - return lastUpdated; - } - - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } - - @Override - public Date getLastPolled() { - return lastPolled; - } - - public void setLastPolled(Date lastPolled) { - this.lastPolled = lastPolled; - } - - @Override - public Date getRemoved() { - return removed; - } - - public void setRemoved(Date removed) { - this.removed = removed; - } - - @Override - public Type getInstanceType() { - return instanceType; - } - - public void setInstanceType(Type instanceType) { - this.instanceType = instanceType; - } - - @Override - public Long getInstanceId() { - return instanceId; - } - - public void setInstanceId(Long instanceId) { - this.instanceId = instanceId; - } - - @Override - public String getSessionKey() { - return sessionKey; - } - - public void setSessionKey(String sessionKey) { - this.sessionKey = sessionKey; - } - - @Override - public String getCmdOriginator() { - return cmdOriginator; - } - - public void setCmdOriginator(String cmdOriginator) { - this.cmdOriginator = cmdOriginator; - } + public String getCmd() { + return cmd; + } + + public void setCmd(String cmd) { + this.cmd = cmd; + } - @Override + @Override + public int getCmdVersion() { + return cmdVersion; + } + + public void setCmdVersion(int version) { + cmdVersion = version; + } + + @Override + public String getCmdInfo() { + return cmdInfo; + } + + public void setCmdInfo(String cmdInfo) { + this.cmdInfo = cmdInfo; + } + + @Override + public int getCallbackType() { + return callbackType; + } + + public void setCallbackType(int callbackType) { + this.callbackType = callbackType; + } + + @Override + public String getCallbackAddress() { + return callbackAddress; + } + + public void setCallbackAddress(String callbackAddress) { + this.callbackAddress = callbackAddress; + } + + @Override + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + @Override + public int getProcessStatus() { + return processStatus; + } + + public void setProcessStatus(int status) { + processStatus = status; + } + + @Override + public int getResultCode() { + return resultCode; + } + + public void setResultCode(int resultCode) { + this.resultCode = resultCode; + } + + @Override + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + @Override + public Long getInitMsid() { + return initMsid; + } + + public void setInitMsid(Long initMsid) { + this.initMsid = initMsid; + } + + @Override + public Long getCompleteMsid() { + return completeMsid; + } + + public void setCompleteMsid(Long completeMsid) { + this.completeMsid = completeMsid; + } + + @Override + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + @Override + public Date getLastUpdated() { + return lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + @Override + public Date getLastPolled() { + return lastPolled; + } + + public void setLastPolled(Date lastPolled) { + this.lastPolled = lastPolled; + } + + @Override + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + @Override + public Type getInstanceType() { + return instanceType; + } + + public void setInstanceType(Type instanceType) { + this.instanceType = instanceType; + } + + @Override + public Long getInstanceId() { + return instanceId; + } + + public void setInstanceId(Long instanceId) { + this.instanceId = instanceId; + } + + @Override + public String getSessionKey() { + return sessionKey; + } + + public void setSessionKey(String sessionKey) { + this.sessionKey = sessionKey; + } + + @Override + public String getCmdOriginator() { + return cmdOriginator; + } + + public void setCmdOriginator(String cmdOriginator) { + this.cmdOriginator = cmdOriginator; + } + + @Override public SyncQueueItemVO getSyncSource() { return syncSource; } @@ -363,30 +363,30 @@ public class AsyncJobVO implements AsyncJob { } @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("AsyncJobVO {id:").append(getId()); - sb.append(", userId: ").append(getUserId()); - sb.append(", accountId: ").append(getAccountId()); - sb.append(", sessionKey: ").append(getSessionKey()); - sb.append(", instanceType: ").append(getInstanceType()); - sb.append(", instanceId: ").append(getInstanceId()); - sb.append(", cmd: ").append(getCmd()); - sb.append(", cmdOriginator: ").append(getCmdOriginator()); - sb.append(", cmdInfo: ").append(getCmdInfo()); - sb.append(", cmdVersion: ").append(getCmdVersion()); - sb.append(", callbackType: ").append(getCallbackType()); - sb.append(", callbackAddress: ").append(getCallbackAddress()); - sb.append(", status: ").append(getStatus()); - sb.append(", processStatus: ").append(getProcessStatus()); - sb.append(", resultCode: ").append(getResultCode()); - sb.append(", result: ").append(getResult()); - sb.append(", initMsid: ").append(getInitMsid()); - sb.append(", completeMsid: ").append(getCompleteMsid()); - sb.append(", lastUpdated: ").append(getLastUpdated()); - sb.append(", lastPolled: ").append(getLastPolled()); - sb.append(", created: ").append(getCreated()); - sb.append("}"); - return sb.toString(); - } -} + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("AsyncJobVO {id:").append(getId()); + sb.append(", userId: ").append(getUserId()); + sb.append(", accountId: ").append(getAccountId()); + sb.append(", sessionKey: ").append(getSessionKey()); + sb.append(", instanceType: ").append(getInstanceType()); + sb.append(", instanceId: ").append(getInstanceId()); + sb.append(", cmd: ").append(getCmd()); + sb.append(", cmdOriginator: ").append(getCmdOriginator()); + sb.append(", cmdInfo: ").append(getCmdInfo()); + sb.append(", cmdVersion: ").append(getCmdVersion()); + sb.append(", callbackType: ").append(getCallbackType()); + sb.append(", callbackAddress: ").append(getCallbackAddress()); + sb.append(", status: ").append(getStatus()); + sb.append(", processStatus: ").append(getProcessStatus()); + sb.append(", resultCode: ").append(getResultCode()); + sb.append(", result: ").append(getResult()); + sb.append(", initMsid: ").append(getInitMsid()); + sb.append(", completeMsid: ").append(getCompleteMsid()); + sb.append(", lastUpdated: ").append(getLastUpdated()); + sb.append(", lastPolled: ").append(getLastPolled()); + sb.append(", created: ").append(getCreated()); + sb.append("}"); + return sb.toString(); + } +} diff --git a/core/src/com/cloud/async/SyncQueueItemVO.java b/core/src/com/cloud/async/SyncQueueItemVO.java index 085d953676a..47f09084e44 100644 --- a/core/src/com/cloud/async/SyncQueueItemVO.java +++ b/core/src/com/cloud/async/SyncQueueItemVO.java @@ -10,111 +10,111 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="sync_queue_item") -public class SyncQueueItemVO implements SyncQueueItem{ - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id = null; - - @Column(name="queue_id") - private Long queueId; - - @Column(name="content_type") - private String contentType; - - @Column(name="content_id") - private Long contentId; - - @Column(name="queue_proc_msid") - private Long lastProcessMsid; - - @Column(name="queue_proc_number") - private Long lastProcessNumber; - - @Column(name="created") - private Date created; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getQueueId() { - return queueId; - } - - public void setQueueId(Long queueId) { - this.queueId = queueId; - } +package com.cloud.async; - @Override - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="sync_queue_item") +public class SyncQueueItemVO implements SyncQueueItem{ + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id = null; - @Override - public Long getContentId() { - return contentId; - } - - public void setContentId(Long contentId) { - this.contentId = contentId; - } - - public Long getLastProcessMsid() { - return lastProcessMsid; - } - - public void setLastProcessMsid(Long lastProcessMsid) { - this.lastProcessMsid = lastProcessMsid; - } - - public Long getLastProcessNumber() { - return lastProcessNumber; - } - - public void setLastProcessNumber(Long lastProcessNumber) { - this.lastProcessNumber = lastProcessNumber; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("SyncQueueItemVO {id:").append(getId()).append(", queueId: ").append(getQueueId()); - sb.append(", contentType: ").append(getContentType()); - sb.append(", contentId: ").append(getContentId()); - sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); - sb.append(", lastprocessNumber: ").append(getLastProcessNumber()); - sb.append(", created: ").append(getCreated()); - sb.append("}"); - return sb.toString(); - } -} + @Column(name="queue_id") + private Long queueId; + + @Column(name="content_type") + private String contentType; + + @Column(name="content_id") + private Long contentId; + + @Column(name="queue_proc_msid") + private Long lastProcessMsid; + + @Column(name="queue_proc_number") + private Long lastProcessNumber; + + @Column(name="created") + private Date created; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getQueueId() { + return queueId; + } + + public void setQueueId(Long queueId) { + this.queueId = queueId; + } + + @Override + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @Override + public Long getContentId() { + return contentId; + } + + public void setContentId(Long contentId) { + this.contentId = contentId; + } + + public Long getLastProcessMsid() { + return lastProcessMsid; + } + + public void setLastProcessMsid(Long lastProcessMsid) { + this.lastProcessMsid = lastProcessMsid; + } + + public Long getLastProcessNumber() { + return lastProcessNumber; + } + + public void setLastProcessNumber(Long lastProcessNumber) { + this.lastProcessNumber = lastProcessNumber; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("SyncQueueItemVO {id:").append(getId()).append(", queueId: ").append(getQueueId()); + sb.append(", contentType: ").append(getContentType()); + sb.append(", contentId: ").append(getContentId()); + sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); + sb.append(", lastprocessNumber: ").append(getLastProcessNumber()); + sb.append(", created: ").append(getCreated()); + sb.append("}"); + return sb.toString(); + } +} diff --git a/core/src/com/cloud/async/SyncQueueVO.java b/core/src/com/cloud/async/SyncQueueVO.java index 5f21a304362..e855b7ddc20 100644 --- a/core/src/com/cloud/async/SyncQueueVO.java +++ b/core/src/com/cloud/async/SyncQueueVO.java @@ -10,126 +10,126 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.async; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="sync_queue") -public class SyncQueueVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id; - - @Column(name="sync_objtype") - private String syncObjType; - - @Column(name="sync_objid") - private Long syncObjId; - - @Column(name="queue_proc_number") - private Long lastProcessNumber; - - @Column(name="queue_proc_time") - @Temporal(TemporalType.TIMESTAMP) - private Date lastProcessTime; - - @Column(name="queue_proc_msid") - private Long lastProcessMsid; - - @Column(name="created") - @Temporal(TemporalType.TIMESTAMP) - private Date created; - - @Column(name="last_updated") - @Temporal(TemporalType.TIMESTAMP) - private Date lastUpdated; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getSyncObjType() { - return syncObjType; - } - - public void setSyncObjType(String syncObjType) { - this.syncObjType = syncObjType; - } - - public Long getSyncObjId() { - return syncObjId; - } - - public void setSyncObjId(Long syncObjId) { - this.syncObjId = syncObjId; - } - - public Long getLastProcessNumber() { - return lastProcessNumber; - } - - public void setLastProcessNumber(Long number) { - lastProcessNumber = number; - } - - public Date getLastProcessTime() { - return lastProcessTime; - } - - public void setLastProcessTime(Date lastProcessTime) { - this.lastProcessTime = lastProcessTime; - } - - public Long getLastProcessMsid() { - return lastProcessMsid; - } - - public void setLastProcessMsid(Long lastProcessMsid) { - this.lastProcessMsid = lastProcessMsid; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getLastUpdated() { - return lastUpdated; - } - - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("SyncQueueVO {id:").append(getId()); - sb.append(", syncObjType: ").append(getSyncObjType()); - sb.append(", syncObjId: ").append(getSyncObjId()); - sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); - sb.append(", lastProcessNumber: ").append(getLastProcessNumber()); - sb.append(", lastProcessTime: ").append(getLastProcessTime()); - sb.append(", lastUpdated: ").append(getLastUpdated()); - sb.append(", created: ").append(getCreated()); - sb.append("}"); - return sb.toString(); - } -} +package com.cloud.async; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="sync_queue") +public class SyncQueueVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id; + + @Column(name="sync_objtype") + private String syncObjType; + + @Column(name="sync_objid") + private Long syncObjId; + + @Column(name="queue_proc_number") + private Long lastProcessNumber; + + @Column(name="queue_proc_time") + @Temporal(TemporalType.TIMESTAMP) + private Date lastProcessTime; + + @Column(name="queue_proc_msid") + private Long lastProcessMsid; + + @Column(name="created") + @Temporal(TemporalType.TIMESTAMP) + private Date created; + + @Column(name="last_updated") + @Temporal(TemporalType.TIMESTAMP) + private Date lastUpdated; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSyncObjType() { + return syncObjType; + } + + public void setSyncObjType(String syncObjType) { + this.syncObjType = syncObjType; + } + + public Long getSyncObjId() { + return syncObjId; + } + + public void setSyncObjId(Long syncObjId) { + this.syncObjId = syncObjId; + } + + public Long getLastProcessNumber() { + return lastProcessNumber; + } + + public void setLastProcessNumber(Long number) { + lastProcessNumber = number; + } + + public Date getLastProcessTime() { + return lastProcessTime; + } + + public void setLastProcessTime(Date lastProcessTime) { + this.lastProcessTime = lastProcessTime; + } + + public Long getLastProcessMsid() { + return lastProcessMsid; + } + + public void setLastProcessMsid(Long lastProcessMsid) { + this.lastProcessMsid = lastProcessMsid; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getLastUpdated() { + return lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("SyncQueueVO {id:").append(getId()); + sb.append(", syncObjType: ").append(getSyncObjType()); + sb.append(", syncObjId: ").append(getSyncObjId()); + sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); + sb.append(", lastProcessNumber: ").append(getLastProcessNumber()); + sb.append(", lastProcessTime: ").append(getLastProcessTime()); + sb.append(", lastUpdated: ").append(getLastUpdated()); + sb.append(", created: ").append(getCreated()); + sb.append("}"); + return sb.toString(); + } +} diff --git a/core/src/com/cloud/capacity/CapacityVO.java b/core/src/com/cloud/capacity/CapacityVO.java index a62325a8266..4bc721d7cb9 100755 --- a/core/src/com/cloud/capacity/CapacityVO.java +++ b/core/src/com/cloud/capacity/CapacityVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.capacity; - +package com.cloud.capacity; + import javax.persistence.Transient; import java.util.Date; @@ -25,37 +25,37 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="op_host_capacity") -public class CapacityVO implements Capacity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="host_id") - private Long hostOrPoolId; - - @Column(name="data_center_id") - private Long dataCenterId; - - @Column(name="pod_id") - private Long podId; - + +@Entity +@Table(name="op_host_capacity") +public class CapacityVO implements Capacity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="host_id") + private Long hostOrPoolId; + + @Column(name="data_center_id") + private Long dataCenterId; + + @Column(name="pod_id") + private Long podId; + @Column(name="cluster_id") private Long clusterId; - @Column(name="used_capacity") - private long usedCapacity; + @Column(name="used_capacity") + private long usedCapacity; @Column(name="reserved_capacity") private long reservedCapacity; - - @Column(name="total_capacity") - private long totalCapacity; - - @Column(name="capacity_type") + + @Column(name="total_capacity") + private long totalCapacity; + + @Column(name="capacity_type") private short capacityType; @Column(name="capacity_state") @@ -67,21 +67,21 @@ public class CapacityVO implements Capacity { @Column(name="update_time", updatable=true, nullable=true) @Temporal(value=TemporalType.TIMESTAMP) protected Date updateTime; - + @Transient private Float usedPercentage; - - public CapacityVO() {} - - public CapacityVO(Long hostId, Long dataCenterId, Long podId, Long clusterId, long usedCapacity, long totalCapacity, short capacityType) { - this.hostOrPoolId = hostId; - this.dataCenterId = dataCenterId; + + public CapacityVO() {} + + public CapacityVO(Long hostId, Long dataCenterId, Long podId, Long clusterId, long usedCapacity, long totalCapacity, short capacityType) { + this.hostOrPoolId = hostId; + this.dataCenterId = dataCenterId; this.podId = podId; - this.clusterId = clusterId; - this.usedCapacity = usedCapacity; - this.totalCapacity = totalCapacity; + this.clusterId = clusterId; + this.usedCapacity = usedCapacity; + this.totalCapacity = totalCapacity; this.capacityType = capacityType; - this.updateTime = new Date(); + this.updateTime = new Date(); } public CapacityVO(Long dataCenterId, Long podId, Long clusterId, short capacityType, float usedPercentage) { @@ -90,35 +90,35 @@ public class CapacityVO implements Capacity { this.clusterId = clusterId; this.capacityType = capacityType; this.usedPercentage = usedPercentage; - } - + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public Long getHostOrPoolId() { - return hostOrPoolId; - } - - public void setHostId(Long hostId) { - this.hostOrPoolId = hostId; - } + public Long getHostOrPoolId() { + return hostOrPoolId; + } + + public void setHostId(Long hostId) { + this.hostOrPoolId = hostId; + } @Override - public Long getDataCenterId() { - return dataCenterId; - } - public void setDataCenterId(Long dataCenterId) { - this.dataCenterId = dataCenterId; - } - + public Long getDataCenterId() { + return dataCenterId; + } + public void setDataCenterId(Long dataCenterId) { + this.dataCenterId = dataCenterId; + } + @Override - public Long getPodId() { - return podId; - } - public void setPodId(long podId) { - this.podId = new Long(podId); + public Long getPodId() { + return podId; + } + public void setPodId(long podId) { + this.podId = new Long(podId); } @Override @@ -128,14 +128,14 @@ public class CapacityVO implements Capacity { public void setClusterId(long clusterId) { this.clusterId = new Long(clusterId); } - + @Override - public long getUsedCapacity() { - return usedCapacity; - } - public void setUsedCapacity(long usedCapacity) { + public long getUsedCapacity() { + return usedCapacity; + } + public void setUsedCapacity(long usedCapacity) { this.usedCapacity = usedCapacity; - this.setUpdateTime (new Date()); + this.setUpdateTime (new Date()); } @Override public long getReservedCapacity() { @@ -144,21 +144,21 @@ public class CapacityVO implements Capacity { public void setReservedCapacity(long reservedCapacity) { this.reservedCapacity = reservedCapacity; this.setUpdateTime (new Date()); - } + } @Override - public long getTotalCapacity() { - return totalCapacity; - } - public void setTotalCapacity(long totalCapacity) { + public long getTotalCapacity() { + return totalCapacity; + } + public void setTotalCapacity(long totalCapacity) { this.totalCapacity = totalCapacity; - this.setUpdateTime (new Date()); - } + this.setUpdateTime (new Date()); + } @Override - public short getCapacityType() { - return capacityType; - } - public void setCapacityType(short capacityType) { - this.capacityType = capacityType; + public short getCapacityType() { + return capacityType; + } + public void setCapacityType(short capacityType) { + this.capacityType = capacityType; } public CapacityState getCapacityState() { @@ -188,5 +188,5 @@ public class CapacityVO implements Capacity { public void setUsedPercentage(float usedPercentage) { this.usedPercentage = usedPercentage; - } -} + } +} diff --git a/core/src/com/cloud/configuration/ConfigurationVO.java b/core/src/com/cloud/configuration/ConfigurationVO.java index e1aa68cacd2..2f144f2f7c1 100644 --- a/core/src/com/cloud/configuration/ConfigurationVO.java +++ b/core/src/com/cloud/configuration/ConfigurationVO.java @@ -10,94 +10,94 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.configuration; - +package com.cloud.configuration; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.crypt.DBEncryptionUtil; - -@Entity -@Table(name="configuration") -public class ConfigurationVO implements Configuration{ - @Column(name="instance") - private String instance; - - @Column(name="component") - private String component; - - @Id - @Column(name="name") - private String name; - - @Column(name="value", length=4095) - private String value; - - @Column(name="description", length=1024) - private String description; - - @Column(name="category") - private String category; - - protected ConfigurationVO() {} - - public ConfigurationVO(String category, String instance, String component, String name, String value, String description) { - this.category = category; - this.instance = instance; - this.component = component; - this.name = name; - this.value = value; - this.description = description; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getInstance() { - return instance; - } - - public void setInstance(String instance) { - this.instance = instance; - } - - public String getComponent() { - return component; - } - - public void setComponent(String component) { - this.component = component; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - + +@Entity +@Table(name="configuration") +public class ConfigurationVO implements Configuration{ + @Column(name="instance") + private String instance; + + @Column(name="component") + private String component; + + @Id + @Column(name="name") + private String name; + + @Column(name="value", length=4095) + private String value; + + @Column(name="description", length=1024) + private String description; + + @Column(name="category") + private String category; + + protected ConfigurationVO() {} + + public ConfigurationVO(String category, String instance, String component, String name, String value, String description) { + this.category = category; + this.instance = instance; + this.component = component; + this.name = name; + this.value = value; + this.description = description; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getInstance() { + return instance; + } + + public void setInstance(String instance) { + this.instance = instance; + } + + public String getComponent() { + return component; + } + + public void setComponent(String component) { + this.component = component; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public String getValue() { - return (("Hidden".equals(getCategory()) || "Secure".equals(getCategory())) ? DBEncryptionUtil.decrypt(value) : value); - } - - public void setValue(String value) { - this.value = value; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - -} + return (("Hidden".equals(getCategory()) || "Secure".equals(getCategory())) ? DBEncryptionUtil.decrypt(value) : 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/core/src/com/cloud/consoleproxy/ConsoleProxyAllocator.java b/core/src/com/cloud/consoleproxy/ConsoleProxyAllocator.java index 0363f96c165..7e11435d2c7 100644 --- a/core/src/com/cloud/consoleproxy/ConsoleProxyAllocator.java +++ b/core/src/com/cloud/consoleproxy/ConsoleProxyAllocator.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.consoleproxy; - -import java.util.List; -import java.util.Map; - +package com.cloud.consoleproxy; + +import java.util.List; +import java.util.Map; + import com.cloud.utils.component.Adapter; import com.cloud.vm.ConsoleProxyVO; - -public interface ConsoleProxyAllocator extends Adapter { - public ConsoleProxyVO allocProxy(List candidates, Map loadInfo, long dataCenterId); -} + +public interface ConsoleProxyAllocator extends Adapter { + public ConsoleProxyVO allocProxy(List candidates, Map loadInfo, long dataCenterId); +} diff --git a/core/src/com/cloud/event/EventVO.java b/core/src/com/cloud/event/EventVO.java index 775afa83104..0fbc502f7d2 100644 --- a/core/src/com/cloud/event/EventVO.java +++ b/core/src/com/cloud/event/EventVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.event; - +package com.cloud.event; + import java.util.Date; import java.util.UUID; @@ -27,70 +27,70 @@ import javax.persistence.Transient; import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="event") -public class EventVO implements Event, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id = -1; - - @Column(name="type") + +@Entity +@Table(name="event") +public class EventVO implements Event, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id = -1; + + @Column(name="type") private String type; @Enumerated(value=EnumType.STRING) @Column(name="state") - private State state = State.Completed; - - @Column(name="description", length=1024) - private String description; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date createDate; - - @Column(name="user_id") - private long userId; - - @Column(name="account_id") - private long accountId; - - @Column(name="domain_id") - private long domainId; - - @Column(name="level") + private State state = State.Completed; + + @Column(name="description", length=1024) + private String description; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date createDate; + + @Column(name="user_id") + private long userId; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="level") private String level = LEVEL_INFO; @Column(name="start_id") - private long startId; - - @Column(name="parameters", length=1024) + private long startId; + + @Column(name="parameters", length=1024) private String parameters; - + @Column(name="uuid") private String uuid; - - @Transient - private int totalSize; - - public static final String LEVEL_INFO = "INFO"; - public static final String LEVEL_WARN = "WARN"; - public static final String LEVEL_ERROR = "ERROR"; - + + @Transient + private int totalSize; + + public static final String LEVEL_INFO = "INFO"; + public static final String LEVEL_WARN = "WARN"; + public static final String LEVEL_ERROR = "ERROR"; + public EventVO() { - this.uuid = UUID.randomUUID().toString(); - } - - public long getId() { - return id; - } + this.uuid = UUID.randomUUID().toString(); + } + + public long getId() { + return id; + } @Override - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } @Override public State getState() { return state; @@ -101,56 +101,56 @@ public class EventVO implements Event, Identity { } @Override - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } @Override - public Date getCreateDate() { - return createDate; - } - public void setCreatedDate(Date createdDate) { - createDate = createdDate; - } + public Date getCreateDate() { + return createDate; + } + public void setCreatedDate(Date createdDate) { + createDate = createdDate; + } @Override - public long getUserId() { - return userId; - } - public void setUserId(long userId) { - this.userId = userId; - } + public long getUserId() { + return userId; + } + public void setUserId(long userId) { + this.userId = userId; + } @Override - public long getAccountId() { - return accountId; - } - public void setAccountId(long accountId) { - this.accountId = accountId; - } - @Override - public long getDomainId() { - return domainId; + public long getAccountId() { + return accountId; } - + public void setAccountId(long accountId) { + this.accountId = accountId; + } + @Override + public long getDomainId() { + return domainId; + } + public void setDomainId(long domainId) { this.domainId = domainId; } @Override - public int getTotalSize() { - return totalSize; - } - public void setTotalSize(int totalSize) { - this.totalSize = totalSize; - } + public int getTotalSize() { + return totalSize; + } + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } @Override - public String getLevel() { - return level; - } - public void setLevel(String level) { - this.level = level; - } + public String getLevel() { + return level; + } + public void setLevel(String level) { + this.level = level; + } @Override public long getStartId() { return startId; @@ -161,11 +161,11 @@ public class EventVO implements Event, Identity { } @Override - public String getParameters() { - return parameters; - } - public void setParameters(String parameters) { - this.parameters = parameters; + public String getParameters() { + return parameters; + } + public void setParameters(String parameters) { + this.parameters = parameters; } @Override @@ -177,4 +177,4 @@ public class EventVO implements Event, Identity { this.uuid = uuid; } -} +} diff --git a/core/src/com/cloud/event/UsageEventVO.java b/core/src/com/cloud/event/UsageEventVO.java index 05de20a8ec4..1439226b550 100644 --- a/core/src/com/cloud/event/UsageEventVO.java +++ b/core/src/com/cloud/event/UsageEventVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.event; - +package com.cloud.event; + import java.util.Date; import javax.persistence.Column; @@ -22,24 +22,24 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="usage_event") -public class UsageEventVO implements UsageEvent { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id = -1; - - @Column(name="type") + +@Entity +@Table(name="usage_event") +public class UsageEventVO implements UsageEvent { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id = -1; + + @Column(name="type") private String type; - @Column(name=GenericDao.CREATED_COLUMN) - private Date createDate; - - @Column(name="account_id") - private long accountId; - + @Column(name=GenericDao.CREATED_COLUMN) + private Date createDate; + + @Column(name="account_id") + private long accountId; + @Column(name="zone_id") private long zoneId; @@ -48,7 +48,7 @@ public class UsageEventVO implements UsageEvent { @Column(name="resource_name") private String resourceName; - + @Column(name="offering_id") private Long offeringId; @@ -64,8 +64,8 @@ public class UsageEventVO implements UsageEvent { @Column(name="processed") boolean processed; - - public UsageEventVO() { + + public UsageEventVO() { } public UsageEventVO(String usageType, long accountId, long zoneId, long resourceId, String resourceName, Long offeringId, Long templateId, Long size) { @@ -121,31 +121,31 @@ public class UsageEventVO implements UsageEvent { } @Override - public long getId() { - return id; - } + public long getId() { + return id; + } @Override - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } @Override - public Date getCreateDate() { - return createDate; - } - public void setCreatedDate(Date createdDate) { - createDate = createdDate; + public Date getCreateDate() { + return createDate; } - + public void setCreatedDate(Date createdDate) { + createDate = createdDate; + } + @Override - public long getAccountId() { - return accountId; - } - public void setAccountId(long accountId) { - this.accountId = accountId; + public long getAccountId() { + return accountId; + } + public void setAccountId(long accountId) { + this.accountId = accountId; } public void setZoneId(long zoneId) { @@ -208,4 +208,4 @@ public class UsageEventVO implements UsageEvent { return resourceType; } -} +} diff --git a/core/src/com/cloud/event/dao/EventDao.java b/core/src/com/cloud/event/dao/EventDao.java index e1f68982879..fc532af4f87 100644 --- a/core/src/com/cloud/event/dao/EventDao.java +++ b/core/src/com/cloud/event/dao/EventDao.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.event.dao; - +package com.cloud.event.dao; + import java.util.Date; import java.util.List; @@ -19,11 +19,11 @@ import com.cloud.event.EventVO; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.SearchCriteria; - -public interface EventDao extends GenericDao { + +public interface EventDao extends GenericDao { public List searchAllEvents(SearchCriteria sc, Filter filter); public List listOlderEvents(Date oldTime); - EventVO findCompletedEvent(long startId); -} + EventVO findCompletedEvent(long startId); +} diff --git a/core/src/com/cloud/event/dao/EventDaoImpl.java b/core/src/com/cloud/event/dao/EventDaoImpl.java index 218d0c52472..722e5eb64d0 100644 --- a/core/src/com/cloud/event/dao/EventDaoImpl.java +++ b/core/src/com/cloud/event/dao/EventDaoImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.event.dao; - +package com.cloud.event.dao; + import java.util.Date; import java.util.List; @@ -25,24 +25,24 @@ import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; - -@Local(value={EventDao.class}) -public class EventDaoImpl extends GenericDaoBase implements EventDao { - public static final Logger s_logger = Logger.getLogger(EventDaoImpl.class.getName()); - protected final SearchBuilder CompletedEventSearch; - + +@Local(value={EventDao.class}) +public class EventDaoImpl extends GenericDaoBase implements EventDao { + public static final Logger s_logger = Logger.getLogger(EventDaoImpl.class.getName()); + protected final SearchBuilder CompletedEventSearch; + public EventDaoImpl () { CompletedEventSearch = createSearchBuilder(); CompletedEventSearch.and("state",CompletedEventSearch.entity().getState(),SearchCriteria.Op.EQ); CompletedEventSearch.and("startId", CompletedEventSearch.entity().getStartId(), SearchCriteria.Op.EQ); CompletedEventSearch.done(); - } - - @Override - public List searchAllEvents(SearchCriteria sc, Filter filter) { - return listIncludingRemovedBy(sc, filter); - } - + } + + @Override + public List searchAllEvents(SearchCriteria sc, Filter filter) { + return listIncludingRemovedBy(sc, filter); + } + @Override public List listOlderEvents(Date oldTime) { if (oldTime == null) return null; @@ -59,4 +59,4 @@ public class EventDaoImpl extends GenericDaoBase implements Event sc.setParameters("startId", startId); return findOneIncludingRemovedBy(sc); } -} +} diff --git a/core/src/com/cloud/event/dao/UsageEventDao.java b/core/src/com/cloud/event/dao/UsageEventDao.java index 8a4079a180f..80513d846ea 100644 --- a/core/src/com/cloud/event/dao/UsageEventDao.java +++ b/core/src/com/cloud/event/dao/UsageEventDao.java @@ -10,17 +10,17 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.event.dao; - +package com.cloud.event.dao; + import java.util.Date; import java.util.List; import com.cloud.event.UsageEventVO; import com.cloud.exception.UsageServerException; import com.cloud.utils.db.GenericDao; - + public interface UsageEventDao extends GenericDao { - + public List listLatestEvents(Date endDate); public List getLatestEvent(); diff --git a/core/src/com/cloud/event/dao/UsageEventDaoImpl.java b/core/src/com/cloud/event/dao/UsageEventDaoImpl.java index cb2d87c4773..37b99a3b74c 100644 --- a/core/src/com/cloud/event/dao/UsageEventDaoImpl.java +++ b/core/src/com/cloud/event/dao/UsageEventDaoImpl.java @@ -62,7 +62,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem IpeventsSearch.or("releaseEvent", IpeventsSearch.entity().getType(), SearchCriteria.Op.EQ); IpeventsSearch.closeParen(); IpeventsSearch.done(); - } + } @Override public List listLatestEvents(Date endDate) { @@ -177,5 +177,5 @@ public class UsageEventDaoImpl extends GenericDaoBase implem sc.setParameters("networktype", Vlan.VlanType.DirectAttached.toString()); return listBy(sc, filter); } - -} + +} diff --git a/core/src/com/cloud/exception/AgentControlChannelException.java b/core/src/com/cloud/exception/AgentControlChannelException.java index 7658ac2a4d4..c71351b285c 100644 --- a/core/src/com/cloud/exception/AgentControlChannelException.java +++ b/core/src/com/cloud/exception/AgentControlChannelException.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.exception; +package com.cloud.exception; import com.cloud.exception.CloudException; - -public class AgentControlChannelException extends CloudException { - private static final long serialVersionUID = -310647782960500466L; - - public AgentControlChannelException(String msg) { - super(msg); - } -} + +public class AgentControlChannelException extends CloudException { + private static final long serialVersionUID = -310647782960500466L; + + public AgentControlChannelException(String msg) { + super(msg); + } +} diff --git a/core/src/com/cloud/host/HostTagVO.java b/core/src/com/cloud/host/HostTagVO.java index ec1b0f568dc..600fb6dc5af 100644 --- a/core/src/com/cloud/host/HostTagVO.java +++ b/core/src/com/cloud/host/HostTagVO.java @@ -10,50 +10,50 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.host; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="host_tags") -public class HostTagVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="host_id") - private long hostId; - - @Column(name="tag") - private String tag; - - protected HostTagVO() { - } - - public HostTagVO(long hostId, String tag) { - this.hostId = hostId; - this.tag = tag; - } - - public long getHostId() { - return hostId; - } - - public String getTag() { - return tag; - } - - public void setTag(String tag) { - this.tag = tag; - } - - public long getId() { - return id; - } -} +package com.cloud.host; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="host_tags") +public class HostTagVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="host_id") + private long hostId; + + @Column(name="tag") + private String tag; + + protected HostTagVO() { + } + + public HostTagVO(long hostId, String tag) { + this.hostId = hostId; + this.tag = tag; + } + + public long getHostId() { + return hostId; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + public long getId() { + return id; + } +} diff --git a/core/src/com/cloud/host/HostVO.java b/core/src/com/cloud/host/HostVO.java index 38c8996431f..e339c20a3ae 100755 --- a/core/src/com/cloud/host/HostVO.java +++ b/core/src/com/cloud/host/HostVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.host; - +package com.cloud.host; + import java.util.Date; import java.util.List; import java.util.Map; @@ -39,84 +39,84 @@ import com.cloud.resource.ResourceState; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="host") -@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) -@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class HostVO implements Host, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="disconnected") - @Temporal(value=TemporalType.TIMESTAMP) - private Date disconnectedOn; - - @Column(name="name", nullable=false) - private String name = null; - - /** - * Note: There is no setter for status because it has to be set in the dao code. - */ - @Column(name="status", nullable=false) - private Status status = null; - - @Column(name="type", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) - private Type type; - - @Column(name="private_ip_address", nullable=false) - private String privateIpAddress; - - @Column(name="private_mac_address", nullable=false) - private String privateMacAddress; - - @Column(name="private_netmask", nullable=false) - private String privateNetmask; - - @Column(name="public_netmask") - private String publicNetmask; - - @Column(name="public_ip_address") - private String publicIpAddress; - - @Column(name="public_mac_address") - private String publicMacAddress; - - @Column(name="storage_ip_address") - private String storageIpAddress; + +@Entity +@Table(name="host") +@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) +@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) +public class HostVO implements Host, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="disconnected") + @Temporal(value=TemporalType.TIMESTAMP) + private Date disconnectedOn; + + @Column(name="name", nullable=false) + private String name = null; + + /** + * Note: There is no setter for status because it has to be set in the dao code. + */ + @Column(name="status", nullable=false) + private Status status = null; + + @Column(name="type", updatable = true, nullable=false) + @Enumerated(value=EnumType.STRING) + private Type type; + + @Column(name="private_ip_address", nullable=false) + private String privateIpAddress; + + @Column(name="private_mac_address", nullable=false) + private String privateMacAddress; + + @Column(name="private_netmask", nullable=false) + private String privateNetmask; + + @Column(name="public_netmask") + private String publicNetmask; + + @Column(name="public_ip_address") + private String publicIpAddress; + + @Column(name="public_mac_address") + private String publicMacAddress; + + @Column(name="storage_ip_address") + private String storageIpAddress; @Column(name="cluster_id") private Long clusterId; - - @Column(name="storage_netmask") - private String storageNetmask; - - @Column(name="storage_mac_address") - private String storageMacAddress; - - @Column(name="storage_ip_address_2") - private String storageIpAddressDeux; - - @Column(name="storage_netmask_2") - private String storageNetmaskDeux; - - @Column(name="storage_mac_address_2") - private String storageMacAddressDeux; - - @Column(name="hypervisor_type", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) - private HypervisorType hypervisorType; - - @Column(name="proxy_port") - private Integer proxyPort; - - @Column(name="resource") - private String resource; - - @Column(name="fs_type") + + @Column(name="storage_netmask") + private String storageNetmask; + + @Column(name="storage_mac_address") + private String storageMacAddress; + + @Column(name="storage_ip_address_2") + private String storageIpAddressDeux; + + @Column(name="storage_netmask_2") + private String storageNetmaskDeux; + + @Column(name="storage_mac_address_2") + private String storageMacAddressDeux; + + @Column(name="hypervisor_type", updatable = true, nullable=false) + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + @Column(name="proxy_port") + private Integer proxyPort; + + @Column(name="resource") + private String resource; + + @Column(name="fs_type") private StoragePoolType fsType; @Column(name="available") @@ -128,7 +128,7 @@ public class HostVO implements Host, Identity { @Column(name="resource_state", nullable=false) @Enumerated(value=EnumType.STRING) private ResourceState resourceState; - + @Column(name="hypervisor_version") private String hypervisorVersion; @@ -137,32 +137,32 @@ public class HostVO implements Host, Identity { @Column(name="uuid") private String uuid; - - // This is a delayed load value. If the value is null, - // then this field has not been loaded yet. - // Call host dao to load it. - @Transient - Map details; + + // This is a delayed load value. If the value is null, + // then this field has not been loaded yet. + // Call host dao to load it. + @Transient + Map details; // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call host dao to load it. @Transient List hostTags; - - @Override - public String getStorageIpAddressDeux() { - return storageIpAddressDeux; - } - - public void setStorageIpAddressDeux(String deuxStorageIpAddress) { - this.storageIpAddressDeux = deuxStorageIpAddress; - } - + @Override - public String getStorageNetmaskDeux() { - return storageNetmaskDeux; - } + public String getStorageIpAddressDeux() { + return storageIpAddressDeux; + } + + public void setStorageIpAddressDeux(String deuxStorageIpAddress) { + this.storageIpAddressDeux = deuxStorageIpAddress; + } + + @Override + public String getStorageNetmaskDeux() { + return storageNetmaskDeux; + } @Override public Long getClusterId() { @@ -172,27 +172,27 @@ public class HostVO implements Host, Identity { public void setClusterId(Long clusterId) { this.clusterId = clusterId; } - - public void setStorageNetmaskDeux(String deuxStorageNetmask) { - this.storageNetmaskDeux = deuxStorageNetmask; - } - + + public void setStorageNetmaskDeux(String deuxStorageNetmask) { + this.storageNetmaskDeux = deuxStorageNetmask; + } + @Override - public String getStorageMacAddressDeux() { - return storageMacAddressDeux; - } - - public void setStorageMacAddressDeux(String duexStorageMacAddress) { - this.storageMacAddressDeux = duexStorageMacAddress; - } - + public String getStorageMacAddressDeux() { + return storageMacAddressDeux; + } + + public void setStorageMacAddressDeux(String duexStorageMacAddress) { + this.storageMacAddressDeux = duexStorageMacAddress; + } + @Override - public String getPrivateMacAddress() { - return privateMacAddress; - } - - public void setPrivateMacAddress(String privateMacAddress) { - this.privateMacAddress = privateMacAddress; + public String getPrivateMacAddress() { + return privateMacAddress; + } + + public void setPrivateMacAddress(String privateMacAddress) { + this.privateMacAddress = privateMacAddress; } public boolean isAvailable() { @@ -201,65 +201,65 @@ public class HostVO implements Host, Identity { public void setAvailable(boolean available) { this.available = available; - } - + } + @Override - public String getPrivateNetmask() { - return privateNetmask; - } - - public void setPrivateNetmask(String privateNetmask) { - this.privateNetmask = privateNetmask; - } - + public String getPrivateNetmask() { + return privateNetmask; + } + + public void setPrivateNetmask(String privateNetmask) { + this.privateNetmask = privateNetmask; + } + @Override - public String getPublicNetmask() { - return publicNetmask; - } - - public void setPublicNetmask(String publicNetmask) { - this.publicNetmask = publicNetmask; - } - + public String getPublicNetmask() { + return publicNetmask; + } + + public void setPublicNetmask(String publicNetmask) { + this.publicNetmask = publicNetmask; + } + @Override - public String getPublicIpAddress() { - return publicIpAddress; - } - - public void setPublicIpAddress(String publicIpAddress) { - this.publicIpAddress = publicIpAddress; - } - + public String getPublicIpAddress() { + return publicIpAddress; + } + + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } + @Override - public String getPublicMacAddress() { - return publicMacAddress; - } - - public void setPublicMacAddress(String publicMacAddress) { - this.publicMacAddress = publicMacAddress; - } - - @Override - public String getStorageIpAddress() { - return storageIpAddress; - } - - public void setStorageIpAddress(String storageIpAddress) { - this.storageIpAddress = storageIpAddress; - } - + public String getPublicMacAddress() { + return publicMacAddress; + } + + public void setPublicMacAddress(String publicMacAddress) { + this.publicMacAddress = publicMacAddress; + } + @Override - public String getStorageNetmask() { - return storageNetmask; - } - - public void setStorageNetmask(String storageNetmask) { - this.storageNetmask = storageNetmask; - } - + public String getStorageIpAddress() { + return storageIpAddress; + } + + public void setStorageIpAddress(String storageIpAddress) { + this.storageIpAddress = storageIpAddress; + } + @Override - public String getStorageMacAddress() { - return storageMacAddress; + public String getStorageNetmask() { + return storageNetmask; + } + + public void setStorageNetmask(String storageNetmask) { + this.storageNetmask = storageNetmask; + } + + @Override + public String getStorageMacAddress() { + return storageMacAddress; } public boolean isSetup() { @@ -268,39 +268,39 @@ public class HostVO implements Host, Identity { public void setSetup(boolean setup) { this.setup = setup; - } - - public void setStorageMacAddress(String storageMacAddress) { - this.storageMacAddress = storageMacAddress; - } - - public String getResource() { - return resource; - } - - public void setResource(String resource) { - this.resource = resource; - } - - public Map getDetails() { - return details; - } - - public String getDetail(String name) { - assert (details != null) : "Did you forget to load the details?"; - - return details != null ? details.get(name) : null; - } - - public void setDetail(String name, String value) { - assert (details != null) : "Did you forget to load the details?"; - - details.put(name, value); - } - - public void setDetails(Map details) { - this.details = details; - } + } + + public void setStorageMacAddress(String storageMacAddress) { + this.storageMacAddress = storageMacAddress; + } + + public String getResource() { + return resource; + } + + public void setResource(String resource) { + this.resource = resource; + } + + public Map getDetails() { + return details; + } + + public String getDetail(String name) { + assert (details != null) : "Did you forget to load the details?"; + + return details != null ? details.get(name) : null; + } + + public void setDetail(String name, String value) { + assert (details != null) : "Did you forget to load the details?"; + + details.put(name, value); + } + + public void setDetails(Map details) { + this.details = details; + } public List getHostTags() { return hostTags; @@ -309,372 +309,372 @@ public class HostVO implements Host, Identity { public void setHostTags(List hostTags) { this.hostTags = hostTags; } - - @Column(name="data_center_id", nullable=false) - private long dataCenterId; - - @Column(name="pod_id") - private Long podId; - - @Column(name="cpus") - private Integer cpus; - - @Column(name="url") - private String storageUrl; - - @Column(name="speed") - private Long speed; - - @Column(name="ram") - private long totalMemory; - - @Column(name="parent", nullable=false) - private String parent; - - @Column(name="guid", updatable=true, nullable=false) - private String guid; - - @Column(name="capabilities") - private String caps; - - @Column(name="total_size") - private Long totalSize; - - @Column(name="last_ping") - private long lastPinged; - - @Column(name="mgmt_server_id") - private Long managementServerId; - - @Column(name="dom0_memory") - private long dom0MinMemory; - - @Column(name="version") - private String version; - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - public HostVO(String guid) { - this.guid = guid; - this.status = Status.Creating; - this.totalMemory = 0; + @Column(name="data_center_id", nullable=false) + private long dataCenterId; + + @Column(name="pod_id") + private Long podId; + + @Column(name="cpus") + private Integer cpus; + + @Column(name="url") + private String storageUrl; + + @Column(name="speed") + private Long speed; + + @Column(name="ram") + private long totalMemory; + + @Column(name="parent", nullable=false) + private String parent; + + @Column(name="guid", updatable=true, nullable=false) + private String guid; + + @Column(name="capabilities") + private String caps; + + @Column(name="total_size") + private Long totalSize; + + @Column(name="last_ping") + private long lastPinged; + + @Column(name="mgmt_server_id") + private Long managementServerId; + + @Column(name="dom0_memory") + private long dom0MinMemory; + + @Column(name="version") + private String version; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + public HostVO(String guid) { + this.guid = guid; + this.status = Status.Creating; + this.totalMemory = 0; this.dom0MinMemory = 0; this.resourceState = ResourceState.Creating; - this.uuid = UUID.randomUUID().toString(); - } - - protected HostVO() { this.uuid = UUID.randomUUID().toString(); - } - - public HostVO(long id, - String name, - Type type, - String privateIpAddress, - String privateNetmask, - String privateMacAddress, - String publicIpAddress, - String publicNetmask, - String publicMacAddress, - String storageIpAddress, - String storageNetmask, - String storageMacAddress, - String deuxStorageIpAddress, - String duxStorageNetmask, - String deuxStorageMacAddress, - String guid, - Status status, - String version, - String iqn, - Date disconnectedOn, - long dcId, - Long podId, - long serverId, - long ping, - String parent, - long totalSize, - StoragePoolType fsType) { - this(id, name, type, privateIpAddress, privateNetmask, privateMacAddress, publicIpAddress, publicNetmask, publicMacAddress, storageIpAddress, storageNetmask, storageMacAddress, guid, status, version, iqn, disconnectedOn, dcId, podId, serverId, ping, null, null, null, 0, null); - this.parent = parent; - this.totalSize = totalSize; - this.fsType = fsType; + } + + protected HostVO() { this.uuid = UUID.randomUUID().toString(); - } - - public HostVO(long id, - String name, - Type type, - String privateIpAddress, - String privateNetmask, - String privateMacAddress, - String publicIpAddress, - String publicNetmask, - String publicMacAddress, - String storageIpAddress, - String storageNetmask, - String storageMacAddress, - String guid, - Status status, - String version, - String url, - Date disconnectedOn, - long dcId, - Long podId, - long serverId, - long ping, - Integer cpus, - Long speed, - Long totalMemory, - long dom0MinMemory, - String caps) { - this.id = id; - this.name = name; - this.status = status; - this.type = type; - this.privateIpAddress = privateIpAddress; - this.privateNetmask = privateNetmask; - this.privateMacAddress = privateMacAddress; - this.publicIpAddress = publicIpAddress; - this.publicNetmask = publicNetmask; - this.publicMacAddress = publicMacAddress; - this.storageIpAddress = storageIpAddress; - this.storageNetmask = storageNetmask; - this.storageMacAddress = storageMacAddress; - this.dataCenterId = dcId; - this.podId = podId; - this.cpus = cpus; - this.version = version; - this.speed = speed; - this.totalMemory = totalMemory != null ? totalMemory : 0; - this.guid = guid; - this.parent = null; - this.totalSize = null; - this.fsType = null; - this.managementServerId = serverId; - this.lastPinged = ping; - this.caps = caps; - this.disconnectedOn = disconnectedOn; - this.dom0MinMemory = dom0MinMemory; - this.storageUrl = url; + } + + public HostVO(long id, + String name, + Type type, + String privateIpAddress, + String privateNetmask, + String privateMacAddress, + String publicIpAddress, + String publicNetmask, + String publicMacAddress, + String storageIpAddress, + String storageNetmask, + String storageMacAddress, + String deuxStorageIpAddress, + String duxStorageNetmask, + String deuxStorageMacAddress, + String guid, + Status status, + String version, + String iqn, + Date disconnectedOn, + long dcId, + Long podId, + long serverId, + long ping, + String parent, + long totalSize, + StoragePoolType fsType) { + this(id, name, type, privateIpAddress, privateNetmask, privateMacAddress, publicIpAddress, publicNetmask, publicMacAddress, storageIpAddress, storageNetmask, storageMacAddress, guid, status, version, iqn, disconnectedOn, dcId, podId, serverId, ping, null, null, null, 0, null); + this.parent = parent; + this.totalSize = totalSize; + this.fsType = fsType; this.uuid = UUID.randomUUID().toString(); - } - - public void setPodId(Long podId) { - - this.podId = podId; - } - - public void setDataCenterId(long dcId) { - this.dataCenterId = dcId; - } - - public void setVersion(String version) { - this.version = version; - } - - public void setStorageUrl(String url) { - this.storageUrl = url; - } - - public void setDisconnectedOn(Date disconnectedOn) { - this.disconnectedOn = disconnectedOn; - } - - public String getStorageUrl() { - return storageUrl; - } - - public void setName(String name) { - this.name = name; - } - - public void setPrivateIpAddress(String ipAddress) { - this.privateIpAddress = ipAddress; - } - - public void setCpus(Integer cpus) { - this.cpus = cpus; - } - - public void setSpeed(Long speed) { - this.speed = speed; - } - - public void setTotalMemory(long totalMemory) { - this.totalMemory = totalMemory; - } - - public void setParent(String parent) { - this.parent = parent; - } - - public void setCaps(String caps) { - this.caps = caps; - } - - public void setTotalSize(Long totalSize) { - this.totalSize = totalSize; - } - - public void setLastPinged(long lastPinged) { - this.lastPinged = lastPinged; - } - - public void setManagementServerId(Long managementServerId) { - this.managementServerId = managementServerId; - } - + } + + public HostVO(long id, + String name, + Type type, + String privateIpAddress, + String privateNetmask, + String privateMacAddress, + String publicIpAddress, + String publicNetmask, + String publicMacAddress, + String storageIpAddress, + String storageNetmask, + String storageMacAddress, + String guid, + Status status, + String version, + String url, + Date disconnectedOn, + long dcId, + Long podId, + long serverId, + long ping, + Integer cpus, + Long speed, + Long totalMemory, + long dom0MinMemory, + String caps) { + this.id = id; + this.name = name; + this.status = status; + this.type = type; + this.privateIpAddress = privateIpAddress; + this.privateNetmask = privateNetmask; + this.privateMacAddress = privateMacAddress; + this.publicIpAddress = publicIpAddress; + this.publicNetmask = publicNetmask; + this.publicMacAddress = publicMacAddress; + this.storageIpAddress = storageIpAddress; + this.storageNetmask = storageNetmask; + this.storageMacAddress = storageMacAddress; + this.dataCenterId = dcId; + this.podId = podId; + this.cpus = cpus; + this.version = version; + this.speed = speed; + this.totalMemory = totalMemory != null ? totalMemory : 0; + this.guid = guid; + this.parent = null; + this.totalSize = null; + this.fsType = null; + this.managementServerId = serverId; + this.lastPinged = ping; + this.caps = caps; + this.disconnectedOn = disconnectedOn; + this.dom0MinMemory = dom0MinMemory; + this.storageUrl = url; + this.uuid = UUID.randomUUID().toString(); + } + + public void setPodId(Long podId) { + + this.podId = podId; + } + + public void setDataCenterId(long dcId) { + this.dataCenterId = dcId; + } + + public void setVersion(String version) { + this.version = version; + } + + public void setStorageUrl(String url) { + this.storageUrl = url; + } + + public void setDisconnectedOn(Date disconnectedOn) { + this.disconnectedOn = disconnectedOn; + } + + public String getStorageUrl() { + return storageUrl; + } + + public void setName(String name) { + this.name = name; + } + + public void setPrivateIpAddress(String ipAddress) { + this.privateIpAddress = ipAddress; + } + + public void setCpus(Integer cpus) { + this.cpus = cpus; + } + + public void setSpeed(Long speed) { + this.speed = speed; + } + + public void setTotalMemory(long totalMemory) { + this.totalMemory = totalMemory; + } + + public void setParent(String parent) { + this.parent = parent; + } + + public void setCaps(String caps) { + this.caps = caps; + } + + public void setTotalSize(Long totalSize) { + this.totalSize = totalSize; + } + + public void setLastPinged(long lastPinged) { + this.lastPinged = lastPinged; + } + + public void setManagementServerId(Long managementServerId) { + this.managementServerId = managementServerId; + } + @Override - public long getLastPinged() { - return lastPinged; - } - - @Override - public String getParent() { - return parent; - } - + public long getLastPinged() { + return lastPinged; + } + @Override - public long getTotalSize() { - return totalSize; - } - + public String getParent() { + return parent; + } + @Override - public String getCapabilities() { - return caps; - } - - @Override - public Date getCreated() { - return created; - } - + public long getTotalSize() { + return totalSize; + } + @Override - public Date getRemoved() { - return removed; - } - + public String getCapabilities() { + return caps; + } + @Override - public String getVersion() { - return version; - } - - public void setType(Type type) { - this.type = type; - } - + public Date getCreated() { + return created; + } + @Override - public long getId() { - return id; - } - - @Override - public String getName() { - return name; - } - - @Override - public Status getStatus() { - return status; - } - - @Override - public long getDataCenterId() { - return dataCenterId; - } - - @Override - public Long getPodId() { - return podId; - } - + public Date getRemoved() { + return removed; + } + @Override - public Long getManagementServerId() { - return managementServerId; - } - + public String getVersion() { + return version; + } + + public void setType(Type type) { + this.type = type; + } + @Override - public Date getDisconnectedOn() { - return disconnectedOn; - } - - @Override - public String getPrivateIpAddress() { - return privateIpAddress; - } - - @Override - public String getGuid() { - return guid; - } - - public void setGuid(String guid) { - this.guid = guid; - } - + public long getId() { + return id; + } + @Override - public Integer getCpus() { - return cpus; - } - - @Override - public Long getSpeed() { - return speed; - } - - @Override - public Long getTotalMemory() { - return totalMemory; - } - - @Override - public Integer getProxyPort() { - return proxyPort; - } - - public void setProxyPort(Integer port) { - proxyPort = port; - } - - public StoragePoolType getFsType() { - return fsType; - } - - @Override - public Type getType() { - return type; - } - - @Override - public int hashCode() { - return NumbersUtil.hash(id); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof HostVO) { - return ((HostVO)obj).getId() == this.getId(); - } else { - return false; - } - } - - @Override - public String toString() { - return new StringBuilder("Host[").append("-").append(id).append("-").append(type).append("]").toString(); - } - - public void setHypervisorType(HypervisorType hypervisorType) { - this.hypervisorType = hypervisorType; - } - - @Override - public HypervisorType getHypervisorType() { - return hypervisorType; + public String getName() { + return name; + } + + @Override + public Status getStatus() { + return status; + } + + @Override + public long getDataCenterId() { + return dataCenterId; + } + + @Override + public Long getPodId() { + return podId; + } + + @Override + public Long getManagementServerId() { + return managementServerId; + } + + @Override + public Date getDisconnectedOn() { + return disconnectedOn; + } + + @Override + public String getPrivateIpAddress() { + return privateIpAddress; + } + + @Override + public String getGuid() { + return guid; + } + + public void setGuid(String guid) { + this.guid = guid; + } + + @Override + public Integer getCpus() { + return cpus; + } + + @Override + public Long getSpeed() { + return speed; + } + + @Override + public Long getTotalMemory() { + return totalMemory; + } + + @Override + public Integer getProxyPort() { + return proxyPort; + } + + public void setProxyPort(Integer port) { + proxyPort = port; + } + + public StoragePoolType getFsType() { + return fsType; + } + + @Override + public Type getType() { + return type; + } + + @Override + public int hashCode() { + return NumbersUtil.hash(id); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof HostVO) { + return ((HostVO)obj).getId() == this.getId(); + } else { + return false; + } + } + + @Override + public String toString() { + return new StringBuilder("Host[").append("-").append(id).append("-").append(type).append("]").toString(); + } + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + @Override + public HypervisorType getHypervisorType() { + return hypervisorType; } public void setHypervisorVersion(String hypervisorVersion) { @@ -724,4 +724,4 @@ public class HostVO implements Host, Identity { public void setUuid(String uuid) { this.uuid = uuid; } -} +} diff --git a/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java b/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java index 7084d8adb67..04dc1d952f8 100644 --- a/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java +++ b/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor; - +package com.cloud.hypervisor; + import java.util.UUID; import javax.persistence.Column; @@ -26,28 +26,28 @@ import javax.persistence.Table; import com.cloud.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.NumbersUtil; - -@Entity -@Table(name="hypervisor_capabilities") -public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - + +@Entity +@Table(name="hypervisor_capabilities") +public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + @Column(name="hypervisor_type") @Enumerated(value=EnumType.STRING) - private HypervisorType hypervisorType; - - @Column(name="hypervisor_version") - private String hypervisorVersion; - + private HypervisorType hypervisorType; + + @Column(name="hypervisor_version") + private String hypervisorVersion; + @Column(name="max_guests_limit") private Long maxGuestsLimit; - + @Column(name="security_group_enabled") private boolean securityGroupEnabled; - + @Column(name="uuid") private String uuid; @@ -62,7 +62,7 @@ public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identit this.securityGroupEnabled = securityGroupEnabled; this.uuid = UUID.randomUUID().toString(); } - + /** * @param hypervisorType the hypervisorType to set */ @@ -122,13 +122,13 @@ public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identit } - public long getId() { - return id; - } - - @Override - public int hashCode() { - return NumbersUtil.hash(id); + public long getId() { + return id; + } + + @Override + public int hashCode() { + return NumbersUtil.hash(id); } @Override @@ -138,15 +138,15 @@ public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identit public void setUuid(String uuid) { this.uuid = uuid; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof HypervisorCapabilitiesVO) { - return ((HypervisorCapabilitiesVO)obj).getId() == this.getId(); - } else { - return false; - } - } - -} + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof HypervisorCapabilitiesVO) { + return ((HypervisorCapabilitiesVO)obj).getId() == this.getId(); + } else { + return false; + } + } + +} diff --git a/core/src/com/cloud/hypervisor/vmware/manager/VmwareManager.java b/core/src/com/cloud/hypervisor/vmware/manager/VmwareManager.java index bf2d4aeac01..67c0e6fffa3 100755 --- a/core/src/com/cloud/hypervisor/vmware/manager/VmwareManager.java +++ b/core/src/com/cloud/hypervisor/vmware/manager/VmwareManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.manager; - +package com.cloud.hypervisor.vmware.manager; + import java.io.File; import java.util.List; import java.util.Map; @@ -21,14 +21,14 @@ import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.Pair; import com.vmware.vim25.ManagedObjectReference; - -public interface VmwareManager { + +public interface VmwareManager { public final String CONTEXT_STOCK_NAME = "vmwareMgr"; // this limitation comes from the fact that we are using linked clone on shared VMFS storage, // we need to limit the size of vCenter cluster, http://en.wikipedia.org/wiki/VMware_VMFS - public final int MAX_HOSTS_PER_CLUSTER = 8; - + public final int MAX_HOSTS_PER_CLUSTER = 8; + String composeWorkerName(); String getSystemVMIsoFileNameOnDatastore(); @@ -39,25 +39,25 @@ public interface VmwareManager { void setupResourceStartupParams(Map params); List addHostToPodCluster(VmwareContext serviceContext, long dcId, Long podId, Long clusterId, String hostInventoryPath) throws Exception; - + String getManagementPortGroupByHost(HostMO hostMo) throws Exception; String getServiceConsolePortGroupName(); String getManagementPortGroupName(); - + String getSecondaryStorageStoreUrl(long dcId); - - File getSystemVMKeyFile(); - + + File getSystemVMKeyFile(); + VmwareStorageManager getStorageManager(); long pushCleanupCheckpoint(String hostGuid, String vmName); void popCleanupCheckpoint(long checkpiont); - void gcLeftOverVMs(VmwareContext context); + void gcLeftOverVMs(VmwareContext context); Pair getAddiionalVncPortRange(); int getMaxHostsPerCluster(); int getRouterExtraPublicNics(); - - boolean beginExclusiveOperation(int timeOutSeconds); + + boolean beginExclusiveOperation(int timeOutSeconds); void endExclusiveOperation(); -} +} diff --git a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java index 6e51989139f..b2372915f7e 100644 --- a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java +++ b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManager.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.manager; - +package com.cloud.hypervisor.vmware.manager; + import com.cloud.agent.api.Answer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; @@ -19,12 +19,12 @@ import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; - -public interface VmwareStorageManager { - Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd); - Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd); - Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd); - Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromSnapshotCommand cmd); - Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd); - Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd); -} + +public interface VmwareStorageManager { + Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd); + Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd); + Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd); + Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromSnapshotCommand cmd); + Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd); + Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd); +} diff --git a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java index 3da2bb84ada..7f5d6b8c9c7 100644 --- a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java +++ b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.manager; - +package com.cloud.hypervisor.vmware.manager; + import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; @@ -61,129 +61,129 @@ import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineFileInfo; import com.vmware.vim25.VirtualMachineGuestOsIdentifier; import com.vmware.vim25.VirtualSCSISharing; - -public class VmwareStorageManagerImpl implements VmwareStorageManager { - private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class); - - private final VmwareStorageMount _mountService; - private final StorageLayer _storage = new JavaStorageLayer(); - - private int _timeout; - - public VmwareStorageManagerImpl(VmwareStorageMount mountService) { - assert(mountService != null); - _mountService = mountService; - } - - public void configure(Map params) { - s_logger.info("Configure VmwareStorageManagerImpl"); - - String value = (String)params.get("scripts.timeout"); - _timeout = NumbersUtil.parseInt(value, 1440) * 1000; - } - - @Override - public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) { - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - assert (secondaryStorageUrl != null); - - String templateUrl = cmd.getUrl(); - - String templateName = null; - String mountPoint = null; - if (templateUrl.endsWith(".ova")) { - int index = templateUrl.lastIndexOf("/"); - mountPoint = templateUrl.substring(0, index); - mountPoint = mountPoint.substring(secondaryStorageUrl.length() + 1); - if (!mountPoint.endsWith("/")) { - mountPoint = mountPoint + "/"; - } - - templateName = templateUrl.substring(index + 1).replace("." + ImageFormat.OVA.getFileExtension(), ""); - - if (templateName == null || templateName.isEmpty()) { - templateName = cmd.getName(); - } - } else { - mountPoint = templateUrl.substring(secondaryStorageUrl.length() + 1); - if (!mountPoint.endsWith("/")) { - mountPoint = mountPoint + "/"; - } - templateName = cmd.getName(); - } - - VmwareContext context = hostService.getServiceContext(cmd); - try { + +public class VmwareStorageManagerImpl implements VmwareStorageManager { + private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class); + + private final VmwareStorageMount _mountService; + private final StorageLayer _storage = new JavaStorageLayer(); + + private int _timeout; + + public VmwareStorageManagerImpl(VmwareStorageMount mountService) { + assert(mountService != null); + _mountService = mountService; + } + + public void configure(Map params) { + s_logger.info("Configure VmwareStorageManagerImpl"); + + String value = (String)params.get("scripts.timeout"); + _timeout = NumbersUtil.parseInt(value, 1440) * 1000; + } + + @Override + public Answer execute(VmwareHostService hostService, PrimaryStorageDownloadCommand cmd) { + String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); + assert (secondaryStorageUrl != null); + + String templateUrl = cmd.getUrl(); + + String templateName = null; + String mountPoint = null; + if (templateUrl.endsWith(".ova")) { + int index = templateUrl.lastIndexOf("/"); + mountPoint = templateUrl.substring(0, index); + mountPoint = mountPoint.substring(secondaryStorageUrl.length() + 1); + if (!mountPoint.endsWith("/")) { + mountPoint = mountPoint + "/"; + } + + templateName = templateUrl.substring(index + 1).replace("." + ImageFormat.OVA.getFileExtension(), ""); + + if (templateName == null || templateName.isEmpty()) { + templateName = cmd.getName(); + } + } else { + mountPoint = templateUrl.substring(secondaryStorageUrl.length() + 1); + if (!mountPoint.endsWith("/")) { + mountPoint = mountPoint + "/"; + } + templateName = cmd.getName(); + } + + VmwareContext context = hostService.getServiceContext(cmd); + try { VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - + String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + cmd.getPoolUuid() + "-" + hyperHost.getMor().get_value()).getBytes()).toString(); // truncate template name to 32 chars to ensure they work well with vSphere API's. templateUuidName = templateUuidName.replace("-", ""); - + DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true); - - if (templateMo == null) { - if(s_logger.isInfoEnabled()) - s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName); - ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getPoolUuid()); + + if (templateMo == null) { + if(s_logger.isInfoEnabled()) + s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName); + ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getPoolUuid()); assert (morDs != null); - DatastoreMO primaryStorageDatastoreMo = new DatastoreMO(context, morDs); - - copyTemplateFromSecondaryToPrimary(hyperHost, - primaryStorageDatastoreMo, secondaryStorageUrl, - mountPoint, templateName, templateUuidName); + DatastoreMO primaryStorageDatastoreMo = new DatastoreMO(context, morDs); + + copyTemplateFromSecondaryToPrimary(hyperHost, + primaryStorageDatastoreMo, secondaryStorageUrl, + mountPoint, templateName, templateUuidName); } else { s_logger.info("Template " + templateName + " has already been setup, skip the template setup process in primary storage"); - } - - return new PrimaryStorageDownloadAnswer(templateUuidName, 0); - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } - - String msg = "Unable to execute PrimaryStorageDownloadCommand due to exception"; - s_logger.error(msg, e); - return new PrimaryStorageDownloadAnswer(msg); - } + } + + return new PrimaryStorageDownloadAnswer(templateUuidName, 0); + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + String msg = "Unable to execute PrimaryStorageDownloadCommand due to exception"; + s_logger.error(msg, e); + return new PrimaryStorageDownloadAnswer(msg); + } } - @Override - public Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd) { - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); + @Override + public Answer execute(VmwareHostService hostService, BackupSnapshotCommand cmd) { + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition. - String prevSnapshotUuid = cmd.getPrevSnapshotUuid(); - String prevBackupUuid = cmd.getPrevBackupUuid(); + String snapshotUuid = cmd.getSnapshotUuid(); // not null: Precondition. + String prevSnapshotUuid = cmd.getPrevSnapshotUuid(); + String prevBackupUuid = cmd.getPrevBackupUuid(); VirtualMachineMO workerVm=null; String workerVMName = null; String volumePath = cmd.getVolumePath(); ManagedObjectReference morDs = null; String snapshotUUID = null; DatastoreMO dsMo=null; - - // By default assume failure - String details = null; - boolean success = false; - String snapshotBackupUuid = null; - + + // By default assume failure + String details = null; + boolean success = false; + String snapshotBackupUuid = null; + VmwareContext context = hostService.getServiceContext(cmd); VirtualMachineMO vmMo = null; - - try { - VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); + + try { + VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); morDs = hyperHost.findDatastore(cmd.getPool().getUuid()); - try { - vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); - if (vmMo == null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter"); - - vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); - if(vmMo == null) { + try { + vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + if (vmMo == null) { + if(s_logger.isDebugEnabled()) + s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter"); + + vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); + if(vmMo == null) { dsMo = new DatastoreMO(hyperHost.getContext(), morDs); workerVMName = hostService.getWorkerName(context, cmd, 0); @@ -206,8 +206,8 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { snapshotUUID = UUID.randomUUID().toString(); if (!vmMo.createSnapshot(snapshotUUID, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) { throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName()); - } - } + } + } } else { if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) { throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName()); @@ -235,206 +235,206 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { } catch (Throwable e) { s_logger.warn("Failed to destroy worker VM: " + workerVMName); } - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } - - s_logger.error("Unexpecpted exception ", e); - - details = "BackupSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); - return new BackupSnapshotAnswer(cmd, false, details, snapshotBackupUuid, true); - } - - return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid, true); - } - - @Override - public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd) { + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + s_logger.error("Unexpecpted exception ", e); + + details = "BackupSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); + return new BackupSnapshotAnswer(cmd, false, details, snapshotBackupUuid, true); + } + + return new BackupSnapshotAnswer(cmd, success, details, snapshotBackupUuid, true); + } + + @Override + public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromVolumeCommand cmd) { String secondaryStoragePoolURL = cmd.getSecondaryStorageUrl(); - String volumePath = cmd.getVolumePath(); - Long accountId = cmd.getAccountId(); - Long templateId = cmd.getTemplateId(); - String details = null; - - VmwareContext context = hostService.getServiceContext(cmd); - try { - VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); - if (vmMo == null) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); - vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); - - if(vmMo == null) { - String msg = "Unable to find the owner VM for volume operation. vm: " + cmd.getVmName(); - s_logger.error(msg); - throw new Exception(msg); - } - } - - Ternary result = createTemplateFromVolume(vmMo, - accountId, templateId, cmd.getUniqueName(), - secondaryStoragePoolURL, volumePath, - hostService.getWorkerName(context, cmd, 0)); - - return new CreatePrivateTemplateAnswer(cmd, true, null, - result.first(), result.third(), result.second(), - cmd.getUniqueName(), ImageFormat.OVA); - - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } - - s_logger.error("Unexpecpted exception ", e); - - details = "CreatePrivateTemplateFromVolumeCommand exception: " + StringUtils.getExceptionStackInfo(e); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - } - - @Override - public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromSnapshotCommand cmd) { - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); + String volumePath = cmd.getVolumePath(); + Long accountId = cmd.getAccountId(); + Long templateId = cmd.getTemplateId(); + String details = null; + + VmwareContext context = hostService.getServiceContext(cmd); + try { + VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + if (vmMo == null) { + if(s_logger.isDebugEnabled()) + s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); + vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); + + if(vmMo == null) { + String msg = "Unable to find the owner VM for volume operation. vm: " + cmd.getVmName(); + s_logger.error(msg); + throw new Exception(msg); + } + } + + Ternary result = createTemplateFromVolume(vmMo, + accountId, templateId, cmd.getUniqueName(), + secondaryStoragePoolURL, volumePath, + hostService.getWorkerName(context, cmd, 0)); + + return new CreatePrivateTemplateAnswer(cmd, true, null, + result.first(), result.third(), result.second(), + cmd.getUniqueName(), ImageFormat.OVA); + + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + s_logger.error("Unexpecpted exception ", e); + + details = "CreatePrivateTemplateFromVolumeCommand exception: " + StringUtils.getExceptionStackInfo(e); + return new CreatePrivateTemplateAnswer(cmd, false, details); + } + } + + @Override + public Answer execute(VmwareHostService hostService, CreatePrivateTemplateFromSnapshotCommand cmd) { + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String backedUpSnapshotUuid = cmd.getSnapshotUuid(); - Long newTemplateId = cmd.getNewTemplateId(); - String details; - String uniqeName = UUID.randomUUID().toString(); - - VmwareContext context = hostService.getServiceContext(cmd); - try { - Ternary result = createTemplateFromSnapshot(accountId, + String backedUpSnapshotUuid = cmd.getSnapshotUuid(); + Long newTemplateId = cmd.getNewTemplateId(); + String details; + String uniqeName = UUID.randomUUID().toString(); + + VmwareContext context = hostService.getServiceContext(cmd); + try { + Ternary result = createTemplateFromSnapshot(accountId, newTemplateId, uniqeName, secondaryStorageUrl, volumeId, - backedUpSnapshotUuid); - - return new CreatePrivateTemplateAnswer(cmd, true, null, - result.first(), result.third(), result.second(), - uniqeName, ImageFormat.OVA); - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } - - s_logger.error("Unexpecpted exception ", e); - - details = "CreatePrivateTemplateFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - } - - @Override - public Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd) { - Long volumeId = cmd.getVolumeId(); - String volumePath = cmd.getVolumePath(); - String secondaryStorageURL = cmd.getSecondaryStorageURL(); - String vmName = cmd.getVmName(); - - VmwareContext context = hostService.getServiceContext(cmd); - try { - VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - - Pair result; - if (cmd.toSecondaryStorage()) { - result = copyVolumeToSecStorage(hostService, - hyperHost, cmd, vmName, volumeId, cmd.getPool().getUuid(), volumePath, - secondaryStorageURL, - hostService.getWorkerName(context, cmd, 0)); - } else { - StorageFilerTO poolTO = cmd.getPool(); - - ManagedObjectReference morDatastore = hyperHost.findDatastore(poolTO.getUuid()); - if (morDatastore == null) { - morDatastore = hyperHost.mountDatastore( - false, - poolTO.getHost(), 0, poolTO.getPath(), - poolTO.getUuid()); - - if (morDatastore == null) { - throw new Exception("Unable to mount storage pool on host. storeUrl: " + poolTO.getHost() + ":/" + poolTO.getPath()); - } - } - - result = copyVolumeFromSecStorage( - hyperHost, volumeId, - new DatastoreMO(context, morDatastore), - secondaryStorageURL, volumePath); - } - return new CopyVolumeAnswer(cmd, true, null, result.first(), result.second()); - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } + backedUpSnapshotUuid); - String msg = "Unable to execute CopyVolumeCommand due to exception"; - s_logger.error(msg, e); - return new CopyVolumeAnswer(cmd, false, "CopyVolumeCommand failed due to exception: " + StringUtils.getExceptionStackInfo(e), null, null); - } - } - - @Override - public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) { - - String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); - Long accountId = cmd.getAccountId(); - Long volumeId = cmd.getVolumeId(); - String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); - String backedUpSnapshotUuid = cmd.getSnapshotUuid(); - - String details = null; - boolean success = false; - String newVolumeName = UUID.randomUUID().toString().replaceAll("-", ""); - - VmwareContext context = hostService.getServiceContext(cmd); - try { - VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); - - ManagedObjectReference morPrimaryDs = hyperHost.findDatastore(primaryStorageNameLabel); - if (morPrimaryDs == null) { - String msg = "Unable to find datastore: " + primaryStorageNameLabel; - s_logger.error(msg); - throw new Exception(msg); - } - - DatastoreMO primaryDsMo = new DatastoreMO(hyperHost.getContext(), morPrimaryDs); - details = createVolumeFromSnapshot(hyperHost, primaryDsMo, - newVolumeName, accountId, volumeId, secondaryStorageUrl, backedUpSnapshotUuid); - if (details == null) { - success = true; - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - hostService.invalidateServiceContext(context); - } - - s_logger.error("Unexpecpted exception ", e); - details = "CreateVolumeFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); - } - - return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); - } + return new CreatePrivateTemplateAnswer(cmd, true, null, + result.first(), result.third(), result.second(), + uniqeName, ImageFormat.OVA); + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + s_logger.error("Unexpecpted exception ", e); + + details = "CreatePrivateTemplateFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); + return new CreatePrivateTemplateAnswer(cmd, false, details); + } + } + + @Override + public Answer execute(VmwareHostService hostService, CopyVolumeCommand cmd) { + Long volumeId = cmd.getVolumeId(); + String volumePath = cmd.getVolumePath(); + String secondaryStorageURL = cmd.getSecondaryStorageURL(); + String vmName = cmd.getVmName(); + + VmwareContext context = hostService.getServiceContext(cmd); + try { + VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); + + Pair result; + if (cmd.toSecondaryStorage()) { + result = copyVolumeToSecStorage(hostService, + hyperHost, cmd, vmName, volumeId, cmd.getPool().getUuid(), volumePath, + secondaryStorageURL, + hostService.getWorkerName(context, cmd, 0)); + } else { + StorageFilerTO poolTO = cmd.getPool(); + + ManagedObjectReference morDatastore = hyperHost.findDatastore(poolTO.getUuid()); + if (morDatastore == null) { + morDatastore = hyperHost.mountDatastore( + false, + poolTO.getHost(), 0, poolTO.getPath(), + poolTO.getUuid()); + + if (morDatastore == null) { + throw new Exception("Unable to mount storage pool on host. storeUrl: " + poolTO.getHost() + ":/" + poolTO.getPath()); + } + } + + result = copyVolumeFromSecStorage( + hyperHost, volumeId, + new DatastoreMO(context, morDatastore), + secondaryStorageURL, volumePath); + } + return new CopyVolumeAnswer(cmd, true, null, result.first(), result.second()); + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + String msg = "Unable to execute CopyVolumeCommand due to exception"; + s_logger.error(msg, e); + return new CopyVolumeAnswer(cmd, false, "CopyVolumeCommand failed due to exception: " + StringUtils.getExceptionStackInfo(e), null, null); + } + } + + @Override + public Answer execute(VmwareHostService hostService, CreateVolumeFromSnapshotCommand cmd) { + + String primaryStorageNameLabel = cmd.getPrimaryStoragePoolNameLabel(); + Long accountId = cmd.getAccountId(); + Long volumeId = cmd.getVolumeId(); + String secondaryStorageUrl = cmd.getSecondaryStorageUrl(); + String backedUpSnapshotUuid = cmd.getSnapshotUuid(); + + String details = null; + boolean success = false; + String newVolumeName = UUID.randomUUID().toString().replaceAll("-", ""); + + VmwareContext context = hostService.getServiceContext(cmd); + try { + VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd); + + ManagedObjectReference morPrimaryDs = hyperHost.findDatastore(primaryStorageNameLabel); + if (morPrimaryDs == null) { + String msg = "Unable to find datastore: " + primaryStorageNameLabel; + s_logger.error(msg); + throw new Exception(msg); + } + + DatastoreMO primaryDsMo = new DatastoreMO(hyperHost.getContext(), morPrimaryDs); + details = createVolumeFromSnapshot(hyperHost, primaryDsMo, + newVolumeName, accountId, volumeId, secondaryStorageUrl, backedUpSnapshotUuid); + if (details == null) { + success = true; + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + hostService.invalidateServiceContext(context); + } + + s_logger.error("Unexpecpted exception ", e); + details = "CreateVolumeFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e); + } + + return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); + } // templateName: name in secondary storage // templateUuid: will be used at hypervisor layer - private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl, - String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception { - - s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: " - + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage - + ", templateName: " + templateName); - - String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl); - s_logger.info("Secondary storage mount point: " + secondaryMountPoint); - - String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage + - templateName + "." + ImageFormat.OVA.getFileExtension(); - - String srcFileName = getOVFFilePath(srcOVAFileName); + private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl, + String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception { + + s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: " + + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + + ", templateName: " + templateName); + + String secondaryMountPoint = _mountService.getMountPoint(secondaryStorageUrl); + s_logger.info("Secondary storage mount point: " + secondaryMountPoint); + + String srcOVAFileName = secondaryMountPoint + "/" + templatePathAtSecondaryStorage + + templateName + "." + ImageFormat.OVA.getFileExtension(); + + String srcFileName = getOVFFilePath(srcOVAFileName); if(srcFileName == null) { Script command = new Script("tar", 0, s_logger); command.add("--no-same-owner"); @@ -451,81 +451,81 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { srcFileName = getOVFFilePath(srcOVAFileName); if(srcFileName == null) { - String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; - s_logger.error(msg); - throw new Exception(msg); + String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; + s_logger.error(msg); + throw new Exception(msg); } - String vmName = templateUuid; - hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin"); - - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); - if(vmMo == null) { - String msg = "Failed to import OVA template. secondaryStorage: " - + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage - + ", templateName: " + templateName + ", templateUuid: " + templateUuid; - s_logger.error(msg); - throw new Exception(msg); + String vmName = templateUuid; + hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin"); + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); + if(vmMo == null) { + String msg = "Failed to import OVA template. secondaryStorage: " + + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage + + ", templateName: " + templateName + ", templateUuid: " + templateUuid; + s_logger.error(msg); + throw new Exception(msg); } - - if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) { + + if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, templateUuid); - vmMo.markAsTemplate(); - } else { - vmMo.destroy(); - String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid; - s_logger.error(msg); - throw new Exception(msg); - } - } - - private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, - String secStorageUrl, String volumePath, String workerVmName) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); - String installFullPath = secondaryMountPoint + "/" + installPath; - synchronized(installPath.intern()) { - Script command = new Script(false, "mkdir", _timeout, s_logger); - command.add("-p"); - command.add(installFullPath); - - String result = command.execute(); - if(result != null) { - String msg = "unable to prepare template directory: " - + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; - s_logger.error(msg); - throw new Exception(msg); - } - } - - VirtualMachineMO clonedVm = null; - try { - Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); - if(volumeDeviceInfo == null) { - String msg = "Unable to find related disk device for volume. volume path: " + volumePath; - s_logger.error(msg); - throw new Exception(msg); - } - - if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) { - String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath; - s_logger.error(msg); - throw new Exception(msg); - } - - // 4 MB is the minimum requirement for VM memory in VMware - vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), - VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); - clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); - if(clonedVm == null) { - String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath; - s_logger.error(msg); - throw new Exception(msg); - } - - clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false); - + vmMo.markAsTemplate(); + } else { + vmMo.destroy(); + String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid; + s_logger.error(msg); + throw new Exception(msg); + } + } + + private Ternary createTemplateFromVolume(VirtualMachineMO vmMo, long accountId, long templateId, String templateUniqueName, + String secStorageUrl, String volumePath, String workerVmName) throws Exception { + + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); + String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); + String installFullPath = secondaryMountPoint + "/" + installPath; + synchronized(installPath.intern()) { + Script command = new Script(false, "mkdir", _timeout, s_logger); + command.add("-p"); + command.add(installFullPath); + + String result = command.execute(); + if(result != null) { + String msg = "unable to prepare template directory: " + + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; + s_logger.error(msg); + throw new Exception(msg); + } + } + + VirtualMachineMO clonedVm = null; + try { + Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); + if(volumeDeviceInfo == null) { + String msg = "Unable to find related disk device for volume. volume path: " + volumePath; + s_logger.error(msg); + throw new Exception(msg); + } + + if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) { + String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath; + s_logger.error(msg); + throw new Exception(msg); + } + + // 4 MB is the minimum requirement for VM memory in VMware + vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), + VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); + clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); + if(clonedVm == null) { + String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath; + s_logger.error(msg); + throw new Exception(msg); + } + + clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false); + long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); VmdkProcessor processor = new VmdkProcessor(); Map params = new HashMap(); @@ -534,69 +534,69 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); - return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); - - } finally { + return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); + + } finally { if(clonedVm != null) { - clonedVm.detachAllDisks(); + clonedVm.detachAllDisks(); clonedVm.destroy(); - } - - vmMo.removeSnapshot(templateUniqueName, false); - } - } - - private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName, - String secStorageUrl, long volumeId, String backedUpSnapshotUuid) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); - String installFullPath = secondaryMountPoint + "/" + installPath; - String installFullName = installFullPath + "/" + templateUniqueName + ".ova"; - String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId) - + "/" + backedUpSnapshotUuid + ".ova"; - String result; - Script command; - - synchronized(installPath.intern()) { - command = new Script(false, "mkdir", _timeout, s_logger); - command.add("-p"); - command.add(installFullPath); - - result = command.execute(); - if(result != null) { - String msg = "unable to prepare template directory: " - + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; - s_logger.error(msg); - throw new Exception(msg); - } - } - - try { - command = new Script(false, "cp", _timeout, s_logger); - command.add(snapshotFullName); - command.add(installFullName); - result = command.execute(); - if(result != null) { - String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath; - s_logger.error(msg); - throw new Exception(msg); - } - - // untar OVA file at template directory + } + + vmMo.removeSnapshot(templateUniqueName, false); + } + } + + private Ternary createTemplateFromSnapshot(long accountId, long templateId, String templateUniqueName, + String secStorageUrl, long volumeId, String backedUpSnapshotUuid) throws Exception { + + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); + String installPath = getTemplateRelativeDirInSecStorage(accountId, templateId); + String installFullPath = secondaryMountPoint + "/" + installPath; + String installFullName = installFullPath + "/" + templateUniqueName + ".ova"; + String snapshotFullName = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId) + + "/" + backedUpSnapshotUuid + ".ova"; + String result; + Script command; + + synchronized(installPath.intern()) { + command = new Script(false, "mkdir", _timeout, s_logger); + command.add("-p"); + command.add(installFullPath); + + result = command.execute(); + if(result != null) { + String msg = "unable to prepare template directory: " + + installPath + ", storage: " + secStorageUrl + ", error msg: " + result; + s_logger.error(msg); + throw new Exception(msg); + } + } + + try { + command = new Script(false, "cp", _timeout, s_logger); + command.add(snapshotFullName); + command.add(installFullName); + result = command.execute(); + if(result != null) { + String msg = "unable to copy snapshot " + snapshotFullName + " to " + installFullPath; + s_logger.error(msg); + throw new Exception(msg); + } + + // untar OVA file at template directory command = new Script("tar", 0, s_logger); - command.add("--no-same-owner"); - command.add("-xf", installFullName); - command.setWorkDir(installFullPath); + command.add("--no-same-owner"); + command.add("-xf", installFullName); + command.setWorkDir(installFullPath); s_logger.info("Executing command: " + command.toString()); result = command.execute(); - if(result != null) { + if(result != null) { String msg = "unable to untar snapshot " + snapshotFullName + " to " - + installFullPath; - s_logger.error(msg); - throw new Exception(msg); - } - + + installFullPath; + s_logger.error(msg); + throw new Exception(msg); + } + long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length(); VmdkProcessor processor = new VmdkProcessor(); Map params = new HashMap(); @@ -605,183 +605,183 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName); postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize); - return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); - - } catch(Exception e) { - // TODO, clean up left over files - throw e; - } - } - - private void postCreatePrivateTemplate(String installFullPath, long templateId, - String templateName, long size, long virtualSize) throws Exception { - - // TODO a bit ugly here - BufferedWriter out = null; - try { - out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties"))); - out.write("filename=" + templateName + ".ova"); - out.newLine(); - out.write("description="); - out.newLine(); - out.write("checksum="); - out.newLine(); - out.write("hvm=false"); - out.newLine(); - out.write("size=" + size); - out.newLine(); - out.write("ova=true"); - out.newLine(); - out.write("id=" + templateId); - out.newLine(); - out.write("public=false"); - out.newLine(); - out.write("ova.filename=" + templateName + ".ova"); - out.newLine(); - out.write("uniquename=" + templateName); - out.newLine(); - out.write("ova.virtualsize=" + virtualSize); - out.newLine(); - out.write("virtualsize=" + virtualSize); - out.newLine(); - out.write("ova.size=" + size); - out.newLine(); - } finally { - if(out != null) - out.close(); - } - } - - private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, - long accountId, long volumeId, String secStorageUrl, String snapshotBackupUuid) throws Exception { - - restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName, - secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid); - return null; - } - - private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, - String secStorageUrl, String secStorageDir, String backupName) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/" - + backupName + "." + ImageFormat.OVA.getFileExtension(); - - String srcFileName = getOVFFilePath(srcOVAFileName); - if(srcFileName == null) { - Script command = new Script("tar", 0, s_logger); + return new Ternary(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize); + + } catch(Exception e) { + // TODO, clean up left over files + throw e; + } + } + + private void postCreatePrivateTemplate(String installFullPath, long templateId, + String templateName, long size, long virtualSize) throws Exception { + + // TODO a bit ugly here + BufferedWriter out = null; + try { + out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties"))); + out.write("filename=" + templateName + ".ova"); + out.newLine(); + out.write("description="); + out.newLine(); + out.write("checksum="); + out.newLine(); + out.write("hvm=false"); + out.newLine(); + out.write("size=" + size); + out.newLine(); + out.write("ova=true"); + out.newLine(); + out.write("id=" + templateId); + out.newLine(); + out.write("public=false"); + out.newLine(); + out.write("ova.filename=" + templateName + ".ova"); + out.newLine(); + out.write("uniquename=" + templateName); + out.newLine(); + out.write("ova.virtualsize=" + virtualSize); + out.newLine(); + out.write("virtualsize=" + virtualSize); + out.newLine(); + out.write("ova.size=" + size); + out.newLine(); + } finally { + if(out != null) + out.close(); + } + } + + private String createVolumeFromSnapshot(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, + long accountId, long volumeId, String secStorageUrl, String snapshotBackupUuid) throws Exception { + + restoreVolumeFromSecStorage(hyperHost, primaryDsMo, newVolumeName, + secStorageUrl, getSnapshotRelativeDirInSecStorage(accountId, volumeId), snapshotBackupUuid); + return null; + } + + private void restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName, + String secStorageUrl, String secStorageDir, String backupName) throws Exception { + + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); + String srcOVAFileName = secondaryMountPoint + "/" + secStorageDir + "/" + + backupName + "." + ImageFormat.OVA.getFileExtension(); + + String srcFileName = getOVFFilePath(srcOVAFileName); + if(srcFileName == null) { + Script command = new Script("tar", 0, s_logger); command.add("--no-same-owner"); - command.add("-xf", srcOVAFileName); + command.add("-xf", srcOVAFileName); command.setWorkDir(secondaryMountPoint + "/" + secStorageDir); s_logger.info("Executing command: " + command.toString()); - String result = command.execute(); - if(result != null) { - String msg = "Unable to unpack snapshot OVA file at: " + srcOVAFileName; - s_logger.error(msg); - throw new Exception(msg); - } - } - - srcFileName = getOVFFilePath(srcOVAFileName); - if(srcFileName == null) { - String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; - s_logger.error(msg); - throw new Exception(msg); - } - - VirtualMachineMO clonedVm = null; - try { - hyperHost.importVmFromOVF(srcFileName, newVolumeName, primaryDsMo, "thin"); - clonedVm = hyperHost.findVmOnHyperHost(newVolumeName); - if(clonedVm == null) - throw new Exception("Unable to create container VM for volume creation"); - - clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false); - clonedVm.detachAllDisks(); - } finally { + String result = command.execute(); + if(result != null) { + String msg = "Unable to unpack snapshot OVA file at: " + srcOVAFileName; + s_logger.error(msg); + throw new Exception(msg); + } + } + + srcFileName = getOVFFilePath(srcOVAFileName); + if(srcFileName == null) { + String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName; + s_logger.error(msg); + throw new Exception(msg); + } + + VirtualMachineMO clonedVm = null; + try { + hyperHost.importVmFromOVF(srcFileName, newVolumeName, primaryDsMo, "thin"); + clonedVm = hyperHost.findVmOnHyperHost(newVolumeName); + if(clonedVm == null) + throw new Exception("Unable to create container VM for volume creation"); + + clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false); + clonedVm.detachAllDisks(); + } finally { if(clonedVm != null) { - clonedVm.detachAllDisks(); + clonedVm.detachAllDisks(); clonedVm.destroy(); - } - } - } - - private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, - String volumePath, String snapshotUuid, String secStorageUrl, - String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception { - - String backupUuid = UUID.randomUUID().toString(); - exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, - getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName); - return backupUuid; - } - - private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath, - String secStorageUrl, String secStorageDir, String exportName, - String workerVmName) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String exportPath = secondaryMountPoint + "/" + secStorageDir; - - synchronized(exportPath.intern()) { - if(!new File(exportPath).exists()) { - Script command = new Script(false, "mkdir", _timeout, s_logger); - command.add("-p"); - command.add(exportPath); - if(command.execute() != null) - throw new Exception("unable to prepare snapshot backup directory"); - } - } - - VirtualMachineMO clonedVm = null; - try { - - Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); - if(volumeDeviceInfo == null) { - String msg = "Unable to find related disk device for volume. volume path: " + volumePath; - s_logger.error(msg); - throw new Exception(msg); - } - - // 4 MB is the minimum requirement for VM memory in VMware - vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), - VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); - clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); - if(clonedVm == null) { - String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath; - s_logger.error(msg); - throw new Exception(msg); - } - - clonedVm.exportVm(exportPath, exportName, true, true); - } finally { + } + } + } + + private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, long accountId, long volumeId, + String volumePath, String snapshotUuid, String secStorageUrl, + String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception { + + String backupUuid = UUID.randomUUID().toString(); + exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, + getSnapshotRelativeDirInSecStorage(accountId, volumeId), backupUuid, workerVmName); + return backupUuid; + } + + private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath, + String secStorageUrl, String secStorageDir, String exportName, + String workerVmName) throws Exception { + + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); + String exportPath = secondaryMountPoint + "/" + secStorageDir; + + synchronized(exportPath.intern()) { + if(!new File(exportPath).exists()) { + Script command = new Script(false, "mkdir", _timeout, s_logger); + command.add("-p"); + command.add(exportPath); + if(command.execute() != null) + throw new Exception("unable to prepare snapshot backup directory"); + } + } + + VirtualMachineMO clonedVm = null; + try { + + Pair volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false); + if(volumeDeviceInfo == null) { + String msg = "Unable to find related disk device for volume. volume path: " + volumePath; + s_logger.error(msg); + throw new Exception(msg); + } + + // 4 MB is the minimum requirement for VM memory in VMware + vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(), + VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first())); + clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName); + if(clonedVm == null) { + String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath; + s_logger.error(msg); + throw new Exception(msg); + } + + clonedVm.exportVm(exportPath, exportName, true, true); + } finally { if(clonedVm != null) { - clonedVm.detachAllDisks(); + clonedVm.detachAllDisks(); clonedVm.destroy(); - } - } - } - - private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception { - - String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); - String snapshotMountRoot = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId); - File file = new File(snapshotMountRoot + "/" + backupUuid + ".ova"); - if(file.exists()) { - if(file.delete()) - return null; - - } else { - return "Backup file does not exist. backupUuid: " + backupUuid; - } - - return "Failed to delete snapshot backup file, backupUuid: " + backupUuid; - } - + } + } + } + + private String deleteSnapshotOnSecondaryStorge(long accountId, long volumeId, String secStorageUrl, String backupUuid) throws Exception { + + String secondaryMountPoint = _mountService.getMountPoint(secStorageUrl); + String snapshotMountRoot = secondaryMountPoint + "/" + getSnapshotRelativeDirInSecStorage(accountId, volumeId); + File file = new File(snapshotMountRoot + "/" + backupUuid + ".ova"); + if(file.exists()) { + if(file.delete()) + return null; + + } else { + return "Backup file does not exist. backupUuid: " + backupUuid; + } + + return "Failed to delete snapshot backup file, backupUuid: " + backupUuid; + } + private Pair copyVolumeToSecStorage(VmwareHostService hostService, VmwareHypervisorHost hyperHost, CopyVolumeCommand cmd, - String vmName, long volumeId, String poolId, String volumePath, + String vmName, long volumeId, String poolId, String volumePath, String secStorageUrl, String workerVmName) throws Exception { - + String volumeFolder = String.valueOf(volumeId) + "/"; VirtualMachineMO workerVm=null; VirtualMachineMO vmMo=null; @@ -795,7 +795,7 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { s_logger.error(msg); throw new Exception(msg); } - + vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { // create a dummy worker vm for attaching the volume @@ -833,53 +833,53 @@ public class VmwareStorageManagerImpl implements VmwareStorageManager { workerVm.attachDisk(new String[] { datastoreVolumePath }, morDs); vmMo = workerVm; } - - vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false); - + + vmMo.createSnapshot(exportName, "Temporary snapshot for copy-volume command", false, false); + exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl, "volumes/" + volumeFolder, exportName, - hostService.getWorkerName(hyperHost.getContext(), cmd, 1)); + hostService.getWorkerName(hyperHost.getContext(), cmd, 1)); return new Pair(volumeFolder, exportName); - - } finally { + + } finally { vmMo.removeSnapshot(exportName, false); if (workerVm != null) { //detach volume and destroy worker vm workerVm.detachAllDisks(); workerVm.destroy(); - } - } - } - - private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId, - DatastoreMO dsMo, String secStorageUrl, String exportName) throws Exception { - + } + } + } + + private Pair copyVolumeFromSecStorage(VmwareHypervisorHost hyperHost, long volumeId, + DatastoreMO dsMo, String secStorageUrl, String exportName) throws Exception { + String volumeFolder = String.valueOf(volumeId) + "/"; - String newVolume = UUID.randomUUID().toString().replaceAll("-", ""); - restoreVolumeFromSecStorage(hyperHost, dsMo, newVolume, secStorageUrl, "volumes/" + volumeFolder, exportName); - - return new Pair(volumeFolder, newVolume); - } - - private String getOVFFilePath(String srcOVAFileName) { - File file = new File(srcOVAFileName); - assert(_storage != null); - String[] files = _storage.listFiles(file.getParent()); - if(files != null) { - for(String fileName : files) { - if(fileName.toLowerCase().endsWith(".ovf")) { - File ovfFile = new File(fileName); - return file.getParent() + File.separator + ovfFile.getName(); - } - } - } - return null; - } - - private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) { - return "template/tmpl/" + accountId + "/" + templateId; - } - - private static String getSnapshotRelativeDirInSecStorage(long accountId, long volumeId) { - return "snapshots/" + accountId + "/" + volumeId; - } -} + String newVolume = UUID.randomUUID().toString().replaceAll("-", ""); + restoreVolumeFromSecStorage(hyperHost, dsMo, newVolume, secStorageUrl, "volumes/" + volumeFolder, exportName); + + return new Pair(volumeFolder, newVolume); + } + + private String getOVFFilePath(String srcOVAFileName) { + File file = new File(srcOVAFileName); + assert(_storage != null); + String[] files = _storage.listFiles(file.getParent()); + if(files != null) { + for(String fileName : files) { + if(fileName.toLowerCase().endsWith(".ovf")) { + File ovfFile = new File(fileName); + return file.getParent() + File.separator + ovfFile.getName(); + } + } + } + return null; + } + + private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) { + return "template/tmpl/" + accountId + "/" + templateId; + } + + private static String getSnapshotRelativeDirInSecStorage(long accountId, long volumeId) { + return "snapshots/" + accountId + "/" + volumeId; + } +} diff --git a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageMount.java b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageMount.java index 6fd62f9f3ac..9f4de50b9fd 100644 --- a/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageMount.java +++ b/core/src/com/cloud/hypervisor/vmware/manager/VmwareStorageMount.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.manager; - -public interface VmwareStorageMount { - String getMountPoint(String storageUrl); -} +package com.cloud.hypervisor.vmware.manager; + +public interface VmwareStorageMount { + String getMountPoint(String storageUrl); +} diff --git a/core/src/com/cloud/hypervisor/vmware/resource/SshHelper.java b/core/src/com/cloud/hypervisor/vmware/resource/SshHelper.java index 1d75711d27a..e85e9ca7a3a 100755 --- a/core/src/com/cloud/hypervisor/vmware/resource/SshHelper.java +++ b/core/src/com/cloud/hypervisor/vmware/resource/SshHelper.java @@ -10,146 +10,146 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.resource; - -import java.io.File; -import java.io.InputStream; - -import org.apache.log4j.Logger; - -import com.cloud.utils.Pair; -import com.trilead.ssh2.ChannelCondition; - -public class SshHelper { - private static int DEFAULT_CONNECT_TIMEOUT = 60000; - private static int DEFAULT_KEX_TIMEOUT = 60000; - - private static final Logger s_logger = Logger.getLogger(SshHelper.class); - - public static Pair sshExecute(String host, int port, String user, File pemKeyFile, String password, String command) - throws Exception { - - return sshExecute(host, port, user, pemKeyFile, password, command, 60000, 60000, 120000); - } - - public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, - String localFile, String fileMode) throws Exception { - - scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, localFile, fileMode, - DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT); - } - - public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, - byte[] data, String remoteFileName, String fileMode) throws Exception { - - scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, data, remoteFileName, fileMode, - DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT); - } - - public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, - String localFile, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception { - - com.trilead.ssh2.Connection conn = null; - com.trilead.ssh2.SCPClient scpClient = null; - - try { - conn = new com.trilead.ssh2.Connection(host, port); - conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); - - if(pemKeyFile == null) { - if(!conn.authenticateWithPassword(user, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } else { - if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } - - scpClient = conn.createSCPClient(); - - if(fileMode != null) - scpClient.put(localFile, remoteTargetDirectory, fileMode); - else - scpClient.put(localFile, remoteTargetDirectory); - } finally { - if(conn != null) - conn.close(); - } - } - - public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, - byte[] data, String remoteFileName, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception { - - com.trilead.ssh2.Connection conn = null; - com.trilead.ssh2.SCPClient scpClient = null; - - try { - conn = new com.trilead.ssh2.Connection(host, port); - conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); - - if(pemKeyFile == null) { - if(!conn.authenticateWithPassword(user, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } else { - if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } - - scpClient = conn.createSCPClient(); - if(fileMode != null) - scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode); - else - scpClient.put(data, remoteFileName, remoteTargetDirectory); - } finally { - if(conn != null) - conn.close(); - } - } - - public static Pair sshExecute(String host, int port, String user, File pemKeyFile, String password, String command, - int connectTimeoutInMs, int kexTimeoutInMs, int waitResultTimeoutInMs) throws Exception { - - com.trilead.ssh2.Connection conn = null; - com.trilead.ssh2.Session sess = null; - try { - conn = new com.trilead.ssh2.Connection(host, port); - conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); - - if(pemKeyFile == null) { - if(!conn.authenticateWithPassword(user, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } else { - if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { - String msg = "Failed to authentication SSH user " + user + " on host " + host; - s_logger.error(msg); - throw new Exception(msg); - } - } - sess = conn.openSession(); - - // There is a bug in Trilead library, wait a second before - // starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html - Thread.sleep(1000); - - sess.execCommand(command); - - InputStream stdout = sess.getStdout(); - InputStream stderr = sess.getStderr(); - +package com.cloud.hypervisor.vmware.resource; + +import java.io.File; +import java.io.InputStream; + +import org.apache.log4j.Logger; + +import com.cloud.utils.Pair; +import com.trilead.ssh2.ChannelCondition; + +public class SshHelper { + private static int DEFAULT_CONNECT_TIMEOUT = 60000; + private static int DEFAULT_KEX_TIMEOUT = 60000; + + private static final Logger s_logger = Logger.getLogger(SshHelper.class); + + public static Pair sshExecute(String host, int port, String user, File pemKeyFile, String password, String command) + throws Exception { + + return sshExecute(host, port, user, pemKeyFile, password, command, 60000, 60000, 120000); + } + + public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, + String localFile, String fileMode) throws Exception { + + scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, localFile, fileMode, + DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT); + } + + public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, + byte[] data, String remoteFileName, String fileMode) throws Exception { + + scpTo(host, port, user, pemKeyFile, password, remoteTargetDirectory, data, remoteFileName, fileMode, + DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT); + } + + public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, + String localFile, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception { + + com.trilead.ssh2.Connection conn = null; + com.trilead.ssh2.SCPClient scpClient = null; + + try { + conn = new com.trilead.ssh2.Connection(host, port); + conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); + + if(pemKeyFile == null) { + if(!conn.authenticateWithPassword(user, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } else { + if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } + + scpClient = conn.createSCPClient(); + + if(fileMode != null) + scpClient.put(localFile, remoteTargetDirectory, fileMode); + else + scpClient.put(localFile, remoteTargetDirectory); + } finally { + if(conn != null) + conn.close(); + } + } + + public static void scpTo(String host, int port, String user, File pemKeyFile, String password, String remoteTargetDirectory, + byte[] data, String remoteFileName, String fileMode, int connectTimeoutInMs, int kexTimeoutInMs) throws Exception { + + com.trilead.ssh2.Connection conn = null; + com.trilead.ssh2.SCPClient scpClient = null; + + try { + conn = new com.trilead.ssh2.Connection(host, port); + conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); + + if(pemKeyFile == null) { + if(!conn.authenticateWithPassword(user, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } else { + if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } + + scpClient = conn.createSCPClient(); + if(fileMode != null) + scpClient.put(data, remoteFileName, remoteTargetDirectory, fileMode); + else + scpClient.put(data, remoteFileName, remoteTargetDirectory); + } finally { + if(conn != null) + conn.close(); + } + } + + public static Pair sshExecute(String host, int port, String user, File pemKeyFile, String password, String command, + int connectTimeoutInMs, int kexTimeoutInMs, int waitResultTimeoutInMs) throws Exception { + + com.trilead.ssh2.Connection conn = null; + com.trilead.ssh2.Session sess = null; + try { + conn = new com.trilead.ssh2.Connection(host, port); + conn.connect(null, connectTimeoutInMs, kexTimeoutInMs); + + if(pemKeyFile == null) { + if(!conn.authenticateWithPassword(user, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } else { + if(!conn.authenticateWithPublicKey(user, pemKeyFile, password)) { + String msg = "Failed to authentication SSH user " + user + " on host " + host; + s_logger.error(msg); + throw new Exception(msg); + } + } + sess = conn.openSession(); + + // There is a bug in Trilead library, wait a second before + // starting a shell and executing commands, from http://spci.st.ewi.tudelft.nl/chiron/xref/nl/tudelft/swerl/util/SSHConnection.html + Thread.sleep(1000); + + sess.execCommand(command); + + InputStream stdout = sess.getStdout(); + InputStream stderr = sess.getStderr(); + byte[] buffer = new byte[8192]; StringBuffer sbResult = new StringBuffer(); @@ -190,12 +190,12 @@ public class SshHelper { } return new Pair(true, result); - } finally { - if(sess != null) - sess.close(); - - if(conn != null) - conn.close(); - } - } -} + } finally { + if(sess != null) + sess.close(); + + if(conn != null) + conn.close(); + } + } +} diff --git a/core/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java b/core/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java index d97c8e2b1e7..f82afb8d3f0 100755 --- a/core/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java +++ b/core/src/com/cloud/hypervisor/vmware/resource/VmwareContextFactory.java @@ -10,51 +10,51 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.resource; - +package com.cloud.hypervisor.vmware.resource; + import org.apache.log4j.Logger; -import com.cloud.hypervisor.vmware.manager.VmwareManager; -import com.cloud.hypervisor.vmware.util.VmwareContext; +import com.cloud.hypervisor.vmware.manager.VmwareManager; +import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.utils.StringUtils; -import com.cloud.utils.component.ComponentLocator; -import com.vmware.apputils.version.ExtendedAppUtil; - +import com.cloud.utils.component.ComponentLocator; +import com.vmware.apputils.version.ExtendedAppUtil; + public class VmwareContextFactory { private static final Logger s_logger = Logger.getLogger(VmwareContextFactory.class); - - private static volatile int s_seq = 1; - private static VmwareManager s_vmwareMgr; - - static { - // skip certificate check - System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); - - ComponentLocator locator = ComponentLocator.getLocator("management-server"); - s_vmwareMgr = locator.getManager(VmwareManager.class); - } - - public static VmwareContext create(String vCenterAddress, String vCenterUserName, String vCenterPassword) throws Exception { - assert(vCenterAddress != null); - assert(vCenterUserName != null); - assert(vCenterPassword != null); - - String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService"; - String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; + + private static volatile int s_seq = 1; + private static VmwareManager s_vmwareMgr; + + static { + // skip certificate check + System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory"); + + ComponentLocator locator = ComponentLocator.getLocator("management-server"); + s_vmwareMgr = locator.getManager(VmwareManager.class); + } + + public static VmwareContext create(String vCenterAddress, String vCenterUserName, String vCenterPassword) throws Exception { + assert(vCenterAddress != null); + assert(vCenterUserName != null); + assert(vCenterPassword != null); + + String serviceUrl = "https://" + vCenterAddress + "/sdk/vimService"; + String[] params = new String[] {"--url", serviceUrl, "--username", vCenterUserName, "--password", vCenterPassword }; if(s_logger.isDebugEnabled()) s_logger.debug("initialize VmwareContext. url: " + serviceUrl + ", username: " + vCenterUserName + ", password: " + StringUtils.getMaskedPasswordForDisplay(vCenterPassword)); - ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params); - - appUtil.connect(); - VmwareContext context = new VmwareContext(appUtil, vCenterAddress); - context.registerStockObject(VmwareManager.CONTEXT_STOCK_NAME, s_vmwareMgr); - - context.registerStockObject("serviceconsole", s_vmwareMgr.getServiceConsolePortGroupName()); + ExtendedAppUtil appUtil = ExtendedAppUtil.initialize(vCenterAddress + "-" + s_seq++, params); + + appUtil.connect(); + VmwareContext context = new VmwareContext(appUtil, vCenterAddress); + context.registerStockObject(VmwareManager.CONTEXT_STOCK_NAME, s_vmwareMgr); + + context.registerStockObject("serviceconsole", s_vmwareMgr.getServiceConsolePortGroupName()); context.registerStockObject("manageportgroup", s_vmwareMgr.getManagementPortGroupName()); - - return context; - } -} + + return context; + } +} diff --git a/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 3471eed6c6f..7bbb6e12f84 100755 --- a/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/core/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.hypervisor.vmware.resource; - +package com.cloud.hypervisor.vmware.resource; + import java.io.File; import java.io.IOException; import java.net.ConnectException; @@ -230,32 +230,32 @@ import com.vmware.vim25.VirtualMachineGuestOsIdentifier; import com.vmware.vim25.VirtualMachinePowerState; import com.vmware.vim25.VirtualMachineRuntimeInfo; import com.vmware.vim25.VirtualSCSISharing; - -public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { - private static final Logger s_logger = Logger.getLogger(VmwareResource.class); - - protected String _name; - + +public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { + private static final Logger s_logger = Logger.getLogger(VmwareResource.class); + + protected String _name; + protected final long _ops_timeout = 900000; // 15 minutes time out to time protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown - - // out an operation - protected final int _retry = 24; - protected final int _sleep = 10000; - protected final int DEFAULT_DOMR_SSHPORT = 3922; - protected final int MAX_CMD_MBEAN = 100; - - protected String _url; - protected String _dcId; - protected String _pod; - protected String _cluster; - protected String _username; - protected String _password; - protected String _guid; - protected String _vCenterAddress; - - protected String _privateNetworkVSwitchName; - protected String _publicNetworkVSwitchName; + + // out an operation + protected final int _retry = 24; + protected final int _sleep = 10000; + protected final int DEFAULT_DOMR_SSHPORT = 3922; + protected final int MAX_CMD_MBEAN = 100; + + protected String _url; + protected String _dcId; + protected String _pod; + protected String _cluster; + protected String _username; + protected String _password; + protected String _guid; + protected String _vCenterAddress; + + protected String _privateNetworkVSwitchName; + protected String _publicNetworkVSwitchName; protected String _guestNetworkVSwitchName; protected float _cpuOverprovisioningFactor = 1; @@ -266,139 +266,139 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa protected boolean _recycleHungWorker = false; protected DiskControllerType _rootDiskController = DiskControllerType.ide; - protected ManagedObjectReference _morHyperHost; - protected VmwareContext _serviceContext; - protected String _hostName; - + protected ManagedObjectReference _morHyperHost; + protected VmwareContext _serviceContext; + protected String _hostName; + protected HashMap _vms = new HashMap(71); - protected List _cmdMBeans = new ArrayList(); - - protected Gson _gson; - - protected volatile long _cmdSequence = 1; - - protected static HashMap s_statesTable; - static { - s_statesTable = new HashMap(); - s_statesTable.put(VirtualMachinePowerState.poweredOn, State.Running); - s_statesTable.put(VirtualMachinePowerState.poweredOff, State.Stopped); - s_statesTable.put(VirtualMachinePowerState.suspended, State.Stopped); - } - - public VmwareResource() { - _gson = GsonHelper.getGsonLogger(); - } - - @Override + protected List _cmdMBeans = new ArrayList(); + + protected Gson _gson; + + protected volatile long _cmdSequence = 1; + + protected static HashMap s_statesTable; + static { + s_statesTable = new HashMap(); + s_statesTable.put(VirtualMachinePowerState.poweredOn, State.Running); + s_statesTable.put(VirtualMachinePowerState.poweredOff, State.Stopped); + s_statesTable.put(VirtualMachinePowerState.suspended, State.Stopped); + } + + public VmwareResource() { + _gson = GsonHelper.getGsonLogger(); + } + + @Override public Answer executeRequest(Command cmd) { if(s_logger.isTraceEnabled()) s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName()); - Answer answer = null; - NDC.push(_hostName != null ? _hostName : _guid + "(" + ComponentLocator.class.getPackage().getImplementationVersion() + ")"); - try { - long cmdSequence = _cmdSequence++; - Date startTime = DateUtil.currentGMTTime(); - PropertyMapDynamicBean mbean = new PropertyMapDynamicBean(); - mbean.addProp("StartTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), startTime)); - mbean.addProp("Command", _gson.toJson(cmd)); - mbean.addProp("Sequence", String.valueOf(cmdSequence)); - mbean.addProp("Name", cmd.getClass().getSimpleName()); - - if (cmd instanceof CreateCommand) { - answer = execute((CreateCommand) cmd); - } else if (cmd instanceof SetPortForwardingRulesCommand) { - answer = execute((SetPortForwardingRulesCommand) cmd); - } else if (cmd instanceof SetStaticNatRulesCommand) { - answer = execute((SetStaticNatRulesCommand) cmd); - } else if (cmd instanceof LoadBalancerConfigCommand) { - answer = execute((LoadBalancerConfigCommand) cmd); - } else if (cmd instanceof IpAssocCommand) { - answer = execute((IpAssocCommand) cmd); - } else if (cmd instanceof SavePasswordCommand) { - answer = execute((SavePasswordCommand) cmd); - } else if (cmd instanceof DhcpEntryCommand) { - answer = execute((DhcpEntryCommand) cmd); - } else if (cmd instanceof VmDataCommand) { - answer = execute((VmDataCommand) cmd); - } else if (cmd instanceof ReadyCommand) { - answer = execute((ReadyCommand) cmd); - } else if (cmd instanceof GetHostStatsCommand) { - answer = execute((GetHostStatsCommand) cmd); - } else if (cmd instanceof GetVmStatsCommand) { - answer = execute((GetVmStatsCommand) cmd); - } else if (cmd instanceof CheckHealthCommand) { - answer = execute((CheckHealthCommand) cmd); - } else if (cmd instanceof StopCommand) { - answer = execute((StopCommand) cmd); - } else if (cmd instanceof RebootRouterCommand) { - answer = execute((RebootRouterCommand) cmd); - } else if (cmd instanceof RebootCommand) { - answer = execute((RebootCommand) cmd); - } else if (cmd instanceof CheckVirtualMachineCommand) { - answer = execute((CheckVirtualMachineCommand) cmd); - } else if (cmd instanceof PrepareForMigrationCommand) { - answer = execute((PrepareForMigrationCommand) cmd); - } else if (cmd instanceof MigrateCommand) { - answer = execute((MigrateCommand) cmd); - } else if (cmd instanceof DestroyCommand) { - answer = execute((DestroyCommand) cmd); - } else if (cmd instanceof CreateStoragePoolCommand) { - return execute((CreateStoragePoolCommand) cmd); - } else if (cmd instanceof ModifyStoragePoolCommand) { - answer = execute((ModifyStoragePoolCommand) cmd); - } else if (cmd instanceof DeleteStoragePoolCommand) { - answer = execute((DeleteStoragePoolCommand) cmd); - } else if (cmd instanceof CopyVolumeCommand) { - answer = execute((CopyVolumeCommand) cmd); - } else if (cmd instanceof AttachVolumeCommand) { - answer = execute((AttachVolumeCommand) cmd); - } else if (cmd instanceof AttachIsoCommand) { - answer = execute((AttachIsoCommand) cmd); - } else if (cmd instanceof ValidateSnapshotCommand) { - answer = execute((ValidateSnapshotCommand) cmd); - } else if (cmd instanceof ManageSnapshotCommand) { - answer = execute((ManageSnapshotCommand) cmd); - } else if (cmd instanceof BackupSnapshotCommand) { - answer = execute((BackupSnapshotCommand) cmd); - } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { - answer = execute((CreateVolumeFromSnapshotCommand) cmd); - } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) { - answer = execute((CreatePrivateTemplateFromVolumeCommand) cmd); - } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { - answer = execute((CreatePrivateTemplateFromSnapshotCommand) cmd); - } else if (cmd instanceof UpgradeSnapshotCommand) { - answer = execute((UpgradeSnapshotCommand) cmd); - } else if (cmd instanceof GetStorageStatsCommand) { - answer = execute((GetStorageStatsCommand) cmd); - } else if (cmd instanceof PrimaryStorageDownloadCommand) { - answer = execute((PrimaryStorageDownloadCommand) cmd); - } else if (cmd instanceof GetVncPortCommand) { - answer = execute((GetVncPortCommand) cmd); - } else if (cmd instanceof SetupCommand) { - answer = execute((SetupCommand) cmd); - } else if (cmd instanceof MaintainCommand) { - answer = execute((MaintainCommand) cmd); - } else if (cmd instanceof PingTestCommand) { - answer = execute((PingTestCommand) cmd); - } else if (cmd instanceof CheckOnHostCommand) { - answer = execute((CheckOnHostCommand) cmd); - } else if (cmd instanceof ModifySshKeysCommand) { - answer = execute((ModifySshKeysCommand) cmd); - } else if (cmd instanceof PoolEjectCommand) { - answer = execute((PoolEjectCommand) cmd); - } else if (cmd instanceof NetworkUsageCommand) { - answer = execute((NetworkUsageCommand) cmd); - } else if (cmd instanceof StartCommand) { - answer = execute((StartCommand) cmd); - } else if (cmd instanceof RemoteAccessVpnCfgCommand) { - answer = execute((RemoteAccessVpnCfgCommand) cmd); - } else if (cmd instanceof VpnUsersCfgCommand) { - answer = execute((VpnUsersCfgCommand) cmd); - } else if (cmd instanceof CheckSshCommand) { - answer = execute((CheckSshCommand) cmd); - } else if (cmd instanceof CheckRouterCommand) { - answer = execute((CheckRouterCommand) cmd); + Answer answer = null; + NDC.push(_hostName != null ? _hostName : _guid + "(" + ComponentLocator.class.getPackage().getImplementationVersion() + ")"); + try { + long cmdSequence = _cmdSequence++; + Date startTime = DateUtil.currentGMTTime(); + PropertyMapDynamicBean mbean = new PropertyMapDynamicBean(); + mbean.addProp("StartTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), startTime)); + mbean.addProp("Command", _gson.toJson(cmd)); + mbean.addProp("Sequence", String.valueOf(cmdSequence)); + mbean.addProp("Name", cmd.getClass().getSimpleName()); + + if (cmd instanceof CreateCommand) { + answer = execute((CreateCommand) cmd); + } else if (cmd instanceof SetPortForwardingRulesCommand) { + answer = execute((SetPortForwardingRulesCommand) cmd); + } else if (cmd instanceof SetStaticNatRulesCommand) { + answer = execute((SetStaticNatRulesCommand) cmd); + } else if (cmd instanceof LoadBalancerConfigCommand) { + answer = execute((LoadBalancerConfigCommand) cmd); + } else if (cmd instanceof IpAssocCommand) { + answer = execute((IpAssocCommand) cmd); + } else if (cmd instanceof SavePasswordCommand) { + answer = execute((SavePasswordCommand) cmd); + } else if (cmd instanceof DhcpEntryCommand) { + answer = execute((DhcpEntryCommand) cmd); + } else if (cmd instanceof VmDataCommand) { + answer = execute((VmDataCommand) cmd); + } else if (cmd instanceof ReadyCommand) { + answer = execute((ReadyCommand) cmd); + } else if (cmd instanceof GetHostStatsCommand) { + answer = execute((GetHostStatsCommand) cmd); + } else if (cmd instanceof GetVmStatsCommand) { + answer = execute((GetVmStatsCommand) cmd); + } else if (cmd instanceof CheckHealthCommand) { + answer = execute((CheckHealthCommand) cmd); + } else if (cmd instanceof StopCommand) { + answer = execute((StopCommand) cmd); + } else if (cmd instanceof RebootRouterCommand) { + answer = execute((RebootRouterCommand) cmd); + } else if (cmd instanceof RebootCommand) { + answer = execute((RebootCommand) cmd); + } else if (cmd instanceof CheckVirtualMachineCommand) { + answer = execute((CheckVirtualMachineCommand) cmd); + } else if (cmd instanceof PrepareForMigrationCommand) { + answer = execute((PrepareForMigrationCommand) cmd); + } else if (cmd instanceof MigrateCommand) { + answer = execute((MigrateCommand) cmd); + } else if (cmd instanceof DestroyCommand) { + answer = execute((DestroyCommand) cmd); + } else if (cmd instanceof CreateStoragePoolCommand) { + return execute((CreateStoragePoolCommand) cmd); + } else if (cmd instanceof ModifyStoragePoolCommand) { + answer = execute((ModifyStoragePoolCommand) cmd); + } else if (cmd instanceof DeleteStoragePoolCommand) { + answer = execute((DeleteStoragePoolCommand) cmd); + } else if (cmd instanceof CopyVolumeCommand) { + answer = execute((CopyVolumeCommand) cmd); + } else if (cmd instanceof AttachVolumeCommand) { + answer = execute((AttachVolumeCommand) cmd); + } else if (cmd instanceof AttachIsoCommand) { + answer = execute((AttachIsoCommand) cmd); + } else if (cmd instanceof ValidateSnapshotCommand) { + answer = execute((ValidateSnapshotCommand) cmd); + } else if (cmd instanceof ManageSnapshotCommand) { + answer = execute((ManageSnapshotCommand) cmd); + } else if (cmd instanceof BackupSnapshotCommand) { + answer = execute((BackupSnapshotCommand) cmd); + } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { + answer = execute((CreateVolumeFromSnapshotCommand) cmd); + } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) { + answer = execute((CreatePrivateTemplateFromVolumeCommand) cmd); + } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { + answer = execute((CreatePrivateTemplateFromSnapshotCommand) cmd); + } else if (cmd instanceof UpgradeSnapshotCommand) { + answer = execute((UpgradeSnapshotCommand) cmd); + } else if (cmd instanceof GetStorageStatsCommand) { + answer = execute((GetStorageStatsCommand) cmd); + } else if (cmd instanceof PrimaryStorageDownloadCommand) { + answer = execute((PrimaryStorageDownloadCommand) cmd); + } else if (cmd instanceof GetVncPortCommand) { + answer = execute((GetVncPortCommand) cmd); + } else if (cmd instanceof SetupCommand) { + answer = execute((SetupCommand) cmd); + } else if (cmd instanceof MaintainCommand) { + answer = execute((MaintainCommand) cmd); + } else if (cmd instanceof PingTestCommand) { + answer = execute((PingTestCommand) cmd); + } else if (cmd instanceof CheckOnHostCommand) { + answer = execute((CheckOnHostCommand) cmd); + } else if (cmd instanceof ModifySshKeysCommand) { + answer = execute((ModifySshKeysCommand) cmd); + } else if (cmd instanceof PoolEjectCommand) { + answer = execute((PoolEjectCommand) cmd); + } else if (cmd instanceof NetworkUsageCommand) { + answer = execute((NetworkUsageCommand) cmd); + } else if (cmd instanceof StartCommand) { + answer = execute((StartCommand) cmd); + } else if (cmd instanceof RemoteAccessVpnCfgCommand) { + answer = execute((RemoteAccessVpnCfgCommand) cmd); + } else if (cmd instanceof VpnUsersCfgCommand) { + answer = execute((VpnUsersCfgCommand) cmd); + } else if (cmd instanceof CheckSshCommand) { + answer = execute((CheckSshCommand) cmd); + } else if (cmd instanceof CheckRouterCommand) { + answer = execute((CheckRouterCommand) cmd); } else if (cmd instanceof SetFirewallRulesCommand) { answer = execute((SetFirewallRulesCommand)cmd); } else if (cmd instanceof BumpUpPriorityCommand) { @@ -407,43 +407,43 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa answer = execute((GetDomRVersionCmd)cmd); } else if (cmd instanceof CheckNetworkCommand) { answer = execute((CheckNetworkCommand) cmd); - } else { - answer = Answer.createUnsupportedCommandAnswer(cmd); + } else { + answer = Answer.createUnsupportedCommandAnswer(cmd); } if(cmd.getContextParam("checkpoint") != null) { answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint")); } - - Date doneTime = DateUtil.currentGMTTime(); - mbean.addProp("DoneTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), doneTime)); - mbean.addProp("Answer", _gson.toJson(answer)); - - synchronized (this) { - try { - JmxUtil.registerMBean("VMware " + _morHyperHost.get_value(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); - _cmdMBeans.add(mbean); - - if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { - PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); - _cmdMBeans.remove(0); - - JmxUtil.unregisterMBean("VMware " + _morHyperHost.get_value(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); - } + + Date doneTime = DateUtil.currentGMTTime(); + mbean.addProp("DoneTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), doneTime)); + mbean.addProp("Answer", _gson.toJson(answer)); + + synchronized (this) { + try { + JmxUtil.registerMBean("VMware " + _morHyperHost.get_value(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); + _cmdMBeans.add(mbean); + + if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { + PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); + _cmdMBeans.remove(0); + + JmxUtil.unregisterMBean("VMware " + _morHyperHost.get_value(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); + } } catch (Exception e) { - if(s_logger.isTraceEnabled()) - s_logger.trace("Unable to register JMX monitoring due to exception " + ExceptionUtil.toString(e)); - } - } - - } finally { - NDC.pop(); - } + if(s_logger.isTraceEnabled()) + s_logger.trace("Unable to register JMX monitoring due to exception " + ExceptionUtil.toString(e)); + } + } + + } finally { + NDC.pop(); + } if(s_logger.isTraceEnabled()) s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName()); - - return answer; + + return answer; } protected Answer execute(CheckNetworkCommand cmd) { @@ -453,66 +453,66 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // TODO setup portgroup for private network needs to be done here now return new CheckNetworkAnswer(cmd, true , "Network Setup check by names is done"); - } - - protected Answer execute(NetworkUsageCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource NetworkUsageCommand " + _gson.toJson(cmd)); - } + } + + protected Answer execute(NetworkUsageCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource NetworkUsageCommand " + _gson.toJson(cmd)); + } if(cmd.getOption()!=null && cmd.getOption().equals("create") ){ String result = networkUsage(cmd.getPrivateIP(), "create", null); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L); return answer; - } - long[] stats = getNetworkStats(cmd.getPrivateIP()); - - NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); - return answer; - } - - protected Answer execute(SetPortForwardingRulesCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); - } - - String controlIp = getRouterSshControlIp(cmd); - String args = ""; - String[] results = new String[cmd.getRules().length]; + } + long[] stats = getNetworkStats(cmd.getPrivateIP()); + + NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); + return answer; + } + + protected Answer execute(SetPortForwardingRulesCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); + } + + String controlIp = getRouterSshControlIp(cmd); + String args = ""; + String[] results = new String[cmd.getRules().length]; int i = 0; - boolean endResult = true; - for (PortForwardingRuleTO rule : cmd.getRules()) { - args += rule.revoked() ? " -D " : " -A "; - args += " -P " + rule.getProtocol().toLowerCase(); - args += " -l " + rule.getSrcIp(); - args += " -p " + rule.getStringSrcPortRange(); - args += " -r " + rule.getDstIp(); + boolean endResult = true; + for (PortForwardingRuleTO rule : cmd.getRules()) { + args += rule.revoked() ? " -D " : " -A "; + args += " -P " + rule.getProtocol().toLowerCase(); + args += " -l " + rule.getSrcIp(); + args += " -p " + rule.getStringSrcPortRange(); + args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange(); - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); - - if (!result.first()) { - s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + + if (!result.first()) { + s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); + endResult = false; + } else { + results[i++] = null; + } + } catch (Throwable e) { + s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; - endResult = false; - } - } - - return new SetPortForwardingRulesAnswer(cmd, results, endResult); + endResult = false; + } + } + + return new SetPortForwardingRulesAnswer(cmd, results, endResult); } - + protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { String controlIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; @@ -563,103 +563,103 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new SetFirewallRulesAnswer(cmd, true, results); } - - protected Answer execute(SetStaticNatRulesCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); - } - - String args = null; - String[] results = new String[cmd.getRules().length]; + + protected Answer execute(SetStaticNatRulesCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); + } + + String args = null; + String[] results = new String[cmd.getRules().length]; int i = 0; - boolean endResult = true; - for (StaticNatRuleTO rule : cmd.getRules()) { - // 1:1 NAT needs instanceip;publicip;domrip;op - args = rule.revoked() ? " -D " : " -A "; - - args += " -l " + rule.getSrcIp(); + boolean endResult = true; + for (StaticNatRuleTO rule : cmd.getRules()) { + // 1:1 NAT needs instanceip;publicip;domrip;op + args = rule.revoked() ? " -D " : " -A "; + + args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); if (rule.getProtocol() != null) { args += " -P " + rule.getProtocol().toLowerCase(); - } - - args += " -d " + rule.getStringSrcPortRange(); - args += " -G "; - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); - - if (s_logger.isDebugEnabled()) - s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); - - if (!result.first()) { - s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); + } + + args += " -d " + rule.getStringSrcPortRange(); + args += " -G "; + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); + + if (s_logger.isDebugEnabled()) + s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); + + if (!result.first()) { + s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; - endResult = false; - } else { - results[i++] = null; - } - } catch (Throwable e) { - s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); + endResult = false; + } else { + results[i++] = null; + } + } catch (Throwable e) { + s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; - endResult = false; - } - } - return new SetStaticNatRulesAnswer(cmd, results, endResult); - } - - protected Answer execute(final LoadBalancerConfigCommand cmd) { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - File keyFile = mgr.getSystemVMKeyFile(); - - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - assert(controlIp != null); - + endResult = false; + } + } + return new SetStaticNatRulesAnswer(cmd, results, endResult); + } + + protected Answer execute(final LoadBalancerConfigCommand cmd) { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + File keyFile = mgr.getSystemVMKeyFile(); + + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String controlIp = getRouterSshControlIp(cmd); + + assert(controlIp != null); + LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); - String[] config = cfgtr.generateConfiguration(cmd); - - String[][] rules = cfgtr.generateFwRules(cmd); - String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; - String tmpCfgFileContents = ""; - for (int i = 0; i < config.length; i++) { - tmpCfgFileContents += config[i]; - tmpCfgFileContents += "\n"; - } - - try { - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); - - try { - String[] addRules = rules[LoadBalancerConfigurator.ADD]; + String[] config = cfgtr.generateConfiguration(cmd); + + String[][] rules = cfgtr.generateFwRules(cmd); + String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; + String tmpCfgFileContents = ""; + for (int i = 0; i < config.length; i++) { + tmpCfgFileContents += config[i]; + tmpCfgFileContents += "\n"; + } + + try { + SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); + + try { + String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; - String[] statRules = rules[LoadBalancerConfigurator.STATS]; - - String args = ""; - args += "-i " + routerIp; - args += " -f " + tmpCfgFilePath; - - StringBuilder sb = new StringBuilder(); - if (addRules.length > 0) { - for (int i = 0; i < addRules.length; i++) { - sb.append(addRules[i]).append(','); - } - - args += " -a " + sb.toString(); - } - - sb = new StringBuilder(); - if (removeRules.length > 0) { - for (int i = 0; i < removeRules.length; i++) { - sb.append(removeRules[i]).append(','); - } - - args += " -d " + sb.toString(); - } + String[] statRules = rules[LoadBalancerConfigurator.STATS]; + + String args = ""; + args += "-i " + routerIp; + args += " -f " + tmpCfgFilePath; + + StringBuilder sb = new StringBuilder(); + if (addRules.length > 0) { + for (int i = 0; i < addRules.length; i++) { + sb.append(addRules[i]).append(','); + } + + args += " -a " + sb.toString(); + } + + sb = new StringBuilder(); + if (removeRules.length > 0) { + for (int i = 0; i < removeRules.length; i++) { + sb.append(removeRules[i]).append(','); + } + + args += " -d " + sb.toString(); + } sb = new StringBuilder(); if (statRules.length > 0) { @@ -669,119 +669,119 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa args += " -s " + sb.toString(); } - - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); - - if (!result.first()) { - s_logger.error("Unable to copy haproxy configuration file"); - return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); - } - - result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); - - if (!result.first()) { - String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); - s_logger.error(msg); - - return new Answer(cmd, false, msg); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); - } - } finally { - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); - } - - return new Answer(cmd); - } catch (Throwable e) { - s_logger.error("Unexpected exception: " + e.toString(), e); - return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); - } - } - - protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, - final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress, String guestIp) throws Exception { - - String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); - Pair publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); - } - - boolean addVif = false; - boolean removeVif = false; - if (add && publicNicInfo.first().intValue() == -1) { - if (s_logger.isDebugEnabled()) { - s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); - } - - addVif = true; - } else if (!add && firstIP) { - removeVif = true; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Unplug NIC " + publicNicInfo.first()); - } - } - - if (addVif) { - plugPublicNic(vmMo, vlanId, vifMacAddress); - publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); - if (publicNicInfo.first().intValue() >= 0) { - networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); - } - } - - if (publicNicInfo.first().intValue() < 0) { - String msg = "Failed to find DomR VIF to associate/disassociate IP with."; - s_logger.error(msg); - throw new InternalErrorException(msg); - } - - String args = null; - - if (add) { - args = " -A "; - } else { - args = " -D "; - } - String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); - if (sourceNat) { - args += " -s "; + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); + + if (!result.first()) { + s_logger.error("Unable to copy haproxy configuration file"); + return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); + } + + result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); + + if (!result.first()) { + String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); + s_logger.error(msg); + + return new Answer(cmd, false, msg); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); + } + } finally { + SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); + } + + return new Answer(cmd); + } catch (Throwable e) { + s_logger.error("Unexpected exception: " + e.toString(), e); + return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); } - if (firstIP) { - args += " -f "; - args += " -l "; - args += publicIpAddress + "/" + cidrSize; - } else { - args += " -l "; - args += publicIpAddress; - } - - args += " -c "; + } + + protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, + final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress, String guestIp) throws Exception { + + String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); + Pair publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); + } + + boolean addVif = false; + boolean removeVif = false; + if (add && publicNicInfo.first().intValue() == -1) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); + } + + addVif = true; + } else if (!add && firstIP) { + removeVif = true; + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Unplug NIC " + publicNicInfo.first()); + } + } + + if (addVif) { + plugPublicNic(vmMo, vlanId, vifMacAddress); + publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); + if (publicNicInfo.first().intValue() >= 0) { + networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); + } + } + + if (publicNicInfo.first().intValue() < 0) { + String msg = "Failed to find DomR VIF to associate/disassociate IP with."; + s_logger.error(msg); + throw new InternalErrorException(msg); + } + + String args = null; + + if (add) { + args = " -A "; + } else { + args = " -D "; + } + String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); + if (sourceNat) { + args += " -s "; + } + if (firstIP) { + args += " -f "; + args += " -l "; + args += publicIpAddress + "/" + cidrSize; + } else { + args += " -l "; + args += publicIpAddress; + } + + args += " -c "; args += "eth" + publicNicInfo.first(); args += " -g "; - args += vlanGateway; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domain router " + privateIpAddress + ", /root/ipassoc.sh " + args); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/ipassoc.sh " + args); - - if (!result.first()) { - s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); - throw new Exception("ipassoc failed due to " + result.second()); - } - + args += vlanGateway; + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run command on domain router " + privateIpAddress + ", /root/ipassoc.sh " + args); + } + + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/ipassoc.sh " + args); + + if (!result.first()) { + s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); + throw new Exception("ipassoc failed due to " + result.second()); + } + if (removeVif) { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); @@ -789,24 +789,24 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa nicMasks &= ~(1 << publicNicInfo.first().intValue()); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); - HostMO hostMo = vmMo.getRunningHost(); - List networks = vmMo.getNetworksWithDetails(); - for (NetworkDetails netDetails : networks) { - if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { - if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { - cleanupNetwork(hostMo, netDetails); - } - } - } - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); - } - } - - private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { - // TODO : probably need to set traffic shaping + HostMO hostMo = vmMo.getRunningHost(); + List networks = vmMo.getNetworksWithDetails(); + for (NetworkDetails netDetails : networks) { + if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { + if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { + cleanupNetwork(hostMo, netDetails); + } + } + } + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); + } + } + + private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { + // TODO : probably need to set traffic shaping Pair networkInfo = HypervisorHostHelper.prepareNetwork(this._publicNetworkVSwitchName, "cloud.public", vmMo.getRunningHost(), vlanId, null, null, this._ops_timeout, true); @@ -862,24 +862,24 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Could not allocate a free public NIC"); } - - protected Answer execute(IpAssocCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); - } - - int i = 0; - String[] results = new String[cmd.getIpAddresses().length]; - - VmwareContext context = getServiceContext(); - try { - VmwareHypervisorHost hyperHost = getHyperHost(context); - - IpAddressTO[] ips = cmd.getIpAddresses(); - String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); - String controlIp = VmwareResource.getRouterSshControlIp(cmd); - - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); + + protected Answer execute(IpAssocCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); + } + + int i = 0; + String[] results = new String[cmd.getIpAddresses().length]; + + VmwareContext context = getServiceContext(); + try { + VmwareHypervisorHost hyperHost = getHyperHost(context); + + IpAddressTO[] ips = cmd.getIpAddresses(); + String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + String controlIp = VmwareResource.getRouterSshControlIp(cmd); + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); // command may sometimes be redirect to a wrong host, we relax // the check and will try to find it within cluster @@ -891,78 +891,78 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - if (vmMo == null) { - String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; - s_logger.error(msg); - throw new Exception(msg); - } - - for (IpAddressTO ip : ips) { - assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), - ip.getVifMacAddress(), ip.getGuestIp()); - results[i++] = ip.getPublicIp() + " - success"; - } - } catch (Throwable e) { - s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); - - for (; i < cmd.getIpAddresses().length; i++) { - results[i++] = IpAssocAnswer.errorResult; - } - } - - return new IpAssocAnswer(cmd, results); - } - - protected Answer execute(SavePasswordCommand cmd) { - if (s_logger.isInfoEnabled()) { + if (vmMo == null) { + String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; + s_logger.error(msg); + throw new Exception(msg); + } + + for (IpAddressTO ip : ips) { + assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), + ip.getVifMacAddress(), ip.getGuestIp()); + results[i++] = ip.getPublicIp() + " - success"; + } + } catch (Throwable e) { + s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); + + for (; i < cmd.getIpAddresses().length; i++) { + results[i++] = IpAssocAnswer.errorResult; + } + } + + return new IpAssocAnswer(cmd, results); + } + + protected Answer execute(SavePasswordCommand cmd) { + if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " - + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); - } - + + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); + } + String controlIp = getRouterSshControlIp(cmd); - final String password = cmd.getPassword(); - final String vmIpAddress = cmd.getVmIpAddress(); - - // Run save_password_to_domr.sh + final String password = cmd.getPassword(); + final String vmIpAddress = cmd.getVmIpAddress(); + + // Run save_password_to_domr.sh String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } - - args += " -p " + password; - - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); - - if (!result.first()) { - s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); - - return new Answer(cmd, false, "SavePassword failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("savepassword command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - return new Answer(cmd); - } - - protected Answer execute(DhcpEntryCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); - } - + + args += " -p " + password; + + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); + + if (!result.first()) { + s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "SavePassword failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("savepassword command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + return new Answer(cmd); + } + + protected Answer execute(DhcpEntryCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); + } + // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null - String args = " " + cmd.getVmMac(); - args += " " + cmd.getVmIpAddress(); + String args = " " + cmd.getVmMac(); + args += " " + cmd.getVmIpAddress(); args += " " + cmd.getVmName(); if (cmd.getDefaultRouter() != null) { @@ -976,34 +976,34 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (cmd.getStaticRoutes() != null) { args += " " + cmd.getStaticRoutes(); } - + if (s_logger.isDebugEnabled()) { - s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - String controlIp = getRouterSshControlIp(cmd); - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, - "/root/edithosts.sh " + args); - - if (!result.first()) { - s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); - - return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); + s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); + } + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + String controlIp = getRouterSshControlIp(cmd); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, + "/root/edithosts.sh " + args); + + if (!result.first()) { + s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); + + return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); } protected Answer execute(CheckRouterCommand cmd) { @@ -1035,7 +1035,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return new CheckRouterAnswer(cmd, result.second(), true); } - + protected Answer execute(GetDomRVersionCmd cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd)); @@ -1069,7 +1069,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); } - + protected Answer execute(BumpUpPriorityCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd)); @@ -1103,190 +1103,190 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return new Answer(cmd, false, result.second()); } - protected Answer execute(VmDataCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); - } - - String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String controlIp = getRouterSshControlIp(cmd); - - String vmIpAddress = cmd.getVmIpAddress(); - List vmData = cmd.getVmData(); - String[] vmDataArgs = new String[vmData.size() * 2 + 4]; - vmDataArgs[0] = "routerIP"; - vmDataArgs[1] = routerPrivateIpAddress; - vmDataArgs[2] = "vmIP"; - vmDataArgs[3] = vmIpAddress; - int i = 4; - for (String[] vmDataEntry : vmData) { - String folder = vmDataEntry[0]; - String file = vmDataEntry[1]; - String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; - - vmDataArgs[i] = folder + "," + file; - vmDataArgs[i + 1] = contents; - i += 2; - } - - String content = encodeDataArgs(vmDataArgs); - String tmpFileName = UUID.randomUUID().toString(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); - - try { - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, - "/root/userdata.py " + tmpFileName); - - if (!result.first()) { - s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); - return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); - } - } finally { - - SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("vm_data command on domain router " + controlIp + " completed"); - } - - } catch (Throwable e) { - String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - return new Answer(cmd); - } - - private String encodeDataArgs(String[] dataArgs) { - StringBuilder sb = new StringBuilder(); - - for (String arg : dataArgs) { - sb.append(arg); - sb.append("\n"); - } - - return sb.toString(); - } - - protected CheckSshAnswer execute(CheckSshCommand cmd) { - String vmName = cmd.getName(); - String privateIp = cmd.getIp(); - int cmdPort = cmd.getPort(); - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); - } - - try { - String result = connect(cmd.getName(), privateIp, cmdPort); - if (result != null) { - s_logger.error("Can not ping System vm " + vmName + "due to:" + result); - return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); - } - } catch (Exception e) { - s_logger.error("Can not ping System vm " + vmName + "due to exception"); - return new CheckSshAnswer(cmd, e); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Ping command port succeeded for vm " + vmName); - } - - if (VirtualMachineName.isValidRouterName(vmName)) { + protected Answer execute(VmDataCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); + } + + String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String controlIp = getRouterSshControlIp(cmd); + + String vmIpAddress = cmd.getVmIpAddress(); + List vmData = cmd.getVmData(); + String[] vmDataArgs = new String[vmData.size() * 2 + 4]; + vmDataArgs[0] = "routerIP"; + vmDataArgs[1] = routerPrivateIpAddress; + vmDataArgs[2] = "vmIP"; + vmDataArgs[3] = vmIpAddress; + int i = 4; + for (String[] vmDataEntry : vmData) { + String folder = vmDataEntry[0]; + String file = vmDataEntry[1]; + String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; + + vmDataArgs[i] = folder + "," + file; + vmDataArgs[i + 1] = contents; + i += 2; + } + + String content = encodeDataArgs(vmDataArgs); + String tmpFileName = UUID.randomUUID().toString(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); + } + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); + + try { + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, + "/root/userdata.py " + tmpFileName); + + if (!result.first()) { + s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); + return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); + } + } finally { + + SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("vm_data command on domain router " + controlIp + " completed"); + } + + } catch (Throwable e) { + String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + return new Answer(cmd); + } + + private String encodeDataArgs(String[] dataArgs) { + StringBuilder sb = new StringBuilder(); + + for (String arg : dataArgs) { + sb.append(arg); + sb.append("\n"); + } + + return sb.toString(); + } + + protected CheckSshAnswer execute(CheckSshCommand cmd) { + String vmName = cmd.getName(); + String privateIp = cmd.getIp(); + int cmdPort = cmd.getPort(); + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); + } + + try { + String result = connect(cmd.getName(), privateIp, cmdPort); + if (result != null) { + s_logger.error("Can not ping System vm " + vmName + "due to:" + result); + return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); + } + } catch (Exception e) { + s_logger.error("Can not ping System vm " + vmName + "due to exception"); + return new CheckSshAnswer(cmd, e); + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Ping command port succeeded for vm " + vmName); + } + + if (VirtualMachineName.isValidRouterName(vmName)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Execute network usage setup command on " + vmName); - } - networkUsage(privateIp, "create", null); - } - - return new CheckSshAnswer(cmd); - } - - private VolumeTO[] validateDisks(VolumeTO[] disks) { - List validatedDisks = new ArrayList(); - - for (VolumeTO vol : disks) { - if (vol.getPoolUuid() != null && !vol.getPoolUuid().isEmpty()) { - validatedDisks.add(vol); - } else if (vol.getPoolType() == StoragePoolType.ISO && (vol.getPath() != null && !vol.getPath().isEmpty())) { - validatedDisks.add(vol); - } else { + } + networkUsage(privateIp, "create", null); + } + + return new CheckSshAnswer(cmd); + } + + private VolumeTO[] validateDisks(VolumeTO[] disks) { + List validatedDisks = new ArrayList(); + + for (VolumeTO vol : disks) { + if (vol.getPoolUuid() != null && !vol.getPoolUuid().isEmpty()) { + validatedDisks.add(vol); + } else if (vol.getPoolType() == StoragePoolType.ISO && (vol.getPath() != null && !vol.getPath().isEmpty())) { + validatedDisks.add(vol); + } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Drop invalid disk option, volumeTO: " + _gson.toJson(vol)); - } - } - } - - return validatedDisks.toArray(new VolumeTO[0]); - } - - protected StartAnswer execute(StartCommand cmd) { - - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd)); - } - - VirtualMachineTO vmSpec = cmd.getVirtualMachine(); + } + } + } + + return validatedDisks.toArray(new VolumeTO[0]); + } + + protected StartAnswer execute(StartCommand cmd) { + + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd)); + } + + VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); - State state = State.Stopped; - VmwareContext context = getServiceContext(); - try { - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - // mark VM as starting state so that sync() can know not to report stopped too early - synchronized (_vms) { - _vms.put(vmName, State.Starting); - } + State state = State.Stopped; + VmwareContext context = getServiceContext(); + try { + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + + // mark VM as starting state so that sync() can know not to report stopped too early + synchronized (_vms) { + _vms.put(vmName, State.Starting); + } VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER)); if(s_logger.isDebugEnabled()) s_logger.debug("VM " + vmName + " will be started with NIC device type: " + nicDeviceType); - - VmwareHypervisorHost hyperHost = getHyperHost(context); - VolumeTO[] disks = validateDisks(vmSpec.getDisks()); - assert (disks.length > 0); - NicTO[] nics = vmSpec.getNics(); - - HashMap> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); - if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty()) ){ - String msg = "Unable to locate datastore details of the volumes to be attached"; - s_logger.error(msg); - throw new Exception(msg); - } - - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); - if (vmMo != null) { - s_logger.info("VM " + vmName + " already exists, tear down devices for reconfiguration"); - if (getVmState(vmMo) != State.Stopped) - vmMo.safePowerOff(_shutdown_waitMs); - vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); + + VmwareHypervisorHost hyperHost = getHyperHost(context); + VolumeTO[] disks = validateDisks(vmSpec.getDisks()); + assert (disks.length > 0); + NicTO[] nics = vmSpec.getNics(); + + HashMap> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); + if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty()) ){ + String msg = "Unable to locate datastore details of the volumes to be attached"; + s_logger.error(msg); + throw new Exception(msg); + } + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo != null) { + s_logger.info("VM " + vmName + " already exists, tear down devices for reconfiguration"); + if (getVmState(vmMo) != State.Stopped) + vmMo.safePowerOff(_shutdown_waitMs); + vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); - } else { - ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); - assert (morDc != null); - - vmMo = hyperHost.findVmOnPeerHyperHost(vmName); - if (vmMo != null) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Found vm " + vmName + " at other host, relocate to " + hyperHost.getHyperHostName()); - } - - takeVmFromOtherHyperHost(hyperHost, vmName); - - if (getVmState(vmMo) != State.Stopped) - vmMo.safePowerOff(_shutdown_waitMs); + } else { + ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); + assert (morDc != null); + + vmMo = hyperHost.findVmOnPeerHyperHost(vmName); + if (vmMo != null) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Found vm " + vmName + " at other host, relocate to " + hyperHost.getHyperHostName()); + } + + takeVmFromOtherHyperHost(hyperHost, vmName); + + if (getVmState(vmMo) != State.Stopped) + vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); - } else { + } else { int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); Pair rootDiskDataStoreDetails = null; for (VolumeTO vol : disks) { @@ -1295,121 +1295,121 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - assert (vmSpec.getSpeed() != null) && (rootDiskDataStoreDetails != null); + assert (vmSpec.getSpeed() != null) && (rootDiskDataStoreDetails != null); if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), vmSpec.getLimitCpuUse(), ramMb, getReserveMemMB(ramMb), - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { - throw new Exception("Failed to create VM. vmName: " + vmName); - } - } - - vmMo = hyperHost.findVmOnHyperHost(vmName); - if (vmMo == null) { - throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmName); - } - } - - int totalChangeDevices = disks.length + nics.length; - VolumeTO volIso = null; - if (vmSpec.getType() != VirtualMachine.Type.User) { - // system VM needs a patch ISO - totalChangeDevices++; - } else { - for (VolumeTO vol : disks) { - if (vol.getType() == Volume.Type.ISO) { - volIso = vol; - break; - } - } - - if (volIso == null) - totalChangeDevices++; - } - - VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); - int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { + throw new Exception("Failed to create VM. vmName: " + vmName); + } + } + + vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo == null) { + throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmName); + } + } + + int totalChangeDevices = disks.length + nics.length; + VolumeTO volIso = null; + if (vmSpec.getType() != VirtualMachine.Type.User) { + // system VM needs a patch ISO + totalChangeDevices++; + } else { + for (VolumeTO vol : disks) { + if (vol.getType() == Volume.Type.ISO) { + volIso = vol; + break; + } + } + + if (volIso == null) + totalChangeDevices++; + } + + VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); + int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), - getReserveCpuMHz(vmSpec.getSpeed().intValue()), ramMb, getReserveMemMB(ramMb), - translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); - - VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; - int i = 0; - int ideControllerKey = vmMo.getIDEDeviceControllerKey(); - int scsiControllerKey = vmMo.getScsiDeviceControllerKey(); - int controllerKey; - String datastoreDiskPath; - - // prepare systemvm patch ISO - if (vmSpec.getType() != VirtualMachine.Type.User) { - // attach ISO (for patching of system VM) + getReserveCpuMHz(vmSpec.getSpeed().intValue()), ramMb, getReserveMemMB(ramMb), + translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); + + VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; + int i = 0; + int ideControllerKey = vmMo.getIDEDeviceControllerKey(); + int scsiControllerKey = vmMo.getScsiDeviceControllerKey(); + int controllerKey; + String datastoreDiskPath; + + // prepare systemvm patch ISO + if (vmSpec.getType() != VirtualMachine.Type.User) { + // attach ISO (for patching of system VM) String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); - - ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); - if (morSecDs == null) { - String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; - throw new Exception(msg); - } - DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); - - deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); + + ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); + if (morSecDs == null) { + String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; + throw new Exception(msg); + } + DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); + + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), - secDsMo.getMor(), true, true, i, i + 1); - deviceConfigSpecArray[i].setDevice(isoInfo.first()); - if (isoInfo.second()) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); - } - i++; - } else { - // we will always plugin a CDROM device - if (volIso != null && volIso.getPath() != null && !volIso.getPath().isEmpty()) { - Pair isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, volIso.getPath()); - assert (isoDatastoreInfo != null); - assert (isoDatastoreInfo.second() != null); - - deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); - Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, i, i + 1); - deviceConfigSpecArray[i].setDevice(isoInfo.first()); - if (isoInfo.second()) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); - } - } else { - deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); - Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, i, i + 1); - deviceConfigSpecArray[i].setDevice(isoInfo.first()); - if (isoInfo.second()) { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - } else { - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); - - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); - } - } - i++; - } - - for (VolumeTO vol : sortVolumesByDeviceId(disks)) { - deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); + secDsMo.getMor(), true, true, i, i + 1); + deviceConfigSpecArray[i].setDevice(isoInfo.first()); + if (isoInfo.second()) { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + } else { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + } + i++; + } else { + // we will always plugin a CDROM device + if (volIso != null && volIso.getPath() != null && !volIso.getPath().isEmpty()) { + Pair isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, volIso.getPath()); + assert (isoDatastoreInfo != null); + assert (isoDatastoreInfo.second() != null); + + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); + Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, i, i + 1); + deviceConfigSpecArray[i].setDevice(isoInfo.first()); + if (isoInfo.second()) { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + } else { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + } + } else { + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); + Pair isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, i, i + 1); + deviceConfigSpecArray[i].setDevice(isoInfo.first()); + if (isoInfo.second()) { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); + + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + } else { + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); + + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); + } + } + i++; + } + + for (VolumeTO vol : sortVolumesByDeviceId(disks)) { + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); if (vol.getType() == Volume.Type.ISO) { controllerKey = ideControllerKey; @@ -1429,72 +1429,72 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa controllerKey = scsiControllerKey; } } - - if (vol.getType() != Volume.Type.ISO) { + + if (vol.getType() != Volume.Type.ISO) { Pair volumeDsDetails = dataStoresDetails.get(vol.getPoolUuid()); assert (volumeDsDetails != null); - VirtualDevice device; - datastoreDiskPath = String.format("[%s] %s.vmdk", volumeDsDetails.second().getName(), vol.getPath()); - String chainInfo = vol.getChainInfo(); - - if (chainInfo != null && !chainInfo.isEmpty()) { - String[] diskChain = _gson.fromJson(chainInfo, String[].class); - if (diskChain == null || diskChain.length < 1) { - s_logger.warn("Empty previously-saved chain info, fall back to the original"); - device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); - } else { - s_logger.info("Attach the disk with stored chain info: " + chainInfo); - for (int j = 0; j < diskChain.length; j++) { - diskChain[j] = String.format("[%s] %s", volumeDsDetails.second().getName(), diskChain[j]); - } - - device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, diskChain, volumeDsDetails.first(), i, i + 1); - } - } else { - device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); - } - deviceConfigSpecArray[i].setDevice(device); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); - - i++; - } - } - + VirtualDevice device; + datastoreDiskPath = String.format("[%s] %s.vmdk", volumeDsDetails.second().getName(), vol.getPath()); + String chainInfo = vol.getChainInfo(); + + if (chainInfo != null && !chainInfo.isEmpty()) { + String[] diskChain = _gson.fromJson(chainInfo, String[].class); + if (diskChain == null || diskChain.length < 1) { + s_logger.warn("Empty previously-saved chain info, fall back to the original"); + device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); + } else { + s_logger.info("Attach the disk with stored chain info: " + chainInfo); + for (int j = 0; j < diskChain.length; j++) { + diskChain[j] = String.format("[%s] %s", volumeDsDetails.second().getName(), diskChain[j]); + } + + device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, diskChain, volumeDsDetails.first(), i, i + 1); + } + } else { + device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); + } + deviceConfigSpecArray[i].setDevice(device); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); + + i++; + } + } + VirtualDevice nic; int nicMask = 0; - int nicCount = 0; - for (NicTO nicTo : sortNicsByDeviceId(nics)) { - s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); - + int nicCount = 0; + for (NicTO nicTo : sortNicsByDeviceId(nics)) { + s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); + Pair networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo); - - nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i, i + 1, true, true); - deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); - deviceConfigSpecArray[i].setDevice(nic); - deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); - - if(s_logger.isDebugEnabled()) - s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); + + nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i, i + 1, true, true); + deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); + deviceConfigSpecArray[i].setDevice(nic); + deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); + + if(s_logger.isDebugEnabled()) + s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); - // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3 + // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3 if(nicCount < 3) nicMask |= (1 << nicCount); i++; nicCount++; - } - - vmConfigSpec.setDeviceChange(deviceConfigSpecArray); - + } + + vmConfigSpec.setDeviceChange(deviceConfigSpecArray); + // pass boot arguments through machine.id & perform customized options to VMX Map vmDetailOptions = validateVmDetails(vmSpec.getDetails()); - OptionValue[] extraOptions = new OptionValue[2 + vmDetailOptions.size()]; - extraOptions[0] = new OptionValue(); - extraOptions[0].setKey("machine.id"); + OptionValue[] extraOptions = new OptionValue[2 + vmDetailOptions.size()]; + extraOptions[0] = new OptionValue(); + extraOptions[0].setKey("machine.id"); extraOptions[0].setValue(vmSpec.getBootArgs()); extraOptions[1] = new OptionValue(); @@ -1512,38 +1512,38 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String keyboardLayout = null; if(vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); - vmConfigSpec.setExtraConfig(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout)); - - if (!vmMo.configureVm(vmConfigSpec)) { - throw new Exception("Failed to configure VM before start. vmName: " + vmName); + vmConfigSpec.setExtraConfig(configureVnc(extraOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout)); + + if (!vmMo.configureVm(vmConfigSpec)) { + throw new Exception("Failed to configure VM before start. vmName: " + vmName); } - vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask)); - - if (!vmMo.powerOn()) { - throw new Exception("Failed to start VM. vmName: " + vmName); - } - - state = State.Running; - return new StartAnswer(cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.warn(msg, e); - return new StartAnswer(cmd, msg); - } finally { - synchronized (_vms) { - if (state != State.Stopped) { - _vms.put(vmName, state); - } else { - _vms.remove(vmName); - } - } - } + vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask)); + + if (!vmMo.powerOn()) { + throw new Exception("Failed to start VM. vmName: " + vmName); + } + + state = State.Running; + return new StartAnswer(cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.warn(msg, e); + return new StartAnswer(cmd, msg); + } finally { + synchronized (_vms) { + if (state != State.Stopped) { + _vms.put(vmName, state); + } else { + _vms.remove(vmName); + } + } + } } private Map validateVmDetails(Map vmDetails) { @@ -1568,7 +1568,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } return validatedDetails; - } + } private int getReserveCpuMHz(int cpuMHz) { if(this._reserveCpu) { @@ -1585,28 +1585,28 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return 0; } - - private NicTO[] sortNicsByDeviceId(NicTO[] nics) { - - List listForSort = new ArrayList(); - for (NicTO nic : nics) { - listForSort.add(nic); - } - Collections.sort(listForSort, new Comparator() { - - @Override - public int compare(NicTO arg0, NicTO arg1) { - if (arg0.getDeviceId() < arg1.getDeviceId()) { - return -1; - } else if (arg0.getDeviceId() == arg1.getDeviceId()) { - return 0; - } - - return 1; - } - }); - - return listForSort.toArray(new NicTO[0]); + + private NicTO[] sortNicsByDeviceId(NicTO[] nics) { + + List listForSort = new ArrayList(); + for (NicTO nic : nics) { + listForSort.add(nic); + } + Collections.sort(listForSort, new Comparator() { + + @Override + public int compare(NicTO arg0, NicTO arg1) { + if (arg0.getDeviceId() < arg1.getDeviceId()) { + return -1; + } else if (arg0.getDeviceId() == arg1.getDeviceId()) { + return 0; + } + + return 1; + } + }); + + return listForSort.toArray(new NicTO[0]); } private VolumeTO[] sortVolumesByDeviceId(VolumeTO[] volumes) { @@ -1631,11 +1631,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa return listForSort.toArray(new VolumeTO[0]); } - + private HashMap> inferDatastoreDetailsFromDiskInfo(VmwareHypervisorHost hyperHost, VmwareContext context, VolumeTO[] disks) throws Exception { HashMap> poolMors = new HashMap>(); - assert (hyperHost != null) && (context != null); + assert (hyperHost != null) && (context != null); for (VolumeTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { String poolUuid = vol.getPoolUuid(); @@ -1648,29 +1648,29 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } poolMors.put(vol.getPoolUuid(), new Pair (morDataStore, new DatastoreMO(context, morDataStore))); } - } - } - return poolMors; - } - - private String getVlanInfo(NicTO nicTo) { - if (nicTo.getBroadcastType() == BroadcastDomainType.Native) { - return Vlan.UNTAGGED; - } - - if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan) { - if (nicTo.getBroadcastUri() != null) { - return nicTo.getBroadcastUri().getHost(); - } else { - s_logger.warn("BroadcastType is not claimed as VLAN, but without vlan info in broadcast URI"); - return Vlan.UNTAGGED; - } - } - - s_logger.warn("Unrecognized broadcast type in VmwareResource, type: " + nicTo.getBroadcastType().toString()); - return Vlan.UNTAGGED; - } - + } + } + return poolMors; + } + + private String getVlanInfo(NicTO nicTo) { + if (nicTo.getBroadcastType() == BroadcastDomainType.Native) { + return Vlan.UNTAGGED; + } + + if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan) { + if (nicTo.getBroadcastUri() != null) { + return nicTo.getBroadcastUri().getHost(); + } else { + s_logger.warn("BroadcastType is not claimed as VLAN, but without vlan info in broadcast URI"); + return Vlan.UNTAGGED; + } + } + + s_logger.warn("Unrecognized broadcast type in VmwareResource, type: " + nicTo.getBroadcastType().toString()); + return Vlan.UNTAGGED; + } + private Pair prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo) throws Exception { String switchName = getTargetSwitch(nicTo); @@ -1715,143 +1715,143 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } - } - - protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { - String controlIp = getRouterSshControlIp(cmd); - StringBuffer argsBuf = new StringBuffer(); - if (cmd.isCreate()) { - argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) - .append(" -c "); - - } else { - argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - + } + + protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { + String controlIp = getRouterSshControlIp(cmd); + StringBuffer argsBuf = new StringBuffer(); + if (cmd.isCreate()) { + argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) + .append(" -c "); + + } else { + argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); + } + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); - } - - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); - - if (!result.first()) { - s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); - - return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); - } - - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - - return new Answer(cmd); - } - - protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - String controlIp = getRouterSshControlIp(cmd); - for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { - StringBuffer argsBuf = new StringBuffer(); - if (!userpwd.isAdd()) { - argsBuf.append(" -U ").append(userpwd.getUsername()); - } else { - argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); - } - - try { - + } + + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + + if (!result.first()) { + s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); + + return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); + } + + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + + return new Answer(cmd); + } + + protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + + String controlIp = getRouterSshControlIp(cmd); + for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { + StringBuffer argsBuf = new StringBuffer(); + if (!userpwd.isAdd()) { + argsBuf.append(" -U ").append(userpwd.getUsername()); + } else { + argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); + } + + try { + if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); - } - - Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); - - if (!result.first()) { - s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); - - return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - } - - return new Answer(cmd); - } - - private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { - - VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); - if (vmMo != null) { - ManagedObjectReference morTargetPhysicalHost = hyperHost.findMigrationTarget(vmMo); - if (morTargetPhysicalHost == null) { - String msg = "VM " + vmName + " is on other host and we have no resource available to migrate and start it here"; - s_logger.error(msg); - throw new Exception(msg); - } + } - if (!vmMo.relocate(morTargetPhysicalHost)) { - String msg = "VM " + vmName + " is on other host and we failed to relocate it here"; - s_logger.error(msg); - throw new Exception(msg); - } - - return vmMo; - } - return null; - } - - // isoUrl sample content : - // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary/template/tmpl/2/200//200-2-80f7ee58-6eff-3a2d-bcb0-59663edf6d26.iso - private Pair getIsoDatastoreInfo(VmwareHypervisorHost hyperHost, String isoUrl) throws Exception { - - assert (isoUrl != null); - int isoFileNameStartPos = isoUrl.lastIndexOf("/"); - if (isoFileNameStartPos < 0) { - throw new Exception("Invalid ISO path info"); - } - - String isoFileName = isoUrl.substring(isoFileNameStartPos); - - int templateRootPos = isoUrl.indexOf("template/tmpl"); - if (templateRootPos < 0) { - throw new Exception("Invalid ISO path info"); - } - - String storeUrl = isoUrl.substring(0, templateRootPos - 1); - String isoPath = isoUrl.substring(templateRootPos, isoFileNameStartPos); - - ManagedObjectReference morDs = prepareSecondaryDatastoreOnHost(storeUrl); - DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); - - return new Pair(String.format("[%s] %s%s", dsMo.getName(), isoPath, isoFileName), morDs); - } - - protected Answer execute(ReadyCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); + Pair result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); + + if (!result.first()) { + s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); + + return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + } + + return new Answer(cmd); + } + + private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { + + VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); + if (vmMo != null) { + ManagedObjectReference morTargetPhysicalHost = hyperHost.findMigrationTarget(vmMo); + if (morTargetPhysicalHost == null) { + String msg = "VM " + vmName + " is on other host and we have no resource available to migrate and start it here"; + s_logger.error(msg); + throw new Exception(msg); + } + + if (!vmMo.relocate(morTargetPhysicalHost)) { + String msg = "VM " + vmName + " is on other host and we failed to relocate it here"; + s_logger.error(msg); + throw new Exception(msg); + } + + return vmMo; + } + return null; + } + + // isoUrl sample content : + // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary/template/tmpl/2/200//200-2-80f7ee58-6eff-3a2d-bcb0-59663edf6d26.iso + private Pair getIsoDatastoreInfo(VmwareHypervisorHost hyperHost, String isoUrl) throws Exception { + + assert (isoUrl != null); + int isoFileNameStartPos = isoUrl.lastIndexOf("/"); + if (isoFileNameStartPos < 0) { + throw new Exception("Invalid ISO path info"); + } + + String isoFileName = isoUrl.substring(isoFileNameStartPos); + + int templateRootPos = isoUrl.indexOf("template/tmpl"); + if (templateRootPos < 0) { + throw new Exception("Invalid ISO path info"); + } + + String storeUrl = isoUrl.substring(0, templateRootPos - 1); + String isoPath = isoUrl.substring(templateRootPos, isoFileNameStartPos); + + ManagedObjectReference morDs = prepareSecondaryDatastoreOnHost(storeUrl); + DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); + + return new Pair(String.format("[%s] %s%s", dsMo.getName(), isoPath, isoFileName), morDs); + } + + protected Answer execute(ReadyCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); } try { @@ -1865,43 +1865,43 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ReadyAnswer(cmd, VmwareHelper.getExceptionMessage(e)); - } - } - - protected Answer execute(GetHostStatsCommand cmd) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Executing resource GetHostStatsCommand: " + _gson.toJson(cmd)); - } - - VmwareContext context = getServiceContext(); + } + } + + protected Answer execute(GetHostStatsCommand cmd) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Executing resource GetHostStatsCommand: " + _gson.toJson(cmd)); + } + + VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", 0, 0, 0, 0); - Answer answer = new GetHostStatsAnswer(cmd, hostStats); - try { + Answer answer = new GetHostStatsAnswer(cmd, hostStats); + try { HostStatsEntry entry = getHyperHostStats(hyperHost); - if(entry != null) { - entry.setHostId(cmd.getHostId()); + if(entry != null) { + entry.setHostId(cmd.getHostId()); answer = new GetHostStatsAnswer(cmd, entry); - } - } catch (Exception e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "Unable to execute GetHostStatsCommand due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - } - - if (s_logger.isTraceEnabled()) { - s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer)); + } + } catch (Exception e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "Unable to execute GetHostStatsCommand due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); } - return answer; - } - - protected Answer execute(GetVmStatsCommand cmd) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer)); + } + + return answer; + } + + protected Answer execute(GetVmStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVmStatsCommand: " + _gson.toJson(cmd)); } @@ -1939,145 +1939,145 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if (s_logger.isTraceEnabled()) { s_logger.trace("Report GetVmStatsAnswer: " + _gson.toJson(answer)); } - return answer; - } - - protected Answer execute(CheckHealthCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CheckHealthCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - if (hyperHost.isHyperHostConnected()) { - return new CheckHealthAnswer(cmd, true); - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - s_logger.error("Unable to execute CheckHealthCommand due to " + VmwareHelper.getExceptionMessage(e), e); - } - return new CheckHealthAnswer(cmd, false); - } - - protected Answer execute(StopCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource StopCommand: " + _gson.toJson(cmd)); - } - - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - try { - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); - if (vmMo != null) { - - State state = null; - synchronized (_vms) { - state = _vms.get(cmd.getVmName()); - _vms.put(cmd.getVmName(), State.Stopping); - } - + return answer; + } + + protected Answer execute(CheckHealthCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CheckHealthCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + if (hyperHost.isHyperHostConnected()) { + return new CheckHealthAnswer(cmd, true); + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + s_logger.error("Unable to execute CheckHealthCommand due to " + VmwareHelper.getExceptionMessage(e), e); + } + return new CheckHealthAnswer(cmd, false); + } + + protected Answer execute(StopCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource StopCommand: " + _gson.toJson(cmd)); + } + + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + try { + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + if (vmMo != null) { + + State state = null; + synchronized (_vms) { + state = _vms.get(cmd.getVmName()); + _vms.put(cmd.getVmName(), State.Stopping); + } + try { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0"); - - if (getVmState(vmMo) != State.Stopped) { - Long bytesSent = 0L; - Long bytesRcvd = 0L; - - if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { - if (cmd.getPrivateRouterIpAddress() != null) { - long[] stats = getNetworkStats(cmd.getPrivateRouterIpAddress()); - bytesSent = stats[0]; - bytesRcvd = stats[1]; - } + + if (getVmState(vmMo) != State.Stopped) { + Long bytesSent = 0L; + Long bytesRcvd = 0L; + + if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { + if (cmd.getPrivateRouterIpAddress() != null) { + long[] stats = getNetworkStats(cmd.getPrivateRouterIpAddress()); + bytesSent = stats[0]; + bytesRcvd = stats[1]; + } } // before we stop VM, remove all possible snapshots on the VM to let // disk chain be collapsed s_logger.info("Remove all snapshot before stopping VM " + cmd.getVmName()); - vmMo.removeAllSnapshots(); - if (vmMo.safePowerOff(_shutdown_waitMs)) { - state = State.Stopped; - return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", 0, bytesSent, bytesRcvd); + vmMo.removeAllSnapshots(); + if (vmMo.safePowerOff(_shutdown_waitMs)) { + state = State.Stopped; + return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", 0, bytesSent, bytesRcvd); } else { String msg = "Have problem in powering off VM " + cmd.getVmName() + ", let the process continue"; s_logger.warn(msg); return new StopAnswer(cmd, msg, 0, 0L, 0L); } - } else { - state = State.Stopped; - } - - String msg = "VM " + cmd.getVmName() + " is already in stopped state"; - s_logger.info(msg); - return new StopAnswer(cmd, msg, 0, 0L, 0L); - } finally { - synchronized (_vms) { - _vms.put(cmd.getVmName(), state); - } - } - } else { - synchronized (_vms) { - _vms.remove(cmd.getVmName()); - } - - String msg = "VM " + cmd.getVmName() + " is no longer in vSphere"; - s_logger.info(msg); - return new StopAnswer(cmd, msg, 0, 0L, 0L); - } - } catch (Exception e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "StopCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg); - return new StopAnswer(cmd, msg); - } - } - - protected Answer execute(RebootRouterCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource RebootRouterCommand: " + _gson.toJson(cmd)); - } - - Long bytesSent = 0L; - Long bytesRcvd = 0L; - if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { - long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); - bytesSent = stats[0]; - bytesRcvd = stats[1]; - } - - RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); - answer.setBytesSent(bytesSent); - answer.setBytesReceived(bytesRcvd); - - if (answer.getResult()) { - String connectResult = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); - networkUsage(cmd.getPrivateIpAddress(), "create", null); - if (connectResult == null) { - return answer; - } else { - return new Answer(cmd, false, connectResult); - } - } - return answer; - } - - protected Answer execute(RebootCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource RebootCommand: " + _gson.toJson(cmd)); - } - - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - try { - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + } else { + state = State.Stopped; + } + + String msg = "VM " + cmd.getVmName() + " is already in stopped state"; + s_logger.info(msg); + return new StopAnswer(cmd, msg, 0, 0L, 0L); + } finally { + synchronized (_vms) { + _vms.put(cmd.getVmName(), state); + } + } + } else { + synchronized (_vms) { + _vms.remove(cmd.getVmName()); + } + + String msg = "VM " + cmd.getVmName() + " is no longer in vSphere"; + s_logger.info(msg); + return new StopAnswer(cmd, msg, 0, 0L, 0L); + } + } catch (Exception e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "StopCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg); + return new StopAnswer(cmd, msg); + } + } + + protected Answer execute(RebootRouterCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource RebootRouterCommand: " + _gson.toJson(cmd)); + } + + Long bytesSent = 0L; + Long bytesRcvd = 0L; + if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { + long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); + bytesSent = stats[0]; + bytesRcvd = stats[1]; + } + + RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); + answer.setBytesSent(bytesSent); + answer.setBytesReceived(bytesRcvd); + + if (answer.getResult()) { + String connectResult = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); + networkUsage(cmd.getPrivateIpAddress(), "create", null); + if (connectResult == null) { + return answer; + } else { + return new Answer(cmd, false, connectResult); + } + } + return answer; + } + + protected Answer execute(RebootCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource RebootCommand: " + _gson.toJson(cmd)); + } + + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + try { + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { vmMo.rebootGuest(); @@ -2089,95 +2089,95 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } // continue to try with hard-reset - if (vmMo.reset()) { - return new RebootAnswer(cmd, "reboot succeeded", null, null); - } - - String msg = "Reboot failed in vSphere. vm: " + cmd.getVmName(); - s_logger.warn(msg); - return new RebootAnswer(cmd, msg); - } else { - String msg = "Unable to find the VM in vSphere to reboot. vm: " + cmd.getVmName(); - s_logger.warn(msg); - return new RebootAnswer(cmd, msg); - } - } catch (Exception e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "RebootCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg); - return new RebootAnswer(cmd, msg); - } - } - - protected Answer execute(CheckVirtualMachineCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CheckVirtualMachineCommand: " + _gson.toJson(cmd)); - } - - final String vmName = cmd.getVmName(); - State state = State.Unknown; - Integer vncPort = null; - - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - - try { - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); - if (vmMo != null) { - state = getVmState(vmMo); - if (state == State.Running) { - synchronized (_vms) { - _vms.put(vmName, State.Running); - } - } - return new CheckVirtualMachineAnswer(cmd, state, vncPort); - } else { - s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand"); - return new CheckVirtualMachineAnswer(cmd, state, vncPort); - } - - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - s_logger.error("Unexpected exception: " + VmwareHelper.getExceptionMessage(e), e); - - return new CheckVirtualMachineAnswer(cmd, state, vncPort); - } - } - - protected Answer execute(PrepareForMigrationCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd)); - } - - VirtualMachineTO vm = cmd.getVirtualMachine(); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Preparing host for migrating " + vm); - } - - final String vmName = vm.getName(); - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + if (vmMo.reset()) { + return new RebootAnswer(cmd, "reboot succeeded", null, null); + } + + String msg = "Reboot failed in vSphere. vm: " + cmd.getVmName(); + s_logger.warn(msg); + return new RebootAnswer(cmd, msg); + } else { + String msg = "Unable to find the VM in vSphere to reboot. vm: " + cmd.getVmName(); + s_logger.warn(msg); + return new RebootAnswer(cmd, msg); + } + } catch (Exception e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "RebootCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg); + return new RebootAnswer(cmd, msg); + } + } + + protected Answer execute(CheckVirtualMachineCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CheckVirtualMachineCommand: " + _gson.toJson(cmd)); + } + + final String vmName = cmd.getVmName(); + State state = State.Unknown; + Integer vncPort = null; + + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + + try { + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); + if (vmMo != null) { + state = getVmState(vmMo); + if (state == State.Running) { + synchronized (_vms) { + _vms.put(vmName, State.Running); + } + } + return new CheckVirtualMachineAnswer(cmd, state, vncPort); + } else { + s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand"); + return new CheckVirtualMachineAnswer(cmd, state, vncPort); + } + + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + s_logger.error("Unexpected exception: " + VmwareHelper.getExceptionMessage(e), e); + + return new CheckVirtualMachineAnswer(cmd, state, vncPort); + } + } + + protected Answer execute(PrepareForMigrationCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd)); + } + + VirtualMachineTO vm = cmd.getVirtualMachine(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Preparing host for migrating " + vm); + } + + final String vmName = vm.getName(); + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - // find VM through datacenter (VM is not at the target host yet) - VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); - if (vmMo == null) { - String msg = "VM " + vmName + " does not exist in VMware datacenter"; - s_logger.error(msg); - throw new Exception(msg); - } - - NicTO[] nics = vm.getNics(); - for (NicTO nic : nics) { - // prepare network on the host - prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic); + + // find VM through datacenter (VM is not at the target host yet) + VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); + if (vmMo == null) { + String msg = "VM " + vmName + " does not exist in VMware datacenter"; + s_logger.error(msg); + throw new Exception(msg); + } + + NicTO[] nics = vm.getNics(); + for (NicTO nic : nics) { + // prepare network on the host + prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic); } String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); @@ -2192,678 +2192,678 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } - - synchronized (_vms) { - _vms.put(vm.getName(), State.Migrating); - } - return new PrepareForMigrationAnswer(cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new PrepareForMigrationAnswer(cmd, msg); - } - } - - protected Answer execute(MigrateCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd)); - } - - final String vmName = cmd.getVmName(); - - State state = null; - synchronized (_vms) { - state = _vms.get(vmName); - _vms.put(vmName, State.Stopping); - } - - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); - - // find VM through datacenter (VM is not at the target host yet) - VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); - if (vmMo == null) { - String msg = "VM " + vmName + " does not exist in VMware datacenter"; - s_logger.error(msg); - throw new Exception(msg); - } - - VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp()); - - ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo); - if (morTargetPhysicalHost == null) { - throw new Exception("Unable to find a target capable physical host"); - } - if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) { - throw new Exception("Migration failed"); - } - - state = State.Stopping; - return new MigrateAnswer(cmd, true, "migration succeeded", null); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.warn(msg, e); - return new MigrateAnswer(cmd, false, msg, null); - } finally { - synchronized (_vms) { - _vms.put(vmName, state); - } - } - } - + synchronized (_vms) { + _vms.put(vm.getName(), State.Migrating); + } + return new PrepareForMigrationAnswer(cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new PrepareForMigrationAnswer(cmd, msg); + } + } + + protected Answer execute(MigrateCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd)); + } + + final String vmName = cmd.getVmName(); + + State state = null; + synchronized (_vms) { + state = _vms.get(vmName); + _vms.put(vmName, State.Stopping); + } + + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); + + // find VM through datacenter (VM is not at the target host yet) + VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); + if (vmMo == null) { + String msg = "VM " + vmName + " does not exist in VMware datacenter"; + s_logger.error(msg); + throw new Exception(msg); + } + + VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp()); + + ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo); + if (morTargetPhysicalHost == null) { + throw new Exception("Unable to find a target capable physical host"); + } + + if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) { + throw new Exception("Migration failed"); + } + + state = State.Stopping; + return new MigrateAnswer(cmd, true, "migration succeeded", null); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.warn(msg, e); + return new MigrateAnswer(cmd, false, msg, null); + } finally { + synchronized (_vms) { + _vms.put(vmName, state); + } + } + } + private VmwareHypervisorHost getTargetHyperHost(DatacenterMO dcMo, String destIp) throws Exception { VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - ObjectContent[] ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); - if (ocs != null && ocs.length > 0) { - for (ObjectContent oc : ocs) { - HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); - VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); - if (destIp.equalsIgnoreCase(netSummary.getHostIp())) { - return new HostMO(dcMo.getContext(), oc.getObj()); - } - } - } - - throw new Exception("Unable to locate dest host by " + destIp); - } - - protected Answer execute(CreateStoragePoolCommand cmd) { - return new Answer(cmd, true, "success"); - } - - protected Answer execute(ModifyStoragePoolCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource ModifyStoragePoolCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - StorageFilerTO pool = cmd.getPool(); - + + ObjectContent[] ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); + if (ocs != null && ocs.length > 0) { + for (ObjectContent oc : ocs) { + HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); + VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); + if (destIp.equalsIgnoreCase(netSummary.getHostIp())) { + return new HostMO(dcMo.getContext(), oc.getObj()); + } + } + } + + throw new Exception("Unable to locate dest host by " + destIp); + } + + protected Answer execute(CreateStoragePoolCommand cmd) { + return new Answer(cmd, true, "success"); + } + + protected Answer execute(ModifyStoragePoolCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource ModifyStoragePoolCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + StorageFilerTO pool = cmd.getPool(); + if (pool.getType() != StoragePoolType.NetworkFilesystem && pool.getType() != StoragePoolType.VMFS) { throw new Exception("Unsupported storage pool type " + pool.getType()); - } - - ManagedObjectReference morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid()); - - assert (morDatastore != null); - DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); - long capacity = summary.getCapacity(); - long available = summary.getFreeSpace(); - Map tInfo = new HashMap(); - ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); - return answer; - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "ModifyStoragePoolCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - } - - protected Answer execute(DeleteStoragePoolCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource DeleteStoragePoolCommand: " + _gson.toJson(cmd)); - } - - StorageFilerTO pool = cmd.getPool(); + } + + ManagedObjectReference morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid()); + + assert (morDatastore != null); + DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); + long capacity = summary.getCapacity(); + long available = summary.getFreeSpace(); + Map tInfo = new HashMap(); + ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); + return answer; + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "ModifyStoragePoolCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + } + + protected Answer execute(DeleteStoragePoolCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource DeleteStoragePoolCommand: " + _gson.toJson(cmd)); + } + + StorageFilerTO pool = cmd.getPool(); try { // We will leave datastore cleanup management to vCenter. Since for cluster VMFS datastore, it will always // be mounted by vCenter. - - // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); - // hyperHost.unmountDatastore(pool.getUuid()); - Answer answer = new Answer(cmd, true, "success"); - return answer; - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "DeleteStoragePoolCommand (pool: " + pool.getHost() + ", path: " + pool.getPath() + ") failed due to " + VmwareHelper.getExceptionMessage(e); - return new Answer(cmd, false, msg); - } - } - - protected Answer execute(AttachVolumeCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource AttachVolumeCommand: " + _gson.toJson(cmd)); - } - - /* - * AttachVolumeCommand { "attach":true,"vmName":"i-2-1-KY","pooltype":"NetworkFilesystem", - * "volumeFolder":"/export/home/kelven/vmware-test/primary", "volumePath":"uuid", - * "volumeName":"volume name","deviceId":1 } - */ - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); - if (vmMo == null) { - String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); - s_logger.error(msg); - throw new Exception(msg); - } - - ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getPoolUuid()); - if (morDs == null) { - String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); - s_logger.error(msg); - throw new Exception(msg); - } - - DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); - String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getVolumePath()); - - AttachVolumeAnswer answer = new AttachVolumeAnswer(cmd, cmd.getDeviceId()); - if (cmd.getAttach()) { - vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); - } else { - vmMo.removeAllSnapshots(); - vmMo.detachDisk(datastoreVolumePath, false); - } - - return answer; - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new AttachVolumeAnswer(cmd, msg); - } - } - - protected Answer execute(AttachIsoCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); - if (vmMo == null) { - String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName(); - s_logger.error(msg); - throw new Exception(msg); - } - - String storeUrl = cmd.getStoreUrl(); - if (storeUrl == null) { - if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) { - String msg = "ISO store root url is not found in AttachIsoCommand"; - s_logger.error(msg); - throw new Exception(msg); - } else { - if (cmd.isAttach()) { - vmMo.mountToolsInstaller(); + + // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); + // hyperHost.unmountDatastore(pool.getUuid()); + Answer answer = new Answer(cmd, true, "success"); + return answer; + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "DeleteStoragePoolCommand (pool: " + pool.getHost() + ", path: " + pool.getPath() + ") failed due to " + VmwareHelper.getExceptionMessage(e); + return new Answer(cmd, false, msg); + } + } + + protected Answer execute(AttachVolumeCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource AttachVolumeCommand: " + _gson.toJson(cmd)); + } + + /* + * AttachVolumeCommand { "attach":true,"vmName":"i-2-1-KY","pooltype":"NetworkFilesystem", + * "volumeFolder":"/export/home/kelven/vmware-test/primary", "volumePath":"uuid", + * "volumeName":"volume name","deviceId":1 } + */ + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + if (vmMo == null) { + String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); + s_logger.error(msg); + throw new Exception(msg); + } + + ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getPoolUuid()); + if (morDs == null) { + String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); + s_logger.error(msg); + throw new Exception(msg); + } + + DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); + String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getVolumePath()); + + AttachVolumeAnswer answer = new AttachVolumeAnswer(cmd, cmd.getDeviceId()); + if (cmd.getAttach()) { + vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); + } else { + vmMo.removeAllSnapshots(); + vmMo.detachDisk(datastoreVolumePath, false); + } + + return answer; + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new AttachVolumeAnswer(cmd, msg); + } + } + + protected Answer execute(AttachIsoCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); + if (vmMo == null) { + String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName(); + s_logger.error(msg); + throw new Exception(msg); + } + + String storeUrl = cmd.getStoreUrl(); + if (storeUrl == null) { + if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) { + String msg = "ISO store root url is not found in AttachIsoCommand"; + s_logger.error(msg); + throw new Exception(msg); + } else { + if (cmd.isAttach()) { + vmMo.mountToolsInstaller(); } else { - vmMo.unmountToolsInstaller(); - } + vmMo.unmountToolsInstaller(); + } - return new Answer(cmd); - } - } - - ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl); - String isoPath = cmd.getIsoPath(); - if (!isoPath.startsWith(storeUrl)) { - assert (false); - String msg = "ISO path does not start with the secondary storage root"; - s_logger.error(msg); - throw new Exception(msg); - } - - int isoNameStartPos = isoPath.lastIndexOf('/'); - String isoFileName = isoPath.substring(isoNameStartPos + 1); - String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos); - - // TODO, check if iso is already attached, or if there is a previous - // attachment - String isoDatastorePath = String.format("[%s] %s%s", getSecondaryDatastoreUUID(storeUrl), isoStorePathFromRoot, isoFileName); - - if (cmd.isAttach()) { - vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false); - } else { - vmMo.detachIso(isoDatastorePath); - } - - return new Answer(cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } + return new Answer(cmd); + } + } - if(cmd.isAttach()) { - String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); + ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl); + String isoPath = cmd.getIsoPath(); + if (!isoPath.startsWith(storeUrl)) { + assert (false); + String msg = "ISO path does not start with the secondary storage root"; + s_logger.error(msg); + throw new Exception(msg); + } + + int isoNameStartPos = isoPath.lastIndexOf('/'); + String isoFileName = isoPath.substring(isoNameStartPos + 1); + String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos); + + // TODO, check if iso is already attached, or if there is a previous + // attachment + String isoDatastorePath = String.format("[%s] %s%s", getSecondaryDatastoreUUID(storeUrl), isoStorePathFromRoot, isoFileName); + + if (cmd.isAttach()) { + vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false); + } else { + vmMo.detachIso(isoDatastorePath); + } + + return new Answer(cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + if(cmd.isAttach()) { + String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); return new Answer(cmd, false, msg); } else { String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new Answer(cmd, false, msg); - } - } - } - - private synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception { - String storeName = getSecondaryDatastoreUUID(storeUrl); - URI uri = new URI(storeUrl); - - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName); - - if (morDatastore == null) { - throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl); - } - - return morDatastore; - } - - private static String getSecondaryDatastoreUUID(String storeUrl) { - return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString(); - } - - protected Answer execute(ValidateSnapshotCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource ValidateSnapshotCommand: " + _gson.toJson(cmd)); - } - - // the command is no longer available - String expectedSnapshotBackupUuid = null; - String actualSnapshotBackupUuid = null; - String actualSnapshotUuid = null; - return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); - } - - protected Answer execute(ManageSnapshotCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource ManageSnapshotCommand: " + _gson.toJson(cmd)); - } - - long snapshotId = cmd.getSnapshotId(); - - /* - * "ManageSnapshotCommand", - * "{\"_commandSwitch\":\"-c\",\"_volumePath\":\"i-2-3-KY-ROOT\",\"_snapshotName\":\"i-2-3-KY_i-2-3-KY-ROOT_20101102203827\",\"_snapshotId\":1,\"_vmName\":\"i-2-3-KY\"}" - */ - boolean success = false; - String cmdSwitch = cmd.getCommandSwitch(); - String snapshotOp = "Unsupported snapshot command." + cmdSwitch; - if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { - snapshotOp = "create"; - } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { - snapshotOp = "destroy"; - } - - String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; - String snapshotUUID = null; + } + } + } + + private synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception { + String storeName = getSecondaryDatastoreUUID(storeUrl); + URI uri = new URI(storeUrl); + + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName); + + if (morDatastore == null) { + throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl); + } + + return morDatastore; + } + + private static String getSecondaryDatastoreUUID(String storeUrl) { + return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString(); + } + + protected Answer execute(ValidateSnapshotCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource ValidateSnapshotCommand: " + _gson.toJson(cmd)); + } + + // the command is no longer available + String expectedSnapshotBackupUuid = null; + String actualSnapshotBackupUuid = null; + String actualSnapshotUuid = null; + return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); + } + + protected Answer execute(ManageSnapshotCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource ManageSnapshotCommand: " + _gson.toJson(cmd)); + } + + long snapshotId = cmd.getSnapshotId(); + + /* + * "ManageSnapshotCommand", + * "{\"_commandSwitch\":\"-c\",\"_volumePath\":\"i-2-3-KY-ROOT\",\"_snapshotName\":\"i-2-3-KY_i-2-3-KY-ROOT_20101102203827\",\"_snapshotId\":1,\"_vmName\":\"i-2-3-KY\"}" + */ + boolean success = false; + String cmdSwitch = cmd.getCommandSwitch(); + String snapshotOp = "Unsupported snapshot command." + cmdSwitch; + if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { + snapshotOp = "create"; + } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { + snapshotOp = "destroy"; + } + + String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; + String snapshotUUID = null; // snapshot operation (create or destroy) is handled inside BackupSnapshotCommand(), we just fake // a success return here snapshotUUID = UUID.randomUUID().toString(); success = true; details = null; - - return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); - } - - protected Answer execute(BackupSnapshotCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource BackupSnapshotCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - return mgr.getStorageManager().execute(this, cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String details = "BackupSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(details, e); - return new BackupSnapshotAnswer(cmd, false, details, null, true); - } - } - - - protected Answer execute(CreateVolumeFromSnapshotCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CreateVolumeFromSnapshotCommand: " + _gson.toJson(cmd)); - } - - String details = null; - boolean success = false; - String newVolumeName = UUID.randomUUID().toString(); - - try { - VmwareContext context = getServiceContext(); - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - return mgr.getStorageManager().execute(this, cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - details = "CreateVolumeFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(details, e); - } - - return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); - } - - protected Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CreatePrivateTemplateFromVolumeCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - return mgr.getStorageManager().execute(this, cmd); - - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String details = "CreatePrivateTemplateFromVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(details, e); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - } - - protected Answer execute(final UpgradeSnapshotCommand cmd) { - return new Answer(cmd, true, "success"); - } - - protected Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CreatePrivateTemplateFromSnapshotCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - return mgr.getStorageManager().execute(this, cmd); - - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String details = "CreatePrivateTemplateFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(details, e); - return new CreatePrivateTemplateAnswer(cmd, false, details); - } - } - - protected Answer execute(GetStorageStatsCommand cmd) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Executing resource GetStorageStatsCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getStorageId()); - - if (morDs != null) { - DatastoreMO datastoreMo = new DatastoreMO(context, morDs); - DatastoreSummary summary = datastoreMo.getSummary(); - assert (summary != null); - - long capacity = summary.getCapacity(); - long free = summary.getFreeSpace(); - long used = capacity - free; - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ", capacity: " + capacity - + ", free: " + free + ", used: " + used); - } - - if (summary.getCapacity() <= 0) { - s_logger.warn("Something is wrong with vSphere NFS datastore, rebooting ESX(ESXi) host should help"); - } - - return new GetStorageStatsAnswer(cmd, capacity, used); - } else { - String msg = "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype(); - - s_logger.error(msg); - return new GetStorageStatsAnswer(cmd, msg); - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " - + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new GetStorageStatsAnswer(cmd, msg); - } - } - - protected Answer execute(GetVncPortCommand cmd) { - if (s_logger.isTraceEnabled()) { - s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - assert(hyperHost instanceof HostMO); + + return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); + } + + protected Answer execute(BackupSnapshotCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource BackupSnapshotCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName()); - if (vmMo == null) { + return mgr.getStorageManager().execute(this, cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String details = "BackupSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(details, e); + return new BackupSnapshotAnswer(cmd, false, details, null, true); + } + } + + + protected Answer execute(CreateVolumeFromSnapshotCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CreateVolumeFromSnapshotCommand: " + _gson.toJson(cmd)); + } + + String details = null; + boolean success = false; + String newVolumeName = UUID.randomUUID().toString(); + + try { + VmwareContext context = getServiceContext(); + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + return mgr.getStorageManager().execute(this, cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + details = "CreateVolumeFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(details, e); + } + + return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); + } + + protected Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CreatePrivateTemplateFromVolumeCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + + return mgr.getStorageManager().execute(this, cmd); + + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String details = "CreatePrivateTemplateFromVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(details, e); + return new CreatePrivateTemplateAnswer(cmd, false, details); + } + } + + protected Answer execute(final UpgradeSnapshotCommand cmd) { + return new Answer(cmd, true, "success"); + } + + protected Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CreatePrivateTemplateFromSnapshotCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + return mgr.getStorageManager().execute(this, cmd); + + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String details = "CreatePrivateTemplateFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(details, e); + return new CreatePrivateTemplateAnswer(cmd, false, details); + } + } + + protected Answer execute(GetStorageStatsCommand cmd) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Executing resource GetStorageStatsCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getStorageId()); + + if (morDs != null) { + DatastoreMO datastoreMo = new DatastoreMO(context, morDs); + DatastoreSummary summary = datastoreMo.getSummary(); + assert (summary != null); + + long capacity = summary.getCapacity(); + long free = summary.getFreeSpace(); + long used = capacity - free; + + if (s_logger.isDebugEnabled()) { + s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ", capacity: " + capacity + + ", free: " + free + ", used: " + used); + } + + if (summary.getCapacity() <= 0) { + s_logger.warn("Something is wrong with vSphere NFS datastore, rebooting ESX(ESXi) host should help"); + } + + return new GetStorageStatsAnswer(cmd, capacity, used); + } else { + String msg = "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype(); + + s_logger.error(msg); + return new GetStorageStatsAnswer(cmd, msg); + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " + + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new GetStorageStatsAnswer(cmd, msg); + } + } + + protected Answer execute(GetVncPortCommand cmd) { + if (s_logger.isTraceEnabled()) { + s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + assert(hyperHost instanceof HostMO); + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName()); + if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); - } - - vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName()); - + } + + vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName()); + if (vmMo == null) { throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName()); - } + } } - - Pair portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second()); - } - return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second()); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new GetVncPortAnswer(cmd, msg); - } - } - - protected Answer execute(SetupCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource SetupCommand: " + _gson.toJson(cmd)); - } - - return new SetupAnswer(cmd, false); - } - - protected Answer execute(MaintainCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource MaintainCommand: " + _gson.toJson(cmd)); - } - - return new MaintainAnswer(cmd, "Put host in maintaince"); - } - - protected Answer execute(PingTestCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource PingTestCommand: " + _gson.toJson(cmd)); - } - - return new Answer(cmd); - } - - protected Answer execute(CheckOnHostCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CheckOnHostCommand: " + _gson.toJson(cmd)); - } - - return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); - } - + + Pair portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second()); + } + return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second()); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new GetVncPortAnswer(cmd, msg); + } + } + + protected Answer execute(SetupCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource SetupCommand: " + _gson.toJson(cmd)); + } + + return new SetupAnswer(cmd, false); + } + + protected Answer execute(MaintainCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource MaintainCommand: " + _gson.toJson(cmd)); + } + + return new MaintainAnswer(cmd, "Put host in maintaince"); + } + + protected Answer execute(PingTestCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource PingTestCommand: " + _gson.toJson(cmd)); + } + + return new Answer(cmd); + } + + protected Answer execute(CheckOnHostCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CheckOnHostCommand: " + _gson.toJson(cmd)); + } + + return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); + } + protected Answer execute(ModifySshKeysCommand cmd) { - //do not log the command contents for this command. do NOT log the ssh keys - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource ModifySshKeysCommand."); - } - - return new Answer(cmd); - } - - protected Answer execute(PoolEjectCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource PoolEjectCommand: " + _gson.toJson(cmd)); - } - - return new Answer(cmd, false, "PoolEjectCommand is not available for vmware"); - } - - @Override - public PrimaryStorageDownloadAnswer execute(PrimaryStorageDownloadCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource PrimaryStorageDownloadCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - return (PrimaryStorageDownloadAnswer) mgr.getStorageManager().execute(this, cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "PrimaryStorageDownloadCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new PrimaryStorageDownloadAnswer(msg); - } - } - - @Override - public Answer execute(DestroyCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd)); - } - - /* - * DestroyCommand content example - * - * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", - * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": - * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } - * - * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", - * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", - * "poolId":0,"deviceId":0 } } - */ - - try { - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - VolumeTO vol = cmd.getVolume(); - - ManagedObjectReference morDs = hyperHost.findDatastore(vol.getPoolUuid()); - if (morDs == null) { - String msg = "Unable to find datastore based on volume mount point " + cmd.getVolume().getMountPoint(); - s_logger.error(msg); - throw new Exception(msg); - } - + //do not log the command contents for this command. do NOT log the ssh keys + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource ModifySshKeysCommand."); + } + + return new Answer(cmd); + } + + protected Answer execute(PoolEjectCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource PoolEjectCommand: " + _gson.toJson(cmd)); + } + + return new Answer(cmd, false, "PoolEjectCommand is not available for vmware"); + } + + @Override + public PrimaryStorageDownloadAnswer execute(PrimaryStorageDownloadCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource PrimaryStorageDownloadCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + return (PrimaryStorageDownloadAnswer) mgr.getStorageManager().execute(this, cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "PrimaryStorageDownloadCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new PrimaryStorageDownloadAnswer(msg); + } + } + + @Override + public Answer execute(DestroyCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd)); + } + + /* + * DestroyCommand content example + * + * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", + * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": + * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } + * + * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", + * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", + * "poolId":0,"deviceId":0 } } + */ + + try { + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + VolumeTO vol = cmd.getVolume(); + + ManagedObjectReference morDs = hyperHost.findDatastore(vol.getPoolUuid()); + if (morDs == null) { + String msg = "Unable to find datastore based on volume mount point " + cmd.getVolume().getMountPoint(); + s_logger.error(msg); + throw new Exception(msg); + } + DatastoreMO dsMo = new DatastoreMO(context, morDs); - - ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); + + ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(context, morCluster); - - if (cmd.getVolume().getType() == Volume.Type.ROOT) { - String vmName = cmd.getVmName(); - if (vmName != null) { - VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName); - if (vmMo != null) { + + if (cmd.getVolume().getType() == Volume.Type.ROOT) { + String vmName = cmd.getVmName(); + if (vmName != null) { + VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName); + if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume and VM itself. vmName " + vmName); - } - - HostMO hostMo = vmMo.getRunningHost(); - List networks = vmMo.getNetworksWithDetails(); - + } + + HostMO hostMo = vmMo.getRunningHost(); + List networks = vmMo.getNetworksWithDetails(); + // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (getVmState(vmMo) != State.Stopped) - vmMo.safePowerOff(_shutdown_waitMs); - vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); - vmMo.destroy(); - - for (NetworkDetails netDetails : networks) { - if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { - if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { - cleanupNetwork(hostMo, netDetails); - } - } - } - } - - if (s_logger.isInfoEnabled()) - s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); + vmMo.safePowerOff(_shutdown_waitMs); + vmMo.tearDownDevices(new Class[] { VirtualDisk.class, VirtualEthernetCard.class }); + vmMo.destroy(); + + for (NetworkDetails netDetails : networks) { + if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { + if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { + cleanupNetwork(hostMo, netDetails); + } + } + } + } + + if (s_logger.isInfoEnabled()) + s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); // root volume may be created via linked-clone, delete the delta disk as well if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-delta.vmdk"); dsMo.deleteFile(cmd.getVolume().getPath() + "-delta.vmdk", morDc, true); - return new Answer(cmd, true, "Success"); - } - + return new Answer(cmd, true, "Success"); + } + if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume directly from datastore"); - } + } } else { // evitTemplate will be converted into DestroyCommand, test if we are running in this case VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(cmd.getVolume().getPath()); @@ -2874,174 +2874,174 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa vmMo.destroy(); return new Answer(cmd, true, "Success"); } - } - - String chainInfo = cmd.getVolume().getChainInfo(); - if (chainInfo != null && !chainInfo.isEmpty()) { - s_logger.info("Destroy volume by chain info: " + chainInfo); - String[] diskChain = _gson.fromJson(chainInfo, String[].class); - - if (diskChain != null && diskChain.length > 0) { - for (String backingName : diskChain) { + } + + String chainInfo = cmd.getVolume().getChainInfo(); + if (chainInfo != null && !chainInfo.isEmpty()) { + s_logger.info("Destroy volume by chain info: " + chainInfo); + String[] diskChain = _gson.fromJson(chainInfo, String[].class); + + if (diskChain != null && diskChain.length > 0) { + for (String backingName : diskChain) { if (s_logger.isInfoEnabled()) { s_logger.info("Delete volume backing file: " + backingName); - } - dsMo.deleteFile(backingName, morDc, true); - } - } else { + } + dsMo.deleteFile(backingName, morDc, true); + } + } else { if (s_logger.isInfoEnabled()) { s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name"); - } + } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + "-flat.vmdk", morDc, true); - } - } else { + } + } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); - } + } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + "-flat.vmdk", morDc, true); - } - - return new Answer(cmd, true, "Success"); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new Answer(cmd, false, msg); - } - } - - private void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) { - // we will no longer cleanup VLAN networks in order to support native VMware HA - /* - * assert(netDetails.getName() != null); try { synchronized(this) { NetworkMO networkMo = new - * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = - * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { - * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } - * - * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { - * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } - */ - } - - @Override - public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CopyVolumeCommand: " + _gson.toJson(cmd)); - } - - try { - VmwareContext context = getServiceContext(); - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - return (CopyVolumeAnswer) mgr.getStorageManager().execute(this, cmd); - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "CopyVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new CopyVolumeAnswer(cmd, false, msg, null, null); - } - } - - @Override - public synchronized CreateAnswer execute(CreateCommand cmd) { - if (s_logger.isInfoEnabled()) { - s_logger.info("Executing resource CreateCommand: " + _gson.toJson(cmd)); - } - - StorageFilerTO pool = cmd.getPool(); + } + + return new Answer(cmd, true, "Success"); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new Answer(cmd, false, msg); + } + } + + private void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) { + // we will no longer cleanup VLAN networks in order to support native VMware HA + /* + * assert(netDetails.getName() != null); try { synchronized(this) { NetworkMO networkMo = new + * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = + * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { + * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } + * + * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { + * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } + */ + } + + @Override + public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CopyVolumeCommand: " + _gson.toJson(cmd)); + } + + try { + VmwareContext context = getServiceContext(); + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + return (CopyVolumeAnswer) mgr.getStorageManager().execute(this, cmd); + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "CopyVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new CopyVolumeAnswer(cmd, false, msg, null, null); + } + } + + @Override + public synchronized CreateAnswer execute(CreateCommand cmd) { + if (s_logger.isInfoEnabled()) { + s_logger.info("Executing resource CreateCommand: " + _gson.toJson(cmd)); + } + + StorageFilerTO pool = cmd.getPool(); DiskProfile dskch = cmd.getDiskCharacteristics(); - try { - VmwareContext context = getServiceContext(); - VmwareHypervisorHost hyperHost = getHyperHost(context); - DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); + try { + VmwareContext context = getServiceContext(); + VmwareHypervisorHost hyperHost = getHyperHost(context); + DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); VmwareManager vmwareMgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - ManagedObjectReference morDatastore = hyperHost.findDatastore(pool.getUuid()); - if (morDatastore == null) { - throw new Exception("Unable to find datastore in vSphere"); - } - DatastoreMO dsMo = new DatastoreMO(context, morDatastore); - - if (cmd.getDiskCharacteristics().getType() == Volume.Type.ROOT) { - if (cmd.getTemplateUrl() == null) { - // create a root volume for blank VM - String dummyVmName = getWorkerName(context, cmd, 0); + + ManagedObjectReference morDatastore = hyperHost.findDatastore(pool.getUuid()); + if (morDatastore == null) { + throw new Exception("Unable to find datastore in vSphere"); + } + DatastoreMO dsMo = new DatastoreMO(context, morDatastore); + + if (cmd.getDiskCharacteristics().getType() == Volume.Type.ROOT) { + if (cmd.getTemplateUrl() == null) { + // create a root volume for blank VM + String dummyVmName = getWorkerName(context, cmd, 0); VirtualMachineMO vmMo = null; - try { - vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); - if (vmMo == null) { - throw new Exception("Unable to create a dummy VM for volume creation"); - } - - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getDiskCharacteristics().getName()); - synchronized (this) { - s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); - VmwareHelper.deleteVolumeVmdkFiles(dsMo, cmd.getDiskCharacteristics().getName(), dcMo); - vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, -1); - vmMo.detachDisk(volumeDatastorePath, false); - } - - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), cmd - .getDiskCharacteristics().getName(), cmd.getDiskCharacteristics().getSize(), null); - return new CreateAnswer(cmd, vol); - } finally { - vmMo.detachAllDisks(); - - s_logger.info("Destroy dummy VM after volume creation"); + try { + vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); + if (vmMo == null) { + throw new Exception("Unable to create a dummy VM for volume creation"); + } + + String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getDiskCharacteristics().getName()); + synchronized (this) { + s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); + VmwareHelper.deleteVolumeVmdkFiles(dsMo, cmd.getDiskCharacteristics().getName(), dcMo); + vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, -1); + vmMo.detachDisk(volumeDatastorePath, false); + } + + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), cmd + .getDiskCharacteristics().getName(), cmd.getDiskCharacteristics().getSize(), null); + return new CreateAnswer(cmd, vol); + } finally { + vmMo.detachAllDisks(); + + s_logger.info("Destroy dummy VM after volume creation"); vmMo.destroy(); - } - } else { - VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(cmd.getTemplateUrl()), true); - if (vmTemplate == null) { + } + } else { + VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(cmd.getTemplateUrl()), true); + if (vmTemplate == null) { s_logger.warn("Template host in vSphere is not in connected state, request template reload"); return new CreateAnswer(cmd, "Template host in vSphere is not in connected state, request template reload", true); } ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool(); - ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); - ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); - if (morBaseSnapshot == null) { - String msg = "Unable to find template base snapshot, invalid template"; - s_logger.error(msg); - throw new Exception(msg); - } - + ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); + ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); + if (morBaseSnapshot == null) { + String msg = "Unable to find template base snapshot, invalid template"; + s_logger.error(msg); + throw new Exception(msg); + } + String name = cmd.getDiskCharacteristics().getName(); - if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), name)) - dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), name), dcMo.getMor(), false); - - s_logger.info("create linked clone from template"); - if (!vmTemplate.createLinkedClone(name, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { - String msg = "Unable to clone from the template"; - s_logger.error(msg); - throw new Exception(msg); - } - - VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(name); - assert (vmMo != null); + if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), name)) + dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), name), dcMo.getMor(), false); + + s_logger.info("create linked clone from template"); + if (!vmTemplate.createLinkedClone(name, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { + String msg = "Unable to clone from the template"; + s_logger.error(msg); + throw new Exception(msg); + } + + VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(name); + assert (vmMo != null); // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know - // to move files + // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), name, name), dcMo.getMor(), dsMo.getMor(), @@ -3050,106 +3050,106 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), name, name), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-delta.vmdk", dsMo.getName(), name), dcMo.getMor(), true); - - s_logger.info("detach disks from volume-wrapper VM " + name); - vmMo.detachAllDisks(); - - s_logger.info("destroy volume-wrapper VM " + name); - vmMo.destroy(); - - String srcFile = String.format("[%s] %s/", dsMo.getName(), name); - dsMo.deleteFile(srcFile, dcMo.getMor(), true); - - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), name, pool.getPath(), name, cmd.getDiskCharacteristics().getSize(), null); - return new CreateAnswer(cmd, vol); - } - } else { - // create data volume - VirtualMachineMO vmMo = null; - String volumeUuid = UUID.randomUUID().toString().replace("-", ""); - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid); - String dummyVmName = getWorkerName(context, cmd, 0); - try { - vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); - if (vmMo == null) { - throw new Exception("Unable to create a dummy VM for volume creation"); - } - - synchronized (this) { - // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); - VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); - - vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey()); - vmMo.detachDisk(volumeDatastorePath, false); - } - - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), volumeUuid, cmd - .getDiskCharacteristics().getSize(), null); - return new CreateAnswer(cmd, vol); - } finally { - s_logger.info("Destroy dummy VM after volume creation"); - vmMo.detachAllDisks(); - vmMo.destroy(); - } - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - return new CreateAnswer(cmd, new Exception(e)); - } - } - - protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception { - assert (hyperHost != null); - - VirtualMachineMO vmMo = null; - VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); - vmConfig.setName(vmName); - vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB - vmConfig.setNumCPUs(1); - vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString()); - VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); - fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); - vmConfig.setFiles(fileInfo); - - // Scsi controller - VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); - scsiController.setSharedBus(VirtualSCSISharing.noSharing); - scsiController.setBusNumber(0); - scsiController.setKey(1); - VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); - scsiControllerSpec.setDevice(scsiController); - scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); - - vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); - hyperHost.createVm(vmConfig); - vmMo = hyperHost.findVmOnHyperHost(vmName); - return vmMo; - } - - @Override - public void disconnected() { - } - - @Override - public IAgentControl getAgentControl() { - return null; - } - - @Override - public PingCommand getCurrentStatus(long id) { - HashMap newStates = sync(); - if (newStates == null) { - return null; - } - - try { - // take the chance to do left-over dummy VM cleanup from previous run + + s_logger.info("detach disks from volume-wrapper VM " + name); + vmMo.detachAllDisks(); + + s_logger.info("destroy volume-wrapper VM " + name); + vmMo.destroy(); + + String srcFile = String.format("[%s] %s/", dsMo.getName(), name); + dsMo.deleteFile(srcFile, dcMo.getMor(), true); + + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), name, pool.getPath(), name, cmd.getDiskCharacteristics().getSize(), null); + return new CreateAnswer(cmd, vol); + } + } else { + // create data volume + VirtualMachineMO vmMo = null; + String volumeUuid = UUID.randomUUID().toString().replace("-", ""); + String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid); + String dummyVmName = getWorkerName(context, cmd, 0); + try { + vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); + if (vmMo == null) { + throw new Exception("Unable to create a dummy VM for volume creation"); + } + + synchronized (this) { + // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); + VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); + + vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey()); + vmMo.detachDisk(volumeDatastorePath, false); + } + + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), volumeUuid, cmd + .getDiskCharacteristics().getSize(), null); + return new CreateAnswer(cmd, vol); + } finally { + s_logger.info("Destroy dummy VM after volume creation"); + vmMo.detachAllDisks(); + vmMo.destroy(); + } + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + return new CreateAnswer(cmd, new Exception(e)); + } + } + + protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception { + assert (hyperHost != null); + + VirtualMachineMO vmMo = null; + VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); + vmConfig.setName(vmName); + vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB + vmConfig.setNumCPUs(1); + vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString()); + VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); + fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); + vmConfig.setFiles(fileInfo); + + // Scsi controller + VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); + scsiController.setSharedBus(VirtualSCSISharing.noSharing); + scsiController.setBusNumber(0); + scsiController.setKey(1); + VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); + scsiControllerSpec.setDevice(scsiController); + scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); + + vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); + hyperHost.createVm(vmConfig); + vmMo = hyperHost.findVmOnHyperHost(vmName); + return vmMo; + } + + @Override + public void disconnected() { + } + + @Override + public IAgentControl getAgentControl() { + return null; + } + + @Override + public PingCommand getCurrentStatus(long id) { + HashMap newStates = sync(); + if (newStates == null) { + return null; + } + + try { + // take the chance to do left-over dummy VM cleanup from previous run VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); @@ -3208,23 +3208,23 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa s_logger.error("Host is no longer connected."); return null; } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - return null; - } - } - - return new PingRoutingCommand(getType(), id, newStates); - } - - @Override - public Type getType() { - return com.cloud.host.Host.Type.Routing; - } - - @Override + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + return null; + } + } + + return new PingRoutingCommand(getType(), id, newStates); + } + + @Override + public Type getType() { + return com.cloud.host.Host.Type.Routing; + } + + @Override public StartupCommand[] initialize() { String hostApiVersion = "4.1"; VmwareContext context = getServiceContext(); @@ -3245,232 +3245,232 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa invalidateServiceContext(); return null; } - - StartupRoutingCommand cmd = new StartupRoutingCommand(); - fillHostInfo(cmd); - - Map changes = null; - synchronized (_vms) { - _vms.clear(); - changes = sync(); - } - - cmd.setHypervisorType(HypervisorType.VMware); - cmd.setStateChanges(changes); + + StartupRoutingCommand cmd = new StartupRoutingCommand(); + fillHostInfo(cmd); + + Map changes = null; + synchronized (_vms) { + _vms.clear(); + changes = sync(); + } + + cmd.setHypervisorType(HypervisorType.VMware); + cmd.setStateChanges(changes); cmd.setCluster(_cluster); - cmd.setVersion(hostApiVersion); - - List storageCmds = initializeLocalStorage(); - StartupCommand[] answerCmds = new StartupCommand[1 + storageCmds.size()]; - answerCmds[0] = cmd; - for (int i = 0; i < storageCmds.size(); i++) { - answerCmds[i + 1] = storageCmds.get(i); - } - - return answerCmds; - } - - private List initializeLocalStorage() { - List storageCmds = new ArrayList(); - VmwareContext context = getServiceContext(); - - try { - VmwareHypervisorHost hyperHost = getHyperHost(context); - if (hyperHost instanceof HostMO) { - HostMO hostMo = (HostMO) hyperHost; - - List> dsList = hostMo.getLocalDatastoreOnHost(); - for (Pair dsPair : dsList) { - DatastoreMO dsMo = new DatastoreMO(context, dsPair.first()); - - String poolUuid = dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID); - if (poolUuid == null || poolUuid.isEmpty()) { - poolUuid = UUID.randomUUID().toString(); - dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); - } - - DatastoreSummary dsSummary = dsMo.getSummary(); - String address = hostMo.getHostName(); - StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().get_value(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); - StartupStorageCommand cmd = new StartupStorageCommand(); - cmd.setName(poolUuid); - cmd.setPoolInfo(pInfo); - cmd.setGuid(poolUuid); // give storage host the same UUID as the local storage pool itself - cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); - cmd.setDataCenter(_dcId); - cmd.setPod(_pod); - cmd.setCluster(_cluster); - - s_logger.info("Add local storage startup command: " + _gson.toJson(cmd)); - storageCmds.add(cmd); - } - - } else { - s_logger.info("Cluster host does not support local storage, skip it"); - } - } catch (Exception e) { - String msg = "initializing local storage failed due to : " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg); - invalidateServiceContext(); - throw new CloudRuntimeException(msg); - } - - return storageCmds; - } - - protected void fillHostInfo(StartupRoutingCommand cmd) { - VmwareContext serviceContext = getServiceContext(); - Map details = cmd.getHostDetails(); - if (details == null) { - details = new HashMap(); - } - - try { - fillHostHardwareInfo(serviceContext, cmd); - fillHostNetworkInfo(serviceContext, cmd); - fillHostDetailsInfo(serviceContext, details); - } catch (RuntimeFault e) { - s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); - throw new CloudRuntimeException("RuntimeFault while retrieving host info"); - } catch (RemoteException e) { - s_logger.error("RemoteException while retrieving host info: " + e.toString(), e); - invalidateServiceContext(); - throw new CloudRuntimeException("RemoteException while retrieving host info"); - } catch (Exception e) { - s_logger.error("Exception while retrieving host info: " + e.toString(), e); - invalidateServiceContext(); - throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString()); - } - - cmd.setHostDetails(details); - cmd.setName(_url); - cmd.setGuid(_guid); - cmd.setDataCenter(_dcId); - cmd.setPod(_pod); - cmd.setCluster(_cluster); - cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); - } - - private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException, Exception { - - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); - - if (s_logger.isInfoEnabled()) { - s_logger.info("Startup report on host hardware info. " + _gson.toJson(summary)); - } - - cmd.setCaps("hvm"); - cmd.setDom0MinMemory(0); - cmd.setSpeed(summary.getCpuSpeed()); - cmd.setCpus((int) summary.getCpuCount()); - cmd.setMemory(summary.getMemoryBytes()); - } - - private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException { - - try { + cmd.setVersion(hostApiVersion); + + List storageCmds = initializeLocalStorage(); + StartupCommand[] answerCmds = new StartupCommand[1 + storageCmds.size()]; + answerCmds[0] = cmd; + for (int i = 0; i < storageCmds.size(); i++) { + answerCmds[i + 1] = storageCmds.get(i); + } + + return answerCmds; + } + + private List initializeLocalStorage() { + List storageCmds = new ArrayList(); + VmwareContext context = getServiceContext(); + + try { + VmwareHypervisorHost hyperHost = getHyperHost(context); + if (hyperHost instanceof HostMO) { + HostMO hostMo = (HostMO) hyperHost; + + List> dsList = hostMo.getLocalDatastoreOnHost(); + for (Pair dsPair : dsList) { + DatastoreMO dsMo = new DatastoreMO(context, dsPair.first()); + + String poolUuid = dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID); + if (poolUuid == null || poolUuid.isEmpty()) { + poolUuid = UUID.randomUUID().toString(); + dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); + } + + DatastoreSummary dsSummary = dsMo.getSummary(); + String address = hostMo.getHostName(); + StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().get_value(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); + StartupStorageCommand cmd = new StartupStorageCommand(); + cmd.setName(poolUuid); + cmd.setPoolInfo(pInfo); + cmd.setGuid(poolUuid); // give storage host the same UUID as the local storage pool itself + cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); + cmd.setDataCenter(_dcId); + cmd.setPod(_pod); + cmd.setCluster(_cluster); + + s_logger.info("Add local storage startup command: " + _gson.toJson(cmd)); + storageCmds.add(cmd); + } + + } else { + s_logger.info("Cluster host does not support local storage, skip it"); + } + } catch (Exception e) { + String msg = "initializing local storage failed due to : " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg); + invalidateServiceContext(); + throw new CloudRuntimeException(msg); + } + + return storageCmds; + } + + protected void fillHostInfo(StartupRoutingCommand cmd) { + VmwareContext serviceContext = getServiceContext(); + Map details = cmd.getHostDetails(); + if (details == null) { + details = new HashMap(); + } + + try { + fillHostHardwareInfo(serviceContext, cmd); + fillHostNetworkInfo(serviceContext, cmd); + fillHostDetailsInfo(serviceContext, details); + } catch (RuntimeFault e) { + s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); + throw new CloudRuntimeException("RuntimeFault while retrieving host info"); + } catch (RemoteException e) { + s_logger.error("RemoteException while retrieving host info: " + e.toString(), e); + invalidateServiceContext(); + throw new CloudRuntimeException("RemoteException while retrieving host info"); + } catch (Exception e) { + s_logger.error("Exception while retrieving host info: " + e.toString(), e); + invalidateServiceContext(); + throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString()); + } + + cmd.setHostDetails(details); + cmd.setName(_url); + cmd.setGuid(_guid); + cmd.setDataCenter(_dcId); + cmd.setPod(_pod); + cmd.setCluster(_cluster); + cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); + } + + private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException, Exception { + + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); + + if (s_logger.isInfoEnabled()) { + s_logger.info("Startup report on host hardware info. " + _gson.toJson(summary)); + } + + cmd.setCaps("hvm"); + cmd.setDom0MinMemory(0); + cmd.setSpeed(summary.getCpuSpeed()); + cmd.setCpus((int) summary.getCpuCount()); + cmd.setMemory(summary.getMemoryBytes()); + } + + private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException { + + try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); assert(hyperHost instanceof HostMO); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); - if (summary == null) { - throw new Exception("No ESX(i) host found"); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("Startup report on host network info. " + _gson.toJson(summary)); - } - - cmd.setPrivateIpAddress(summary.getHostIp()); - cmd.setPrivateNetmask(summary.getHostNetmask()); - cmd.setPrivateMacAddress(summary.getHostMacAddress()); - - cmd.setStorageIpAddress(summary.getHostIp()); - cmd.setStorageNetmask(summary.getHostNetmask()); - cmd.setStorageMacAddress(summary.getHostMacAddress()); - - } catch (Throwable e) { - String msg = "querying host network info failed due to " + VmwareHelper.getExceptionMessage(e); - s_logger.error(msg, e); - throw new CloudRuntimeException(msg); - } - } - - private void fillHostDetailsInfo(VmwareContext serviceContext, Map details) throws Exception { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - - ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); + + VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); + if (summary == null) { + throw new Exception("No ESX(i) host found"); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("Startup report on host network info. " + _gson.toJson(summary)); + } + + cmd.setPrivateIpAddress(summary.getHostIp()); + cmd.setPrivateNetmask(summary.getHostNetmask()); + cmd.setPrivateMacAddress(summary.getHostMacAddress()); + + cmd.setStorageIpAddress(summary.getHostIp()); + cmd.setStorageNetmask(summary.getHostNetmask()); + cmd.setStorageMacAddress(summary.getHostMacAddress()); + + } catch (Throwable e) { + String msg = "querying host network info failed due to " + VmwareHelper.getExceptionMessage(e); + s_logger.error(msg, e); + throw new CloudRuntimeException(msg); + } + } + + private void fillHostDetailsInfo(VmwareContext serviceContext, Map details) throws Exception { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + + ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); if (dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { details.put("NativeHA", "true"); - } - } + } + } - protected HashMap sync() { - HashMap changes = new HashMap(); - HashMap oldStates = null; - - try { - synchronized (_vms) { - HashMap newStates = getVmStates(); - oldStates = new HashMap(_vms.size()); - oldStates.putAll(_vms); - - for (final Map.Entry entry : newStates.entrySet()) { - final String vm = entry.getKey(); - - State newState = entry.getValue(); - final State oldState = oldStates.remove(vm); - - if (s_logger.isTraceEnabled()) { - s_logger.trace("VM " + vm + ": vSphere has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); - } - - if (vm.startsWith("migrating")) { - s_logger.debug("Migrating detected. Skipping"); - continue; - } - - if (oldState == null) { - _vms.put(vm, newState); - s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); - changes.put(vm, newState); - } else if (oldState == State.Starting) { - if (newState == State.Running) { - _vms.put(vm, newState); - } else if (newState == State.Stopped) { - s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); - } - } else if (oldState == State.Migrating) { - if (newState == State.Running) { - s_logger.debug("Detected that an migrating VM is now running: " + vm); - _vms.put(vm, newState); - } - } else if (oldState == State.Stopping) { - if (newState == State.Stopped) { - _vms.put(vm, newState); - } else if (newState == State.Running) { - s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); - } - } else if (oldState != newState) { - _vms.put(vm, newState); - if (newState == State.Stopped) { - /* - * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); - * newState = State.Error; } - */ - } - changes.put(vm, newState); - } - } - - for (final Map.Entry entry : oldStates.entrySet()) { - final String vm = entry.getKey(); - final State oldState = entry.getValue(); - - if (isVmInCluster(vm)) { + protected HashMap sync() { + HashMap changes = new HashMap(); + HashMap oldStates = null; + + try { + synchronized (_vms) { + HashMap newStates = getVmStates(); + oldStates = new HashMap(_vms.size()); + oldStates.putAll(_vms); + + for (final Map.Entry entry : newStates.entrySet()) { + final String vm = entry.getKey(); + + State newState = entry.getValue(); + final State oldState = oldStates.remove(vm); + + if (s_logger.isTraceEnabled()) { + s_logger.trace("VM " + vm + ": vSphere has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); + } + + if (vm.startsWith("migrating")) { + s_logger.debug("Migrating detected. Skipping"); + continue; + } + + if (oldState == null) { + _vms.put(vm, newState); + s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); + changes.put(vm, newState); + } else if (oldState == State.Starting) { + if (newState == State.Running) { + _vms.put(vm, newState); + } else if (newState == State.Stopped) { + s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); + } + } else if (oldState == State.Migrating) { + if (newState == State.Running) { + s_logger.debug("Detected that an migrating VM is now running: " + vm); + _vms.put(vm, newState); + } + } else if (oldState == State.Stopping) { + if (newState == State.Stopped) { + _vms.put(vm, newState); + } else if (newState == State.Running) { + s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); + } + } else if (oldState != newState) { + _vms.put(vm, newState); + if (newState == State.Stopped) { + /* + * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); + * newState = State.Error; } + */ + } + changes.put(vm, newState); + } + } + + for (final Map.Entry entry : oldStates.entrySet()) { + final String vm = entry.getKey(); + final State oldState = entry.getValue(); + + if (isVmInCluster(vm)) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report but we detected that it might be migrated to other host by vCenter"); } @@ -3481,136 +3481,136 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } else { s_logger.debug("VM " + vm + " is missing from host report, but we will ignore VM " + vm + " in transition state " + oldState); } - continue; - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("VM " + vm + " is now missing from host report"); - } - - if (oldState == State.Stopping) { - s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); - _vms.remove(vm); - } else if (oldState == State.Starting) { - s_logger.debug("Ignoring VM " + vm + " in transition state starting."); - } else if (oldState == State.Stopped) { - _vms.remove(vm); - } else if (oldState == State.Migrating) { - s_logger.debug("Ignoring VM " + vm + " in migrating state."); - } else { - State state = State.Stopped; - changes.put(entry.getKey(), state); - } - } - } - } catch (Throwable e) { - if (e instanceof RemoteException) { - s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); - invalidateServiceContext(); - } - - s_logger.error("Unable to perform sync information collection process at this point due to " + VmwareHelper.getExceptionMessage(e), e); - return null; - } - return changes; - } - - private boolean isVmInCluster(String vmName) throws Exception { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - - return hyperHost.findVmOnPeerHyperHost(vmName) != null; - } - + continue; + } + + if (s_logger.isDebugEnabled()) { + s_logger.debug("VM " + vm + " is now missing from host report"); + } + + if (oldState == State.Stopping) { + s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); + _vms.remove(vm); + } else if (oldState == State.Starting) { + s_logger.debug("Ignoring VM " + vm + " in transition state starting."); + } else if (oldState == State.Stopped) { + _vms.remove(vm); + } else if (oldState == State.Migrating) { + s_logger.debug("Ignoring VM " + vm + " in migrating state."); + } else { + State state = State.Stopped; + changes.put(entry.getKey(), state); + } + } + } + } catch (Throwable e) { + if (e instanceof RemoteException) { + s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); + invalidateServiceContext(); + } + + s_logger.error("Unable to perform sync information collection process at this point due to " + VmwareHelper.getExceptionMessage(e), e); + return null; + } + return changes; + } + + private boolean isVmInCluster(String vmName) throws Exception { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + + return hyperHost.findVmOnPeerHyperHost(vmName) != null; + } + protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { - - VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); - - VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - if(!mgr.beginExclusiveOperation(600)) - throw new Exception("Unable to begin exclusive operation, lock time out"); - - try { - int maxVncPorts = 64; - int vncPort = 0; - Random random = new Random(); - - HostMO vmOwnerHost = vmMo.getRunningHost(); - - ManagedObjectReference morParent = vmOwnerHost.getParentMor(); - HashMap portInfo; - if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { - ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); - portInfo = clusterMo.getVmVncPortsOnCluster(); - } else { - portInfo = vmOwnerHost.getVmVncPortsOnHost(); - } - - // allocate first at 5900 - 5964 range - Collection existingPorts = portInfo.values(); - int val = random.nextInt(maxVncPorts); - int startVal = val; - do { - if (!existingPorts.contains(5900 + val)) { - vncPort = 5900 + val; - break; - } - - val = (++val) % maxVncPorts; - } while (val != startVal); - - if(vncPort == 0) { - s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); + + VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); - Pair additionalRange = mgr.getAddiionalVncPortRange(); - maxVncPorts = additionalRange.second(); - val = random.nextInt(maxVncPorts); - startVal = val; - do { - if (!existingPorts.contains(additionalRange.first() + val)) { - vncPort = additionalRange.first() + val; - break; - } - - val = (++val) % maxVncPorts; - } while (val != startVal); - } - - if (vncPort == 0) { - throw new Exception("Unable to find an available VNC port on host"); - } - - if (s_logger.isInfoEnabled()) { - s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); - } - - return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); - } finally { - try { - mgr.endExclusiveOperation(); - } catch(Throwable e) { - assert(false); - s_logger.error("Unexpected exception ", e); - } - } - } - - private VirtualMachineGuestOsIdentifier translateGuestOsIdentifier(String cpuArchitecture, String cloudGuestOs) { - if (cpuArchitecture == null) { - s_logger.warn("CPU arch is not set, default to i386. guest os: " + cloudGuestOs); - cpuArchitecture = "i386"; - } - - VirtualMachineGuestOsIdentifier identifier = VmwareGuestOsMapper.getGuestOsIdentifier(cloudGuestOs); - if (identifier != null) { - return identifier; - } - - if (cpuArchitecture.equalsIgnoreCase("x86_64")) { - return VirtualMachineGuestOsIdentifier.otherGuest64; - } - return VirtualMachineGuestOsIdentifier.otherGuest; - } + VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + if(!mgr.beginExclusiveOperation(600)) + throw new Exception("Unable to begin exclusive operation, lock time out"); + + try { + int maxVncPorts = 64; + int vncPort = 0; + Random random = new Random(); + + HostMO vmOwnerHost = vmMo.getRunningHost(); + + ManagedObjectReference morParent = vmOwnerHost.getParentMor(); + HashMap portInfo; + if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { + ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); + portInfo = clusterMo.getVmVncPortsOnCluster(); + } else { + portInfo = vmOwnerHost.getVmVncPortsOnHost(); + } + + // allocate first at 5900 - 5964 range + Collection existingPorts = portInfo.values(); + int val = random.nextInt(maxVncPorts); + int startVal = val; + do { + if (!existingPorts.contains(5900 + val)) { + vncPort = 5900 + val; + break; + } + + val = (++val) % maxVncPorts; + } while (val != startVal); + + if(vncPort == 0) { + s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); + + Pair additionalRange = mgr.getAddiionalVncPortRange(); + maxVncPorts = additionalRange.second(); + val = random.nextInt(maxVncPorts); + startVal = val; + do { + if (!existingPorts.contains(additionalRange.first() + val)) { + vncPort = additionalRange.first() + val; + break; + } + + val = (++val) % maxVncPorts; + } while (val != startVal); + } + + if (vncPort == 0) { + throw new Exception("Unable to find an available VNC port on host"); + } + + if (s_logger.isInfoEnabled()) { + s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); + } + + return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); + } finally { + try { + mgr.endExclusiveOperation(); + } catch(Throwable e) { + assert(false); + s_logger.error("Unexpected exception ", e); + } + } + } + + private VirtualMachineGuestOsIdentifier translateGuestOsIdentifier(String cpuArchitecture, String cloudGuestOs) { + if (cpuArchitecture == null) { + s_logger.warn("CPU arch is not set, default to i386. guest os: " + cloudGuestOs); + cpuArchitecture = "i386"; + } + + VirtualMachineGuestOsIdentifier identifier = VmwareGuestOsMapper.getGuestOsIdentifier(cloudGuestOs); + if (identifier != null) { + return identifier; + } + + if (cpuArchitecture.equalsIgnoreCase("x86_64")) { + return VirtualMachineGuestOsIdentifier.otherGuest64; + } + return VirtualMachineGuestOsIdentifier.otherGuest; + } private void prepareNetworkForVmTargetHost(HostMO hostMo, VirtualMachineMO vmMo) throws Exception { assert (vmMo != null); @@ -3679,41 +3679,41 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } } - private HashMap getVmStates() throws Exception { - VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); - ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); - - HashMap newStates = new HashMap(); - if (ocs != null && ocs.length > 0) { - for (ObjectContent oc : ocs) { - DynamicProperty[] objProps = oc.getPropSet(); - if (objProps != null) { - - boolean isTemplate = false; - String name = null; - VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; - for (DynamicProperty objProp : objProps) { - if (objProp.getName().equals("config.template")) { - if (objProp.getVal().toString().equalsIgnoreCase("true")) { - isTemplate = true; - } - } else if (objProp.getName().equals("name")) { - name = (String) objProp.getVal(); - } else if (objProp.getName().equals("runtime.powerState")) { - powerState = (VirtualMachinePowerState) objProp.getVal(); - } else { - assert (false); - } - } - - if (!isTemplate) { - newStates.put(name, convertState(powerState)); - } - } - } - } - return newStates; - } + private HashMap getVmStates() throws Exception { + VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); + ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); + + HashMap newStates = new HashMap(); + if (ocs != null && ocs.length > 0) { + for (ObjectContent oc : ocs) { + DynamicProperty[] objProps = oc.getPropSet(); + if (objProps != null) { + + boolean isTemplate = false; + String name = null; + VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; + for (DynamicProperty objProp : objProps) { + if (objProp.getName().equals("config.template")) { + if (objProp.getVal().toString().equalsIgnoreCase("true")) { + isTemplate = true; + } + } else if (objProp.getName().equals("name")) { + name = (String) objProp.getVal(); + } else if (objProp.getName().equals("runtime.powerState")) { + powerState = (VirtualMachinePowerState) objProp.getVal(); + } else { + assert (false); + } + } + + if (!isTemplate) { + newStates.put(name, convertState(powerState)); + } + } + } + } + return newStates; + } private HashMap getVmStats(List vmNames) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); @@ -3809,200 +3809,200 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa } return vmResponseMap; } - - protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { - String args = null; - if (option.equals("get")) { - args = "-g"; - } else if (option.equals("create")) { - args = "-c"; - } else if (option.equals("reset")) { - args = "-r"; - } else if (option.equals("addVif")) { - args = "-a"; - args += ethName; - } else if (option.equals("deleteVif")) { - args = "-d"; - args += ethName; - } - - try { + + protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { + String args = null; + if (option.equals("get")) { + args = "-g"; + } else if (option.equals("create")) { + args = "-c"; + } else if (option.equals("reset")) { + args = "-r"; + } else if (option.equals("addVif")) { + args = "-a"; + args += ethName; + } else if (option.equals("deleteVif")) { + args = "-d"; + args += ethName; + } + + try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /root/netusage.sh " + args + " on DomR " + privateIpAddress); - } - - VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - - Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/netusage.sh " + args); - - if (!result.first()) { - return null; - } - - return result.second(); - } catch (Throwable e) { + } + + VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + + Pair result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/netusage.sh " + args); + + if (!result.first()) { + return null; + } + + return result.second(); + } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " - + VmwareHelper.getExceptionMessage(e), e); - } - - return null; - } - - private long[] getNetworkStats(String privateIP) { - String result = networkUsage(privateIP, "get", null); - long[] stats = new long[2]; - if (result != null) { - try { - String[] splitResult = result.split(":"); - int i = 0; - while (i < splitResult.length - 1) { - stats[0] += (new Long(splitResult[i++])).longValue(); - stats[1] += (new Long(splitResult[i++])).longValue(); - } - } catch (Throwable e) { - s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); - } - } - return stats; - } - - protected String connect(final String vmName, final String ipAddress, final int port) { - long startTick = System.currentTimeMillis(); - - // wait until we have at least been waiting for _ops_timeout time or - // at least have tried _retry times, this is to coordinate with system - // VM patching/rebooting time that may need - int retry = _retry; - while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { - SocketChannel sch = null; - try { - s_logger.info("Trying to connect to " + ipAddress); - sch = SocketChannel.open(); - sch.configureBlocking(true); - sch.socket().setSoTimeout(5000); - - InetSocketAddress addr = new InetSocketAddress(ipAddress, port); - sch.connect(addr); - return null; - } catch (IOException e) { - s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); - if (e instanceof ConnectException) { - // if connection is refused because of VM is being started, - // we give it more sleep time - // to avoid running out of retry quota too quickly - try { - Thread.sleep(5000); - } catch (InterruptedException ex) { - } - } - } finally { - if (sch != null) { - try { - sch.close(); - } catch (IOException e) { - } - } - } - - try { - Thread.sleep(1000); - } catch (InterruptedException ex) { - } - } - - s_logger.info("Unable to logon to " + ipAddress); - - return "Unable to connect"; - } - - protected String connect(final String vmname, final String ipAddress) { - return connect(vmname, ipAddress, 3922); - } - - private static State convertState(VirtualMachinePowerState powerState) { - return s_statesTable.get(powerState); - } - - private static State getVmState(VirtualMachineMO vmMo) throws Exception { - VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); - return convertState(runtimeInfo.getPowerState()); - } - - private static HostStatsEntry getHyperHostStats(VmwareHypervisorHost hyperHost) throws Exception { + + VmwareHelper.getExceptionMessage(e), e); + } + + return null; + } + + private long[] getNetworkStats(String privateIP) { + String result = networkUsage(privateIP, "get", null); + long[] stats = new long[2]; + if (result != null) { + try { + String[] splitResult = result.split(":"); + int i = 0; + while (i < splitResult.length - 1) { + stats[0] += (new Long(splitResult[i++])).longValue(); + stats[1] += (new Long(splitResult[i++])).longValue(); + } + } catch (Throwable e) { + s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); + } + } + return stats; + } + + protected String connect(final String vmName, final String ipAddress, final int port) { + long startTick = System.currentTimeMillis(); + + // wait until we have at least been waiting for _ops_timeout time or + // at least have tried _retry times, this is to coordinate with system + // VM patching/rebooting time that may need + int retry = _retry; + while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { + SocketChannel sch = null; + try { + s_logger.info("Trying to connect to " + ipAddress); + sch = SocketChannel.open(); + sch.configureBlocking(true); + sch.socket().setSoTimeout(5000); + + InetSocketAddress addr = new InetSocketAddress(ipAddress, port); + sch.connect(addr); + return null; + } catch (IOException e) { + s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); + if (e instanceof ConnectException) { + // if connection is refused because of VM is being started, + // we give it more sleep time + // to avoid running out of retry quota too quickly + try { + Thread.sleep(5000); + } catch (InterruptedException ex) { + } + } + } finally { + if (sch != null) { + try { + sch.close(); + } catch (IOException e) { + } + } + } + + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + } + } + + s_logger.info("Unable to logon to " + ipAddress); + + return "Unable to connect"; + } + + protected String connect(final String vmname, final String ipAddress) { + return connect(vmname, ipAddress, 3922); + } + + private static State convertState(VirtualMachinePowerState powerState) { + return s_statesTable.get(powerState); + } + + private static State getVmState(VirtualMachineMO vmMo) throws Exception { + VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); + return convertState(runtimeInfo.getPowerState()); + } + + private static HostStatsEntry getHyperHostStats(VmwareHypervisorHost hyperHost) throws Exception { ComputeResourceSummary hardwareSummary = hyperHost.getHyperHostHardwareSummary(); if(hardwareSummary == null) return null; - - HostStatsEntry entry = new HostStatsEntry(); - - entry.setEntityType("host"); - double cpuUtilization = ((double) (hardwareSummary.getTotalCpu() - hardwareSummary.getEffectiveCpu()) / (double) hardwareSummary.getTotalCpu() * 100); - entry.setCpuUtilization(cpuUtilization); - entry.setTotalMemoryKBs(hardwareSummary.getTotalMemory() / 1024); - entry.setFreeMemoryKBs(hardwareSummary.getEffectiveMemory() * 1024); - - return entry; - } - - private static String getRouterSshControlIp(NetworkElementCommand cmd) { - String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); - String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); - String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); - - if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { - if(s_logger.isDebugEnabled()) - s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); - - return routerGuestIp; - } - - if(s_logger.isDebugEnabled()) - s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); - return routerIp; - } - - @Override - public void setAgentControl(IAgentControl agentControl) { - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - - _url = (String) params.get("url"); - _username = (String) params.get("username"); - _password = (String) params.get("password"); - _dcId = (String) params.get("zone"); - _pod = (String) params.get("pod"); + + HostStatsEntry entry = new HostStatsEntry(); + + entry.setEntityType("host"); + double cpuUtilization = ((double) (hardwareSummary.getTotalCpu() - hardwareSummary.getEffectiveCpu()) / (double) hardwareSummary.getTotalCpu() * 100); + entry.setCpuUtilization(cpuUtilization); + entry.setTotalMemoryKBs(hardwareSummary.getTotalMemory() / 1024); + entry.setFreeMemoryKBs(hardwareSummary.getEffectiveMemory() * 1024); + + return entry; + } + + private static String getRouterSshControlIp(NetworkElementCommand cmd) { + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); + String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); + + if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { + if(s_logger.isDebugEnabled()) + s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); + + return routerGuestIp; + } + + if(s_logger.isDebugEnabled()) + s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); + return routerIp; + } + + @Override + public void setAgentControl(IAgentControl agentControl) { + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + + _url = (String) params.get("url"); + _username = (String) params.get("username"); + _password = (String) params.get("password"); + _dcId = (String) params.get("zone"); + _pod = (String) params.get("pod"); _cluster = (String) params.get("cluster"); - + _guid = (String) params.get("guid"); - String[] tokens = _guid.split("@"); - _vCenterAddress = tokens[1]; - _morHyperHost = new ManagedObjectReference(); - String[] hostTokens = tokens[0].split(":"); - _morHyperHost.setType(hostTokens[0]); + String[] tokens = _guid.split("@"); + _vCenterAddress = tokens[1]; + _morHyperHost = new ManagedObjectReference(); + String[] hostTokens = tokens[0].split(":"); + _morHyperHost.setType(hostTokens[0]); _morHyperHost.set_value(hostTokens[1]); - VmwareContext context = getServiceContext(); - try { - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); - mgr.setupResourceStartupParams(params); - - CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); - cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); - cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); + VmwareContext context = getServiceContext(); + try { + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + mgr.setupResourceStartupParams(params); + + CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); + cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); + cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_UUID); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_NIC_MASK); - - VmwareHypervisorHost hostMo = this.getHyperHost(context); - _hostName = hostMo.getHyperHostName(); - } catch (Exception e) { - s_logger.error("Unexpected Exception ", e); - } - - _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); - _publicNetworkVSwitchName = (String) params.get("public.network.vswitch.name"); + + VmwareHypervisorHost hostMo = this.getHyperHost(context); + _hostName = hostMo.getHyperHostName(); + } catch (Exception e) { + s_logger.error("Unexpected Exception ", e); + } + + _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); + _publicNetworkVSwitchName = (String) params.get("public.network.vswitch.name"); _guestNetworkVSwitchName = (String) params.get("guest.network.vswitch.name"); String value = (String) params.get("cpu.overprovisioning.factor"); @@ -4031,43 +4031,43 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa else _rootDiskController = DiskControllerType.ide; - s_logger.info("VmwareResource network configuration info. private vSwitch: " + _privateNetworkVSwitchName + ", public vSwitch: " + _publicNetworkVSwitchName + ", guest network: " - + _guestNetworkVSwitchName); - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - private VmwareContext getServiceContext() { - return getServiceContext(null); - } - - private void invalidateServiceContext() { - invalidateServiceContext(null); - } - - private VmwareHypervisorHost getHyperHost(VmwareContext context) { - return getHyperHost(context, null); - } - - @Override - public synchronized VmwareContext getServiceContext(Command cmd) { - if (_serviceContext == null) { - try { + s_logger.info("VmwareResource network configuration info. private vSwitch: " + _privateNetworkVSwitchName + ", public vSwitch: " + _publicNetworkVSwitchName + ", guest network: " + + _guestNetworkVSwitchName); + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + private VmwareContext getServiceContext() { + return getServiceContext(null); + } + + private void invalidateServiceContext() { + invalidateServiceContext(null); + } + + private VmwareHypervisorHost getHyperHost(VmwareContext context) { + return getHyperHost(context, null); + } + + @Override + public synchronized VmwareContext getServiceContext(Command cmd) { + if (_serviceContext == null) { + try { _serviceContext = VmwareContextFactory.create(_vCenterAddress, _username, _password); VmwareHypervisorHost hyperHost = getHyperHost(_serviceContext, cmd); assert(hyperHost instanceof HostMO); @@ -4091,35 +4091,35 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa if(bRefresh) firewallMo.refreshFirewall(); } - } catch (Exception e) { - s_logger.error("Unable to connect to vSphere server: " + _vCenterAddress, e); - throw new CloudRuntimeException("Unable to connect to vSphere server: " + _vCenterAddress); - } - } - - return _serviceContext; - } - - @Override - public synchronized void invalidateServiceContext(VmwareContext context) { - if (_serviceContext == null) { - _serviceContext.close(); - } - _serviceContext = null; - } - - @Override - public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) { + } catch (Exception e) { + s_logger.error("Unable to connect to vSphere server: " + _vCenterAddress, e); + throw new CloudRuntimeException("Unable to connect to vSphere server: " + _vCenterAddress); + } + } + + return _serviceContext; + } + + @Override + public synchronized void invalidateServiceContext(VmwareContext context) { + if (_serviceContext == null) { + _serviceContext.close(); + } + _serviceContext = null; + } + + @Override + public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) { if (_morHyperHost.getType().equalsIgnoreCase("HostSystem")) { return new HostMO(context, _morHyperHost); - } - return new ClusterMO(context, _morHyperHost); - } - + } + return new ClusterMO(context, _morHyperHost); + } + @Override - @DB - public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) { - VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); + @DB + public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) { + VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String vmName = mgr.composeWorkerName(); assert(cmd != null); @@ -4127,5 +4127,5 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa long checkPointId = vmwareMgr.pushCleanupCheckpoint(this._guid, vmName); cmd.setContextParam("checkpoint", String.valueOf(checkPointId)); return vmName; - } -} + } +} diff --git a/core/src/com/cloud/info/ConsoleProxyConnectionInfo.java b/core/src/com/cloud/info/ConsoleProxyConnectionInfo.java index 85ec22ab647..ae2c5519cf9 100644 --- a/core/src/com/cloud/info/ConsoleProxyConnectionInfo.java +++ b/core/src/com/cloud/info/ConsoleProxyConnectionInfo.java @@ -10,16 +10,16 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class ConsoleProxyConnectionInfo { - public int id; - public String host; - public int port; - public String tag; - public long createTime; - public long lastUsedTime; - - public ConsoleProxyConnectionInfo() { - } -} +package com.cloud.info; + +public class ConsoleProxyConnectionInfo { + public int id; + public String host; + public int port; + public String tag; + public long createTime; + public long lastUsedTime; + + public ConsoleProxyConnectionInfo() { + } +} diff --git a/core/src/com/cloud/info/ConsoleProxyInfo.java b/core/src/com/cloud/info/ConsoleProxyInfo.java index 12ab0a909f8..52155b7c5ae 100644 --- a/core/src/com/cloud/info/ConsoleProxyInfo.java +++ b/core/src/com/cloud/info/ConsoleProxyInfo.java @@ -10,83 +10,83 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class ConsoleProxyInfo { - - private boolean sslEnabled; - private String proxyAddress; - private int proxyPort; - private String proxyImageUrl; - private int proxyUrlPort = 8000; - - public ConsoleProxyInfo(int proxyUrlPort) { - this.proxyUrlPort = proxyUrlPort; - } - - public ConsoleProxyInfo(boolean sslEnabled, String proxyIpAddress, int port, int proxyUrlPort, String consoleProxyUrlDomain) { - this.sslEnabled = sslEnabled; - - if(sslEnabled) { - StringBuffer sb = new StringBuffer(proxyIpAddress); - for(int i = 0; i < sb.length(); i++) - if(sb.charAt(i) == '.') +package com.cloud.info; + +public class ConsoleProxyInfo { + + private boolean sslEnabled; + private String proxyAddress; + private int proxyPort; + private String proxyImageUrl; + private int proxyUrlPort = 8000; + + public ConsoleProxyInfo(int proxyUrlPort) { + this.proxyUrlPort = proxyUrlPort; + } + + public ConsoleProxyInfo(boolean sslEnabled, String proxyIpAddress, int port, int proxyUrlPort, String consoleProxyUrlDomain) { + this.sslEnabled = sslEnabled; + + if(sslEnabled) { + StringBuffer sb = new StringBuffer(proxyIpAddress); + for(int i = 0; i < sb.length(); i++) + if(sb.charAt(i) == '.') sb.setCharAt(i, '-'); if(consoleProxyUrlDomain!=null && consoleProxyUrlDomain.length()>0) { sb.append("."); sb.append(consoleProxyUrlDomain); } - else + else sb.append(".realhostip.com"); - - proxyAddress = sb.toString(); - proxyPort = port; - this.proxyUrlPort = proxyUrlPort; - - proxyImageUrl = "https://" + proxyAddress; - if(proxyUrlPort != 443) - proxyImageUrl += ":" + this.proxyUrlPort; - } else { - proxyAddress = proxyIpAddress; - proxyPort = port; - this.proxyUrlPort = proxyUrlPort; - - proxyImageUrl = "http://" + proxyAddress; - if(proxyUrlPort != 80) - proxyImageUrl += ":" + proxyUrlPort; - } - } - - public String getProxyAddress() { - return proxyAddress; - } - - public void setProxyAddress(String proxyAddress) { - this.proxyAddress = proxyAddress; - } - - public int getProxyPort() { - return proxyPort; - } - - public void setProxyPort(int proxyPort) { - this.proxyPort = proxyPort; - } - - public String getProxyImageUrl() { - return proxyImageUrl; - } - - public void setProxyImageUrl(String proxyImageUrl) { - this.proxyImageUrl = proxyImageUrl; - } - - public boolean isSslEnabled() { - return sslEnabled; - } - - public void setSslEnabled(boolean sslEnabled) { - this.sslEnabled = sslEnabled; - } -} + + proxyAddress = sb.toString(); + proxyPort = port; + this.proxyUrlPort = proxyUrlPort; + + proxyImageUrl = "https://" + proxyAddress; + if(proxyUrlPort != 443) + proxyImageUrl += ":" + this.proxyUrlPort; + } else { + proxyAddress = proxyIpAddress; + proxyPort = port; + this.proxyUrlPort = proxyUrlPort; + + proxyImageUrl = "http://" + proxyAddress; + if(proxyUrlPort != 80) + proxyImageUrl += ":" + proxyUrlPort; + } + } + + public String getProxyAddress() { + return proxyAddress; + } + + public void setProxyAddress(String proxyAddress) { + this.proxyAddress = proxyAddress; + } + + public int getProxyPort() { + return proxyPort; + } + + public void setProxyPort(int proxyPort) { + this.proxyPort = proxyPort; + } + + public String getProxyImageUrl() { + return proxyImageUrl; + } + + public void setProxyImageUrl(String proxyImageUrl) { + this.proxyImageUrl = proxyImageUrl; + } + + public boolean isSslEnabled() { + return sslEnabled; + } + + public void setSslEnabled(boolean sslEnabled) { + this.sslEnabled = sslEnabled; + } +} diff --git a/core/src/com/cloud/info/ConsoleProxyLoadInfo.java b/core/src/com/cloud/info/ConsoleProxyLoadInfo.java index 89128b8bd54..c89f33cdafe 100644 --- a/core/src/com/cloud/info/ConsoleProxyLoadInfo.java +++ b/core/src/com/cloud/info/ConsoleProxyLoadInfo.java @@ -10,35 +10,35 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class ConsoleProxyLoadInfo { - - private long id; - private String name; - private int count; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } -} +package com.cloud.info; + +public class ConsoleProxyLoadInfo { + + private long id; + private String name; + private int count; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } +} diff --git a/core/src/com/cloud/info/ConsoleProxyStatus.java b/core/src/com/cloud/info/ConsoleProxyStatus.java index 02cc51879b5..a9a64f0453c 100644 --- a/core/src/com/cloud/info/ConsoleProxyStatus.java +++ b/core/src/com/cloud/info/ConsoleProxyStatus.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class ConsoleProxyStatus { - private ConsoleProxyConnectionInfo[] connections; - - public ConsoleProxyStatus() { - } - - public ConsoleProxyConnectionInfo[] getConnections() { - return connections; - } -} +package com.cloud.info; + +public class ConsoleProxyStatus { + private ConsoleProxyConnectionInfo[] connections; + + public ConsoleProxyStatus() { + } + + public ConsoleProxyConnectionInfo[] getConnections() { + return connections; + } +} diff --git a/core/src/com/cloud/info/RunningHostCountInfo.java b/core/src/com/cloud/info/RunningHostCountInfo.java index 947bcdb79e7..26b6e7e1f03 100644 --- a/core/src/com/cloud/info/RunningHostCountInfo.java +++ b/core/src/com/cloud/info/RunningHostCountInfo.java @@ -10,35 +10,35 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class RunningHostCountInfo { - - private long dcId; - private String hostType; - private int count; - - public long getDcId() { - return dcId; - } - - public void setDcId(long dcId) { - this.dcId = dcId; - } - - public String getHostType() { - return hostType; - } - - public void setHostType(String hostType) { - this.hostType = hostType; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } -} +package com.cloud.info; + +public class RunningHostCountInfo { + + private long dcId; + private String hostType; + private int count; + + public long getDcId() { + return dcId; + } + + public void setDcId(long dcId) { + this.dcId = dcId; + } + + public String getHostType() { + return hostType; + } + + public void setHostType(String hostType) { + this.hostType = hostType; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } +} diff --git a/core/src/com/cloud/info/RunningHostInfoAgregator.java b/core/src/com/cloud/info/RunningHostInfoAgregator.java index 5471a496e51..7da9e2a3097 100644 --- a/core/src/com/cloud/info/RunningHostInfoAgregator.java +++ b/core/src/com/cloud/info/RunningHostInfoAgregator.java @@ -10,72 +10,72 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -import java.util.HashMap; -import java.util.Map; - +package com.cloud.info; + +import java.util.HashMap; +import java.util.Map; + import com.cloud.host.Host; - -public class RunningHostInfoAgregator { - - public static class ZoneHostInfo { - public static int ROUTING_HOST_MASK = 2; - public static int STORAGE_HOST_MASK = 4; - public static int ALL_HOST_MASK = ROUTING_HOST_MASK | STORAGE_HOST_MASK; - - private long dcId; - - // (1 << 1) : at least one routing host is running in the zone - // (1 << 2) : at least one storage host is running in the zone - private int flags = 0; - - public long getDcId() { - return dcId; - } - - public void setDcId(long dcId) { - this.dcId = dcId; - } - - public void setFlag(int flagMask) { - flags |= flagMask; - } - - public int getFlags() { - return flags; - } - } - - private Map zoneHostInfoMap = new HashMap(); - - public RunningHostInfoAgregator() { - } - - public void aggregate(RunningHostCountInfo countInfo) { - if(countInfo.getCount() > 0) { - ZoneHostInfo zoneInfo = getZoneHostInfo(countInfo.getDcId()); - - Host.Type type = Enum.valueOf(Host.Type.class, countInfo.getHostType()); - if(type == Host.Type.Routing) { - zoneInfo.setFlag(ZoneHostInfo.ROUTING_HOST_MASK); - } else if(type == Host.Type.Storage || type == Host.Type.SecondaryStorage) { - zoneInfo.setFlag(ZoneHostInfo.STORAGE_HOST_MASK); - } - } - } - - public Map getZoneHostInfoMap() { - return zoneHostInfoMap; - } - - private ZoneHostInfo getZoneHostInfo(long dcId) { - if(zoneHostInfoMap.containsKey(dcId)) - return zoneHostInfoMap.get(dcId); - - ZoneHostInfo info = new ZoneHostInfo(); - info.setDcId(dcId); - zoneHostInfoMap.put(dcId, info); - return info; - } -} + +public class RunningHostInfoAgregator { + + public static class ZoneHostInfo { + public static int ROUTING_HOST_MASK = 2; + public static int STORAGE_HOST_MASK = 4; + public static int ALL_HOST_MASK = ROUTING_HOST_MASK | STORAGE_HOST_MASK; + + private long dcId; + + // (1 << 1) : at least one routing host is running in the zone + // (1 << 2) : at least one storage host is running in the zone + private int flags = 0; + + public long getDcId() { + return dcId; + } + + public void setDcId(long dcId) { + this.dcId = dcId; + } + + public void setFlag(int flagMask) { + flags |= flagMask; + } + + public int getFlags() { + return flags; + } + } + + private Map zoneHostInfoMap = new HashMap(); + + public RunningHostInfoAgregator() { + } + + public void aggregate(RunningHostCountInfo countInfo) { + if(countInfo.getCount() > 0) { + ZoneHostInfo zoneInfo = getZoneHostInfo(countInfo.getDcId()); + + Host.Type type = Enum.valueOf(Host.Type.class, countInfo.getHostType()); + if(type == Host.Type.Routing) { + zoneInfo.setFlag(ZoneHostInfo.ROUTING_HOST_MASK); + } else if(type == Host.Type.Storage || type == Host.Type.SecondaryStorage) { + zoneInfo.setFlag(ZoneHostInfo.STORAGE_HOST_MASK); + } + } + } + + public Map getZoneHostInfoMap() { + return zoneHostInfoMap; + } + + private ZoneHostInfo getZoneHostInfo(long dcId) { + if(zoneHostInfoMap.containsKey(dcId)) + return zoneHostInfoMap.get(dcId); + + ZoneHostInfo info = new ZoneHostInfo(); + info.setDcId(dcId); + zoneHostInfoMap.put(dcId, info); + return info; + } +} diff --git a/core/src/com/cloud/info/SecStorageVmLoadInfo.java b/core/src/com/cloud/info/SecStorageVmLoadInfo.java index 8a7b778bf0c..95c30576a11 100644 --- a/core/src/com/cloud/info/SecStorageVmLoadInfo.java +++ b/core/src/com/cloud/info/SecStorageVmLoadInfo.java @@ -10,35 +10,35 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.info; - -public class SecStorageVmLoadInfo { - - private long id; - private String name; - private int count; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getCount() { - return count; - } - - public void setCount(int count) { - this.count = count; - } -} +package com.cloud.info; + +public class SecStorageVmLoadInfo { + + private long id; + private String name; + private int count; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } +} diff --git a/core/src/com/cloud/network/VpnUserVO.java b/core/src/com/cloud/network/VpnUserVO.java index 7f1992b5f27..dc996ba0bf6 100644 --- a/core/src/com/cloud/network/VpnUserVO.java +++ b/core/src/com/cloud/network/VpnUserVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.network; - +package com.cloud.network; + import java.util.UUID; import javax.persistence.Column; @@ -24,22 +24,22 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.api.Identity; - -@Entity -@Table(name=("vpn_users")) -public class VpnUserVO implements VpnUser, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="owner_id") - private long accountId; - + +@Entity +@Table(name=("vpn_users")) +public class VpnUserVO implements VpnUser, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="owner_id") + private long accountId; + @Column(name="domain_id") - private long domainId; - - @Column(name="username") + private long domainId; + + @Column(name="username") private String username; @Column(name="password", encryptable=true) @@ -47,34 +47,34 @@ public class VpnUserVO implements VpnUser, Identity { @Column(name="state") @Enumerated(value=EnumType.STRING) - private State state; + private State state; @Column(name="uuid") private String uuid; - + public VpnUserVO() { this.uuid = UUID.randomUUID().toString(); - } - - public VpnUserVO(long accountId, long domainId, String userName, String password) { + } + + public VpnUserVO(long accountId, long domainId, String userName, String password) { this.accountId = accountId; this.domainId = domainId; this.username = userName; this.password = password; this.state = State.Add; this.uuid = UUID.randomUUID().toString(); - } - - @Override - public long getId() { - return id; } - + @Override - public long getAccountId() { - return accountId; - } - + public long getId() { + return id; + } + + @Override + public long getAccountId() { + return accountId; + } + @Override public String getUsername() { return username; @@ -120,5 +120,5 @@ public class VpnUserVO implements VpnUser, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} + } +} diff --git a/core/src/com/cloud/resource/ResourceListener.java b/core/src/com/cloud/resource/ResourceListener.java index a4ab0735696..febfc254439 100755 --- a/core/src/com/cloud/resource/ResourceListener.java +++ b/core/src/com/cloud/resource/ResourceListener.java @@ -10,93 +10,93 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.resource; - -import java.net.URI; -import java.util.List; -import java.util.Map; - -import com.cloud.host.HostVO; - -public interface ResourceListener { - static final Integer EVENT_DISCOVER_BEFORE = 0x1; - static final Integer EVENT_DISCOVER_AFTER = 0x1 << 1; - static final Integer EVENT_DELETE_HOST_BEFORE = 0x1 << 2; - static final Integer EVENT_DELETE_HOST_AFTER = 0x1 << 3; - static final Integer EVENT_CANCEL_MAINTENANCE_BEFORE = 0x1 << 4; - static final Integer EVENT_CANCEL_MAINTENANCE_AFTER = 0x1 << 5; - static final Integer EVENT_PREPARE_MAINTENANCE_BEFORE = 0x1 << 6; - static final Integer EVENT_PREPARE_MAINTENANCE_AFTER = 0x1 << 7; - static final Integer EVENT_ALL = (EVENT_DISCOVER_BEFORE | EVENT_DISCOVER_AFTER | EVENT_DELETE_HOST_BEFORE | EVENT_DELETE_HOST_AFTER - | EVENT_CANCEL_MAINTENANCE_BEFORE | EVENT_CANCEL_MAINTENANCE_AFTER | EVENT_PREPARE_MAINTENANCE_BEFORE | EVENT_PREPARE_MAINTENANCE_AFTER); - - /** - * - * @param dcid - * @param podId - * @param clusterId - * @param uri - * @param username - * @param password - * @param hostTags - * - * Called before Discover.find() - */ - void processDiscoverEventBefore(Long dcid, Long podId, Long clusterId, URI uri, String username, String password, List hostTags); - - /** - * - * @param resources - * - * Called after Discover.find() - */ - void processDiscoverEventAfter(Map> resources); - - /** - * - * @param host - * - * Called before host delete - */ - void processDeleteHostEventBefore(HostVO host); - - /** - * - * @param host - * - * Called after host delete. NOTE param host includes stale data which has been removed from database - */ - void processDeletHostEventAfter(HostVO host); - - /** - * - * @param hostId - * - * Called before AgentManager.cancelMaintenance - */ - void processCancelMaintenaceEventBefore(Long hostId); - - /** - * - * @param hostId - * - * Called after AgentManager.cancelMaintenance - */ - void processCancelMaintenaceEventAfter(Long hostId); - - /** - * - * @param hostId - * - * Called before AgentManager.main - */ - void processPrepareMaintenaceEventBefore(Long hostId); - - /** - * - * @param hostId - * - * Called after AgentManager.main - */ - void processPrepareMaintenaceEventAfter(Long hostId); -} +package com.cloud.resource; + +import java.net.URI; +import java.util.List; +import java.util.Map; + +import com.cloud.host.HostVO; + +public interface ResourceListener { + static final Integer EVENT_DISCOVER_BEFORE = 0x1; + static final Integer EVENT_DISCOVER_AFTER = 0x1 << 1; + static final Integer EVENT_DELETE_HOST_BEFORE = 0x1 << 2; + static final Integer EVENT_DELETE_HOST_AFTER = 0x1 << 3; + static final Integer EVENT_CANCEL_MAINTENANCE_BEFORE = 0x1 << 4; + static final Integer EVENT_CANCEL_MAINTENANCE_AFTER = 0x1 << 5; + static final Integer EVENT_PREPARE_MAINTENANCE_BEFORE = 0x1 << 6; + static final Integer EVENT_PREPARE_MAINTENANCE_AFTER = 0x1 << 7; + static final Integer EVENT_ALL = (EVENT_DISCOVER_BEFORE | EVENT_DISCOVER_AFTER | EVENT_DELETE_HOST_BEFORE | EVENT_DELETE_HOST_AFTER + | EVENT_CANCEL_MAINTENANCE_BEFORE | EVENT_CANCEL_MAINTENANCE_AFTER | EVENT_PREPARE_MAINTENANCE_BEFORE | EVENT_PREPARE_MAINTENANCE_AFTER); + + /** + * + * @param dcid + * @param podId + * @param clusterId + * @param uri + * @param username + * @param password + * @param hostTags + * + * Called before Discover.find() + */ + void processDiscoverEventBefore(Long dcid, Long podId, Long clusterId, URI uri, String username, String password, List hostTags); + + /** + * + * @param resources + * + * Called after Discover.find() + */ + void processDiscoverEventAfter(Map> resources); + + /** + * + * @param host + * + * Called before host delete + */ + void processDeleteHostEventBefore(HostVO host); + + /** + * + * @param host + * + * Called after host delete. NOTE param host includes stale data which has been removed from database + */ + void processDeletHostEventAfter(HostVO host); + + /** + * + * @param hostId + * + * Called before AgentManager.cancelMaintenance + */ + void processCancelMaintenaceEventBefore(Long hostId); + + /** + * + * @param hostId + * + * Called after AgentManager.cancelMaintenance + */ + void processCancelMaintenaceEventAfter(Long hostId); + + /** + * + * @param hostId + * + * Called before AgentManager.main + */ + void processPrepareMaintenaceEventBefore(Long hostId); + + /** + * + * @param hostId + * + * Called after AgentManager.main + */ + void processPrepareMaintenaceEventAfter(Long hostId); +} diff --git a/core/src/com/cloud/resource/UnableDeleteHostException.java b/core/src/com/cloud/resource/UnableDeleteHostException.java index 67746316a83..0641cf2b5de 100755 --- a/core/src/com/cloud/resource/UnableDeleteHostException.java +++ b/core/src/com/cloud/resource/UnableDeleteHostException.java @@ -10,15 +10,15 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.resource; - -import com.cloud.utils.SerialVersionUID; -import com.cloud.exception.CloudException; - -public class UnableDeleteHostException extends CloudException { - private static final long serialVersionUID = SerialVersionUID.UnableDeleteHostException; - - public UnableDeleteHostException(String msg) { - super(msg); - } -} +package com.cloud.resource; + +import com.cloud.utils.SerialVersionUID; +import com.cloud.exception.CloudException; + +public class UnableDeleteHostException extends CloudException { + private static final long serialVersionUID = SerialVersionUID.UnableDeleteHostException; + + public UnableDeleteHostException(String msg) { + super(msg); + } +} diff --git a/core/src/com/cloud/serializer/GsonHelper.java b/core/src/com/cloud/serializer/GsonHelper.java index fcebaeee76b..d3954586ce2 100644 --- a/core/src/com/cloud/serializer/GsonHelper.java +++ b/core/src/com/cloud/serializer/GsonHelper.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.serializer; - +package com.cloud.serializer; + import java.util.List; @@ -29,10 +29,10 @@ import com.cloud.utils.Pair; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; - + public class GsonHelper { private static final Logger s_logger = Logger.getLogger(GsonHelper.class); - + protected static final Gson s_gson; protected static final Gson s_gogger; @@ -73,4 +73,4 @@ public class GsonHelper { public final static Logger getLogger() { return s_logger; } -} +} diff --git a/core/src/com/cloud/serializer/SerializerHelper.java b/core/src/com/cloud/serializer/SerializerHelper.java index 127d31b4e25..8c6d9023874 100644 --- a/core/src/com/cloud/serializer/SerializerHelper.java +++ b/core/src/com/cloud/serializer/SerializerHelper.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.serializer; - +package com.cloud.serializer; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -25,13 +25,13 @@ import org.apache.log4j.Logger; import com.cloud.utils.DateUtil; import com.cloud.utils.Pair; import com.google.gson.Gson; - -/** - * Note: toPairList and appendPairList only support simple POJO objects currently - */ -public class SerializerHelper { + +/** + * Note: toPairList and appendPairList only support simple POJO objects currently + */ +public class SerializerHelper { public static final Logger s_logger = Logger.getLogger(SerializerHelper.class.getName()); - public static String token = "/"; + public static String token = "/"; public static String toSerializedStringOld(Object result) { if(result != null) { @@ -79,106 +79,106 @@ public class SerializerHelper { throw e; } } - - public static List> toPairList(Object o, String name) { - List> l = new ArrayList>(); - return appendPairList(l, o, name); - } - - public static List> appendPairList(List> l, Object o, String name) { - if(o != null) { - Class clz = o.getClass(); - - if(clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { - l.add(new Pair(name, o.toString())); - return l; - } - - for(Field f : clz.getDeclaredFields()) { + + public static List> toPairList(Object o, String name) { + List> l = new ArrayList>(); + return appendPairList(l, o, name); + } + + public static List> appendPairList(List> l, Object o, String name) { + if(o != null) { + Class clz = o.getClass(); + + if(clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { + l.add(new Pair(name, o.toString())); + return l; + } + + for(Field f : clz.getDeclaredFields()) { if((f.getModifiers() & Modifier.STATIC) != 0) { continue; - } - - Param param = f.getAnnotation(Param.class); + } + + Param param = f.getAnnotation(Param.class); if(param == null) { continue; - } - - String propName = f.getName(); + } + + String propName = f.getName(); if(!param.propName().isEmpty()) { propName = param.propName(); - } - - String paramName = param.name(); + } + + String paramName = param.name(); if(paramName.isEmpty()) { paramName = propName; - } - - Method method = getGetMethod(o, propName); - if(method != null) { - try { - Object fieldValue = method.invoke(o); + } + + Method method = getGetMethod(o, propName); + if(method != null) { + try { + Object fieldValue = method.invoke(o); if(fieldValue != null) { if (f.getType() == Date.class) { l.add(new Pair(paramName, DateUtil.getOutputString((Date)fieldValue))); } else { l.add(new Pair(paramName, fieldValue.toString())); } - } - //else - // l.add(new Pair(paramName, "")); - } catch (IllegalArgumentException e) { - s_logger.error("Illegal argument exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); - - } catch (IllegalAccessException e) { - s_logger.error("Illegal access exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); - } catch (InvocationTargetException e) { - s_logger.error("Invocation target exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); - } - } - } - } - return l; - } - - private static Method getGetMethod(Object o, String propName) { - Method method = null; - String methodName = getGetMethodName("get", propName); - try { - method = o.getClass().getMethod(methodName); - } catch (SecurityException e1) { - s_logger.error("Security exception in getting POJO " + o.getClass().getName() + " get method for property: " + propName); - } catch (NoSuchMethodException e1) { + } + //else + // l.add(new Pair(paramName, "")); + } catch (IllegalArgumentException e) { + s_logger.error("Illegal argument exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); + + } catch (IllegalAccessException e) { + s_logger.error("Illegal access exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); + } catch (InvocationTargetException e) { + s_logger.error("Invocation target exception when calling POJO " + o.getClass().getName() + " get method for property: " + propName); + } + } + } + } + return l; + } + + private static Method getGetMethod(Object o, String propName) { + Method method = null; + String methodName = getGetMethodName("get", propName); + try { + method = o.getClass().getMethod(methodName); + } catch (SecurityException e1) { + s_logger.error("Security exception in getting POJO " + o.getClass().getName() + " get method for property: " + propName); + } catch (NoSuchMethodException e1) { if(s_logger.isTraceEnabled()) { s_logger.trace("POJO " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName + ", will check is-prefixed method to see if it is boolean property"); - } - } - + } + } + if(method != null) { return method; - } - - methodName = getGetMethodName("is", propName); - try { - method = o.getClass().getMethod(methodName); - } catch (SecurityException e1) { - s_logger.error("Security exception in getting POJO " + o.getClass().getName() + " get method for property: " + propName); - } catch (NoSuchMethodException e1) { - s_logger.warn("POJO " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName); - } - return method; - } - - private static String getGetMethodName(String prefix, String fieldName) { - StringBuffer sb = new StringBuffer(prefix); - - if(fieldName.length() >= prefix.length() && fieldName.substring(0, prefix.length()).equals(prefix)) { - return fieldName; - } else { - sb.append(fieldName.substring(0, 1).toUpperCase()); - sb.append(fieldName.substring(1)); - } - - return sb.toString(); - } -} + } + + methodName = getGetMethodName("is", propName); + try { + method = o.getClass().getMethod(methodName); + } catch (SecurityException e1) { + s_logger.error("Security exception in getting POJO " + o.getClass().getName() + " get method for property: " + propName); + } catch (NoSuchMethodException e1) { + s_logger.warn("POJO " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName); + } + return method; + } + + private static String getGetMethodName(String prefix, String fieldName) { + StringBuffer sb = new StringBuffer(prefix); + + if(fieldName.length() >= prefix.length() && fieldName.substring(0, prefix.length()).equals(prefix)) { + return fieldName; + } else { + sb.append(fieldName.substring(0, 1).toUpperCase()); + sb.append(fieldName.substring(1)); + } + + return sb.toString(); + } +} diff --git a/core/src/com/cloud/storage/DiskOfferingVO.java b/core/src/com/cloud/storage/DiskOfferingVO.java index ef4fa9517e0..a58f363a18f 100755 --- a/core/src/com/cloud/storage/DiskOfferingVO.java +++ b/core/src/com/cloud/storage/DiskOfferingVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import java.util.List; import java.util.UUID; @@ -33,8 +33,8 @@ import javax.persistence.Transient; import com.cloud.api.Identity; import com.cloud.offering.DiskOffering; import com.cloud.utils.db.GenericDao; - -@Entity + +@Entity @Table(name="disk_offering") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) @@ -44,26 +44,26 @@ public class DiskOfferingVO implements DiskOffering, Identity { Service }; - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - long id; - - @Column(name="domain_id") - Long domainId; + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @Column(name="domain_id") + Long domainId; @Column(name="unique_name") private String uniqueName; - - @Column(name="name") - private String name = null; - - @Column(name="display_text", length=4096) - private String displayText = null; - - @Column(name="disk_size") - long diskSize; - + + @Column(name="name") + private String name = null; + + @Column(name="display_text", length=4096) + private String displayText = null; + + @Column(name="disk_size") + long diskSize; + @Column(name="tags", length=4096) String tags; @@ -71,8 +71,8 @@ public class DiskOfferingVO implements DiskOffering, Identity { Type type; @Column(name=GenericDao.REMOVED) - @Temporal(TemporalType.TIMESTAMP) - private Date removed; + @Temporal(TemporalType.TIMESTAMP) + private Date removed; @Column(name=GenericDao.CREATED_COLUMN) private Date created; @@ -96,19 +96,19 @@ public class DiskOfferingVO implements DiskOffering, Identity { int sortKey; public DiskOfferingVO() { - this.uuid = UUID.randomUUID().toString(); + this.uuid = UUID.randomUUID().toString(); } - public DiskOfferingVO(Long domainId, String name, String displayText, long diskSize, String tags, boolean isCustomized) { - this.domainId = domainId; - this.name = name; - this.displayText = displayText; + public DiskOfferingVO(Long domainId, String name, String displayText, long diskSize, String tags, boolean isCustomized) { + this.domainId = domainId; + this.name = name; + this.displayText = displayText; this.diskSize = diskSize; this.tags = tags; this.recreatable = false; this.type = Type.Disk; this.useLocalStorage = false; - this.customized = isCustomized; + this.customized = isCustomized; this.uuid = UUID.randomUUID().toString(); } @@ -123,7 +123,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { this.systemUse = systemUse; this.customized = customized; this.uuid = UUID.randomUUID().toString(); - } + } //domain specific offerings constructor (null domainId implies public offering) public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage, boolean systemUse, boolean customized, Long domainId) { @@ -138,10 +138,10 @@ public class DiskOfferingVO implements DiskOffering, Identity { this.domainId = domainId; this.uuid = UUID.randomUUID().toString(); } - + @Override - public long getId() { - return id; + public long getId() { + return id; } @Override @@ -162,10 +162,10 @@ public class DiskOfferingVO implements DiskOffering, Identity { public boolean getUseLocalStorage() { return useLocalStorage; } - + @Override - public Long getDomainId() { - return domainId; + public Long getDomainId() { + return domainId; } public Type getType() { @@ -175,18 +175,18 @@ public class DiskOfferingVO implements DiskOffering, Identity { public boolean isRecreatable() { return recreatable; } - - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - - @Override - public String getName() { - return name; + + public void setDomainId(Long domainId) { + this.domainId = domainId; } - - public void setName(String name) { - this.name = name; + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; } @@ -197,28 +197,28 @@ public class DiskOfferingVO implements DiskOffering, Identity { public void setSystemUse(boolean systemUse) { this.systemUse = systemUse; - } - + } + @Override - public String getDisplayText() { - return displayText; - } - public void setDisplayText(String displayText) { - this.displayText = displayText; - } + public String getDisplayText() { + return displayText; + } + public void setDisplayText(String displayText) { + this.displayText = displayText; + } @Override public long getDiskSize(){ return diskSize; } - @Override - public void setDiskSize(long diskSize) { - this.diskSize = diskSize; - } - - public Date getRemoved() { - return removed; + @Override + public void setDiskSize(long diskSize) { + this.diskSize = diskSize; + } + + public Date getRemoved() { + return removed; } @Override @@ -305,5 +305,5 @@ public class DiskOfferingVO implements DiskOffering, Identity { public int getSortKey() { return sortKey; - } -} + } +} diff --git a/core/src/com/cloud/storage/LaunchPermissionVO.java b/core/src/com/cloud/storage/LaunchPermissionVO.java index 75cf59521b0..a367d451009 100644 --- a/core/src/com/cloud/storage/LaunchPermissionVO.java +++ b/core/src/com/cloud/storage/LaunchPermissionVO.java @@ -10,42 +10,42 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="launch_permission") -public class LaunchPermissionVO { - @Id - @Column(name="id") - private Long id; - - @Column(name="template_id") - private long templateId; - - @Column(name="account_id") - private long accountId; - - public LaunchPermissionVO() { } - - public LaunchPermissionVO(long templateId, long accountId) { - this.templateId = templateId; - this.accountId = accountId; - } - - public Long getId() { - return id; - } - - public long getTemplateId() { - return templateId; - } - - public long getAccountId() { - return accountId; - } -} +package com.cloud.storage; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="launch_permission") +public class LaunchPermissionVO { + @Id + @Column(name="id") + private Long id; + + @Column(name="template_id") + private long templateId; + + @Column(name="account_id") + private long accountId; + + public LaunchPermissionVO() { } + + public LaunchPermissionVO(long templateId, long accountId) { + this.templateId = templateId; + this.accountId = accountId; + } + + public Long getId() { + return id; + } + + public long getTemplateId() { + return templateId; + } + + public long getAccountId() { + return accountId; + } +} diff --git a/core/src/com/cloud/storage/SnapshotPolicyVO.java b/core/src/com/cloud/storage/SnapshotPolicyVO.java index 4b2f0b29073..4a42ad35e76 100644 --- a/core/src/com/cloud/storage/SnapshotPolicyVO.java +++ b/core/src/com/cloud/storage/SnapshotPolicyVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.UUID; import javax.persistence.Column; @@ -24,66 +24,66 @@ import javax.persistence.Table; import com.cloud.api.Identity; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.utils.DateUtil.IntervalType; - -@Entity -@Table(name="snapshot_policy") -public class SnapshotPolicyVO implements SnapshotPolicy, Identity { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - long id; - - @Column(name="volume_id") - long volumeId; - - @Column(name="schedule") - String schedule; + +@Entity +@Table(name="snapshot_policy") +public class SnapshotPolicyVO implements SnapshotPolicy, Identity { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; + + @Column(name="volume_id") + long volumeId; + + @Column(name="schedule") + String schedule; @Column(name="timezone") String timezone; - - @Column(name="interval") - private short interval; - - @Column(name="max_snaps") + + @Column(name="interval") + private short interval; + + @Column(name="max_snaps") private int maxSnaps; @Column(name="active") - boolean active = false; + boolean active = false; @Column(name="uuid") String uuid; - + public SnapshotPolicyVO() { this.uuid = UUID.randomUUID().toString(); - } - - public SnapshotPolicyVO(long volumeId, String schedule, String timezone, IntervalType intvType, int maxSnaps) { - this.volumeId = volumeId; + } + + public SnapshotPolicyVO(long volumeId, String schedule, String timezone, IntervalType intvType, int maxSnaps) { + this.volumeId = volumeId; this.schedule = schedule; - this.timezone = timezone; - this.interval = (short)intvType.ordinal(); + this.timezone = timezone; + this.interval = (short)intvType.ordinal(); this.maxSnaps = maxSnaps; - this.active = true; + this.active = true; this.uuid = UUID.randomUUID().toString(); - } - - public long getId() { - return id; - } - - public long getVolumeId() { - return volumeId; - } - + } + + public long getId() { + return id; + } + + public long getVolumeId() { + return volumeId; + } + public void setSchedule(String schedule) { this.schedule = schedule; } - public String getSchedule() { - return schedule; - } + public String getSchedule() { + return schedule; + } public void setInterval(short interval) { this.interval = interval; @@ -96,17 +96,17 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public String getTimezone() { return timezone; } - - public short getInterval() { - return interval; - } - + + public short getInterval() { + return interval; + } + public void setMaxSnaps(int maxSnaps) { this.maxSnaps = maxSnaps; } - public int getMaxSnaps() { - return maxSnaps; + public int getMaxSnaps() { + return maxSnaps; } public boolean isActive() { @@ -124,5 +124,5 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} + } +} diff --git a/core/src/com/cloud/storage/SnapshotScheduleVO.java b/core/src/com/cloud/storage/SnapshotScheduleVO.java index ffcc02897b5..96c6252c89f 100644 --- a/core/src/com/cloud/storage/SnapshotScheduleVO.java +++ b/core/src/com/cloud/storage/SnapshotScheduleVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import java.util.UUID; @@ -26,67 +26,67 @@ import javax.persistence.TemporalType; import com.cloud.api.Identity; import com.cloud.storage.snapshot.SnapshotSchedule; - -@Entity -@Table(name="snapshot_schedule") -public class SnapshotScheduleVO implements SnapshotSchedule, Identity { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - long id; + +@Entity +@Table(name="snapshot_schedule") +public class SnapshotScheduleVO implements SnapshotSchedule, Identity { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + long id; - // DB constraint: For a given volume and policyId, there will only be one entry in this table. - @Column(name="volume_id") - long volumeId; - - @Column(name="policy_id") - long policyId; - - @Column(name="scheduled_timestamp") - @Temporal(value=TemporalType.TIMESTAMP) + // DB constraint: For a given volume and policyId, there will only be one entry in this table. + @Column(name="volume_id") + long volumeId; + + @Column(name="policy_id") + long policyId; + + @Column(name="scheduled_timestamp") + @Temporal(value=TemporalType.TIMESTAMP) Date scheduledTimestamp; @Column(name="async_job_id") Long asyncJobId; @Column(name="snapshot_id") - Long snapshotId; + Long snapshotId; @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - - public SnapshotScheduleVO() { } - - public SnapshotScheduleVO(long volumeId, long policyId, Date scheduledTimestamp) { - this.volumeId = volumeId; - this.policyId = policyId; + + public SnapshotScheduleVO() { } + + public SnapshotScheduleVO(long volumeId, long policyId, Date scheduledTimestamp) { + this.volumeId = volumeId; + this.policyId = policyId; this.scheduledTimestamp = scheduledTimestamp; this.snapshotId = null; - this.asyncJobId = null; - } - - public long getId() { - return id; - } - - public Long getVolumeId() { - return volumeId; - } - - public Long getPolicyId() { - return policyId; - } - + this.asyncJobId = null; + } + + public long getId() { + return id; + } + + public Long getVolumeId() { + return volumeId; + } + + public Long getPolicyId() { + return policyId; + } + public void setPolicyId(long policyId) { this.policyId = policyId; } - /** - * @return the scheduledTimestamp - */ - public Date getScheduledTimestamp() { - return scheduledTimestamp; + /** + * @return the scheduledTimestamp + */ + public Date getScheduledTimestamp() { + return scheduledTimestamp; } public void setScheduledTimestamp(Date scheduledTimestamp) { @@ -116,5 +116,5 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } + } } diff --git a/core/src/com/cloud/storage/SnapshotVO.java b/core/src/com/cloud/storage/SnapshotVO.java index fd66cb47c98..24a5c9e88d7 100644 --- a/core/src/com/cloud/storage/SnapshotVO.java +++ b/core/src/com/cloud/storage/SnapshotVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import java.util.UUID; @@ -28,70 +28,70 @@ import com.cloud.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; - -@Entity -@Table(name="snapshots") -public class SnapshotVO implements Snapshot, Identity { - - @Id + +@Entity +@Table(name="snapshots") +public class SnapshotVO implements Snapshot, Identity { + + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id = -1; @Column(name="data_center_id") - long dataCenterId; - - @Column(name="account_id") + long dataCenterId; + + @Column(name="account_id") long accountId; @Column(name="domain_id") - long domainId; - - @Column(name="volume_id") + long domainId; + + @Column(name="volume_id") Long volumeId; @Column(name="disk_offering_id") - Long diskOfferingId; - - @Expose - @Column(name="path") - String path; - - @Expose - @Column(name="name") + Long diskOfferingId; + + @Expose + @Column(name="path") + String path; + + @Expose + @Column(name="name") String name; - @Expose - @Column(name="status", updatable = true, nullable=false) - @Enumerated(value=EnumType.STRING) - private Status status; - - @Column(name="snapshot_type") - short snapshotType; - - @Column(name="type_description") + @Expose + @Column(name="status", updatable = true, nullable=false) + @Enumerated(value=EnumType.STRING) + private Status status; + + @Column(name="snapshot_type") + short snapshotType; + + @Column(name="type_description") String typeDescription; - + @Column(name="size") long size; - - @Column(name=GenericDao.CREATED_COLUMN) - Date created; - - @Column(name=GenericDao.REMOVED_COLUMN) + + @Column(name=GenericDao.CREATED_COLUMN) + Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) Date removed; - - @Column(name="backup_snap_id") - String backupSnapshotId; + + @Column(name="backup_snap_id") + String backupSnapshotId; @Column(name="swift_id") Long swiftId; @Column(name="sechost_id") Long secHostId; - - @Column(name="prev_snap_id") - long prevSnapshotId; + + @Column(name="prev_snap_id") + long prevSnapshotId; @Column(name="hypervisor_type") @Enumerated(value=EnumType.STRING) @@ -106,48 +106,48 @@ public class SnapshotVO implements Snapshot, Identity { public SnapshotVO() { this.uuid = UUID.randomUUID().toString(); - } - + } + public SnapshotVO(long dcId, long accountId, long domainId, Long volumeId, Long diskOfferingId, String path, String name, short snapshotType, String typeDescription, long size, HypervisorType hypervisorType ) { this.dataCenterId = dcId; this.accountId = accountId; this.domainId = domainId; this.volumeId = volumeId; - this.diskOfferingId = diskOfferingId; - this.path = path; - this.name = name; - this.snapshotType = snapshotType; + this.diskOfferingId = diskOfferingId; + this.path = path; + this.name = name; + this.snapshotType = snapshotType; this.typeDescription = typeDescription; - this.size = size; + this.size = size; this.status = Status.Creating; this.prevSnapshotId = 0; this.hypervisorType = hypervisorType; this.version = "2.2"; this.uuid = UUID.randomUUID().toString(); - } + } - @Override - public Long getId() { - return id; - } + @Override + public Long getId() { + return id; + } public long getDataCenterId() { return dataCenterId; } - @Override - public long getAccountId() { - return accountId; - } + @Override + public long getAccountId() { + return accountId; + } public long getDomainId() { return domainId; } - @Override - public long getVolumeId() { - return volumeId; - } + @Override + public long getVolumeId() { + return volumeId; + } public long getDiskOfferingId() { return diskOfferingId; @@ -157,19 +157,19 @@ public class SnapshotVO implements Snapshot, Identity { this.volumeId = volumeId; } - @Override - public String getPath() { - return path; - } + @Override + public String getPath() { + return path; + } - public void setPath(String path) { - this.path = path; - } + public void setPath(String path) { + this.path = path; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } @Override public short getsnapshotType() { return snapshotType; @@ -181,7 +181,7 @@ public class SnapshotVO implements Snapshot, Identity { return null; } return Type.values()[snapshotType]; - } + } public Long getSwiftId() { return swiftId; @@ -203,9 +203,9 @@ public class SnapshotVO implements Snapshot, Identity { public HypervisorType getHypervisorType() { return hypervisorType; } - - public void setSnapshotType(short snapshotType) { - this.snapshotType = snapshotType; + + public void setSnapshotType(short snapshotType) { + this.snapshotType = snapshotType; } @Override @@ -214,19 +214,19 @@ public class SnapshotVO implements Snapshot, Identity { return true; } return false; - } - + } + public long getSize() { return size; } - public String getTypeDescription() { - return typeDescription; - } - public void setTypeDescription(String typeDescription) { - this.typeDescription = typeDescription; - } - + public String getTypeDescription() { + return typeDescription; + } + public void setTypeDescription(String typeDescription) { + this.typeDescription = typeDescription; + } + public String getVersion() { return version; } @@ -235,37 +235,37 @@ public class SnapshotVO implements Snapshot, Identity { this.version = version; } - public Date getCreated() { - return created; - } - - public Date getRemoved() { - return removed; - } - - @Override - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - public String getBackupSnapshotId(){ - return backupSnapshotId; - } - - public long getPrevSnapshotId(){ - return prevSnapshotId; - } - - public void setBackupSnapshotId(String backUpSnapshotId){ - this.backupSnapshotId = backUpSnapshotId; - } - - public void setPrevSnapshotId(long prevSnapshotId){ - this.prevSnapshotId = prevSnapshotId; + public Date getCreated() { + return created; + } + + public Date getRemoved() { + return removed; + } + + @Override + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public String getBackupSnapshotId(){ + return backupSnapshotId; + } + + public long getPrevSnapshotId(){ + return prevSnapshotId; + } + + public void setBackupSnapshotId(String backUpSnapshotId){ + this.backupSnapshotId = backUpSnapshotId; + } + + public void setPrevSnapshotId(long prevSnapshotId){ + this.prevSnapshotId = prevSnapshotId; } public static Type getSnapshotType(String snapshotType) { @@ -285,4 +285,4 @@ public class SnapshotVO implements Snapshot, Identity { public void setUuid(String uuid) { this.uuid = uuid; } -} +} diff --git a/core/src/com/cloud/storage/SwiftVO.java b/core/src/com/cloud/storage/SwiftVO.java index d2e3cd7f9a0..ea6672eaec8 100644 --- a/core/src/com/cloud/storage/SwiftVO.java +++ b/core/src/com/cloud/storage/SwiftVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import java.util.UUID; @@ -25,11 +25,11 @@ import javax.persistence.Table; import com.cloud.agent.api.to.SwiftTO; import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="swift") -public class SwiftVO implements Swift, Identity { - + +@Entity +@Table(name="swift") +public class SwiftVO implements Swift, Identity { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -37,13 +37,13 @@ public class SwiftVO implements Swift, Identity { @Column(name="url") String url; - - @Column(name="account") + + @Column(name="account") String account; @Column(name="username") - String userName; - + String userName; + @Column(name="key") String key; @@ -53,8 +53,8 @@ public class SwiftVO implements Swift, Identity { @Column(name = GenericDao.CREATED_COLUMN) private Date created; - public SwiftVO() { } - + public SwiftVO() { } + public SwiftVO(String url, String account, String userName, String key) { this.url = url; this.account = account; @@ -65,7 +65,7 @@ public class SwiftVO implements Swift, Identity { @Override public long getId() { return id; - } + } @Override public String getUrl() { return url; @@ -100,4 +100,4 @@ public class SwiftVO implements Swift, Identity { public void setUuid(String uuid) { this.uuid = uuid; } -} +} diff --git a/core/src/com/cloud/storage/VMTemplateDetailVO.java b/core/src/com/cloud/storage/VMTemplateDetailVO.java index 99e3880c5b2..312dcdbc14e 100644 --- a/core/src/com/cloud/storage/VMTemplateDetailVO.java +++ b/core/src/com/cloud/storage/VMTemplateDetailVO.java @@ -10,69 +10,69 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="vm_template_details") -public class VMTemplateDetailVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="template_id") - private long templateId; - - @Column(name="name") - private String name; - - @Column(name="value", length=1024) - private String value; - - public VMTemplateDetailVO() {} - - public VMTemplateDetailVO(long templateId, String name, String value) { - this.templateId = templateId; - this.name = name; - this.value = value; - } - - public long getId() { - return id; - } - - public long getTemplateId() { - return templateId; - } - - public String getName() { - return name; - } - - public String getValue() { - return value; - } - - public void setId(long id) { - this.id = id; - } - - public void setTemplateId(long templateId) { - this.templateId = templateId; - } - - public void setName(String name) { - this.name = name; - } - - public void setValue(String value) { - this.value = value; - } -} +package com.cloud.storage; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="vm_template_details") +public class VMTemplateDetailVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="template_id") + private long templateId; + + @Column(name="name") + private String name; + + @Column(name="value", length=1024) + private String value; + + public VMTemplateDetailVO() {} + + public VMTemplateDetailVO(long templateId, String name, String value) { + this.templateId = templateId; + this.name = name; + this.value = value; + } + + public long getId() { + return id; + } + + public long getTemplateId() { + return templateId; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + + public void setId(long id) { + this.id = id; + } + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + public void setName(String name) { + this.name = name; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/core/src/com/cloud/storage/VMTemplateHostVO.java b/core/src/com/cloud/storage/VMTemplateHostVO.java index fceb4d5f20c..25e015a727d 100755 --- a/core/src/com/cloud/storage/VMTemplateHostVO.java +++ b/core/src/com/cloud/storage/VMTemplateHostVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import javax.persistence.Column; @@ -26,214 +26,214 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; - -/** - * Join table for storage hosts and templates - * @author chiradeep - * - */ -@Entity -@Table(name="template_host_ref") -public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - Long id; - - @Column(name="host_id") - private long hostId; - - @Column(name="template_id") - private long templateId; - - @Column(name=GenericDaoBase.CREATED_COLUMN) - private Date created = null; - - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; - - @Column (name="download_pct") + +/** + * Join table for storage hosts and templates + * @author chiradeep + * + */ +@Entity +@Table(name="template_host_ref") +public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + Long id; + + @Column(name="host_id") + private long hostId; + + @Column(name="template_id") + private long templateId; + + @Column(name=GenericDaoBase.CREATED_COLUMN) + private Date created = null; + + @Column(name="last_updated") + @Temporal(value=TemporalType.TIMESTAMP) + private Date lastUpdated = null; + + @Column (name="download_pct") private int downloadPercent; - - @Column (name="size") + + @Column (name="size") private long size; @Column (name="physical_size") - private long physicalSize; - - @Column (name="download_state") - @Enumerated(EnumType.STRING) + private long physicalSize; + + @Column (name="download_state") + @Enumerated(EnumType.STRING) private Status downloadState; - - @Column (name="local_path") - private String localDownloadPath; - - @Column (name="error_str") - private String errorString; - - @Column (name="job_id") - private String jobId; - - @Column (name="install_path") + + @Column (name="local_path") + private String localDownloadPath; + + @Column (name="error_str") + private String errorString; + + @Column (name="job_id") + private String jobId; + + @Column (name="install_path") private String installPath; @Column (name="url") private String downloadUrl; @Column(name="is_copy") - private boolean isCopy = false; + private boolean isCopy = false; @Column(name="destroyed") - boolean destroyed = false; - + boolean destroyed = false; + @Override - public String getInstallPath() { - return installPath; - } - - public long getHostId() { - return hostId; - } - - public void setHostId(long hostId) { - this.hostId = hostId; - } - + public String getInstallPath() { + return installPath; + } + + public long getHostId() { + return hostId; + } + + public void setHostId(long hostId) { + this.hostId = hostId; + } + @Override - public long getTemplateId() { - return templateId; - } - + public long getTemplateId() { + return templateId; + } + @Override - public void setTemplateId(long templateId) { - this.templateId = templateId; - } - + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + @Override - public int getDownloadPercent() { - return downloadPercent; - } - + public int getDownloadPercent() { + return downloadPercent; + } + @Override - public void setDownloadPercent(int downloadPercent) { - this.downloadPercent = downloadPercent; - } - + public void setDownloadPercent(int downloadPercent) { + this.downloadPercent = downloadPercent; + } + @Override - public void setDownloadState(Status downloadState) { - this.downloadState = downloadState; - } - + public void setDownloadState(Status downloadState) { + this.downloadState = downloadState; + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public Date getCreated() { - return created; - } - + public Date getCreated() { + return created; + } + @Override - public Date getLastUpdated() { - return lastUpdated; - } - + public Date getLastUpdated() { + return lastUpdated; + } + @Override - public void setLastUpdated(Date date) { - lastUpdated = date; - } - + public void setLastUpdated(Date date) { + lastUpdated = date; + } + @Override - public void setInstallPath(String installPath) { - this.installPath = installPath; - } - + public void setInstallPath(String installPath) { + this.installPath = installPath; + } + @Override - public Status getDownloadState() { - return downloadState; - } - - public VMTemplateHostVO(long hostId, long templateId) { - super(); - this.hostId = hostId; - this.templateId = templateId; - } - - public VMTemplateHostVO(long hostId, long templateId, Date lastUpdated, - int downloadPercent, Status downloadState, - String localDownloadPath, String errorString, String jobId, - String installPath, String downloadUrl) { - super(); - this.hostId = hostId; - this.templateId = templateId; - this.lastUpdated = lastUpdated; - this.downloadPercent = downloadPercent; - this.downloadState = downloadState; - this.localDownloadPath = localDownloadPath; - this.errorString = errorString; - this.jobId = jobId; + public Status getDownloadState() { + return downloadState; + } + + public VMTemplateHostVO(long hostId, long templateId) { + super(); + this.hostId = hostId; + this.templateId = templateId; + } + + public VMTemplateHostVO(long hostId, long templateId, Date lastUpdated, + int downloadPercent, Status downloadState, + String localDownloadPath, String errorString, String jobId, + String installPath, String downloadUrl) { + super(); + this.hostId = hostId; + this.templateId = templateId; + this.lastUpdated = lastUpdated; + this.downloadPercent = downloadPercent; + this.downloadState = downloadState; + this.localDownloadPath = localDownloadPath; + this.errorString = errorString; + this.jobId = jobId; this.installPath = installPath; - this.setDownloadUrl(downloadUrl); - } - - protected VMTemplateHostVO() { - - } - + this.setDownloadUrl(downloadUrl); + } + + protected VMTemplateHostVO() { + + } + @Override - public void setLocalDownloadPath(String localPath) { - this.localDownloadPath = localPath; - } - + public void setLocalDownloadPath(String localPath) { + this.localDownloadPath = localPath; + } + @Override - public String getLocalDownloadPath() { - return localDownloadPath; - } - + public String getLocalDownloadPath() { + return localDownloadPath; + } + @Override - public void setErrorString(String errorString) { - this.errorString = errorString; - } - + public void setErrorString(String errorString) { + this.errorString = errorString; + } + @Override - public String getErrorString() { - return errorString; - } - + public String getErrorString() { + return errorString; + } + @Override - public void setJobId(String jobId) { - this.jobId = jobId; - } - + public void setJobId(String jobId) { + this.jobId = jobId; + } + @Override - public String getJobId() { - return jobId; - } - - @Override - public boolean equals(Object obj) { + public String getJobId() { + return jobId; + } + + @Override + public boolean equals(Object obj) { if (obj instanceof VMTemplateHostVO) { - VMTemplateHostVO other = (VMTemplateHostVO)obj; - return (this.templateId==other.getTemplateId() && this.hostId==other.getHostId()); - } - return false; - } - - @Override - public int hashCode() { - Long tid = new Long(templateId); - Long hid = new Long(hostId); - return tid.hashCode()+hid.hashCode(); - } - - public void setSize(long size) { - this.size = size; - } - - public long getSize() { - return size; - } + VMTemplateHostVO other = (VMTemplateHostVO)obj; + return (this.templateId==other.getTemplateId() && this.hostId==other.getHostId()); + } + return false; + } + + @Override + public int hashCode() { + Long tid = new Long(templateId); + Long hid = new Long(hostId); + return tid.hashCode()+hid.hashCode(); + } + + public void setSize(long size) { + this.size = size; + } + + public long getSize() { + return size; + } public void setPhysicalSize(long physicalSize) { @@ -246,7 +246,7 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc { public void setDestroyed(boolean destroyed) { this.destroyed = destroyed; - } + } public boolean getDestroyed() { return destroyed; @@ -277,5 +277,5 @@ public class VMTemplateHostVO implements VMTemplateStorageResourceAssoc { public String toString() { return new StringBuilder("TmplHost[").append(id).append("-").append(templateId).append("-").append(hostId).append(installPath).append("]").toString(); } - -} + +} diff --git a/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java index e8398934b09..37fe15a69ee 100644 --- a/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java +++ b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import javax.persistence.Column; @@ -26,209 +26,209 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; - -/** - * Join table for storage pools and templates - * @author chiradeep - * - */ -@Entity -@Table(name="template_spool_ref") -public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc{ - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - long id; - - @Column(name="pool_id") - private long poolId; - - @Column(name="template_id") long templateId; - - @Column(name=GenericDaoBase.CREATED_COLUMN) Date created = null; - - @Column(name="last_updated") - @Temporal(value=TemporalType.TIMESTAMP) Date lastUpdated = null; - - @Column (name="download_pct") int downloadPercent; - - @Column (name="download_state") - @Enumerated(EnumType.STRING) Status downloadState; - - @Column (name="local_path") String localDownloadPath; - - @Column (name="error_str") String errorString; - - @Column (name="job_id") String jobId; - - @Column (name="install_path") String installPath; - - @Column (name="template_size") long templateSize; - - @Column (name="marked_for_gc") boolean markedForGC; - + +/** + * Join table for storage pools and templates + * @author chiradeep + * + */ +@Entity +@Table(name="template_spool_ref") +public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc{ + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + long id; + + @Column(name="pool_id") + private long poolId; + + @Column(name="template_id") long templateId; + + @Column(name=GenericDaoBase.CREATED_COLUMN) Date created = null; + + @Column(name="last_updated") + @Temporal(value=TemporalType.TIMESTAMP) Date lastUpdated = null; + + @Column (name="download_pct") int downloadPercent; + + @Column (name="download_state") + @Enumerated(EnumType.STRING) Status downloadState; + + @Column (name="local_path") String localDownloadPath; + + @Column (name="error_str") String errorString; + + @Column (name="job_id") String jobId; + + @Column (name="install_path") String installPath; + + @Column (name="template_size") long templateSize; + + @Column (name="marked_for_gc") boolean markedForGC; + @Override - public String getInstallPath() { - return installPath; - } - + public String getInstallPath() { + return installPath; + } + @Override - public long getTemplateSize() { - return templateSize; - } - - public long getPoolId() { - return poolId; - } - - public void setpoolId(long poolId) { - this.poolId = poolId; - } - + public long getTemplateSize() { + return templateSize; + } + + public long getPoolId() { + return poolId; + } + + public void setpoolId(long poolId) { + this.poolId = poolId; + } + @Override - public long getTemplateId() { - return templateId; - } - + public long getTemplateId() { + return templateId; + } + @Override - public void setTemplateId(long templateId) { - this.templateId = templateId; - } - + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + @Override - public int getDownloadPercent() { - return downloadPercent; - } - + public int getDownloadPercent() { + return downloadPercent; + } + @Override - public void setDownloadPercent(int downloadPercent) { - this.downloadPercent = downloadPercent; - } - + public void setDownloadPercent(int downloadPercent) { + this.downloadPercent = downloadPercent; + } + @Override - public void setDownloadState(Status downloadState) { - this.downloadState = downloadState; - } - + public void setDownloadState(Status downloadState) { + this.downloadState = downloadState; + } + @Override - public long getId() { - return id; - } - + public long getId() { + return id; + } + @Override - public Date getCreated() { - return created; - } - + public Date getCreated() { + return created; + } + @Override - public Date getLastUpdated() { - return lastUpdated; - } - + public Date getLastUpdated() { + return lastUpdated; + } + @Override - public void setLastUpdated(Date date) { - lastUpdated = date; - } - + public void setLastUpdated(Date date) { + lastUpdated = date; + } + @Override - public void setInstallPath(String installPath) { - this.installPath = installPath; - } - + public void setInstallPath(String installPath) { + this.installPath = installPath; + } + @Override - public Status getDownloadState() { - return downloadState; - } - - public VMTemplateStoragePoolVO(long poolId, long templateId) { - super(); - this.poolId = poolId; - this.templateId = templateId; - this.downloadState = Status.NOT_DOWNLOADED; - this.markedForGC = false; - } - - public VMTemplateStoragePoolVO(long poolId, long templateId, Date lastUpdated, - int downloadPercent, Status downloadState, - String localDownloadPath, String errorString, String jobId, - String installPath, long templateSize) { - super(); - this.poolId = poolId; - this.templateId = templateId; - this.lastUpdated = lastUpdated; - this.downloadPercent = downloadPercent; - this.downloadState = downloadState; - this.localDownloadPath = localDownloadPath; - this.errorString = errorString; - this.jobId = jobId; - this.installPath = installPath; - this.templateSize = templateSize; - } - - protected VMTemplateStoragePoolVO() { - - } - + public Status getDownloadState() { + return downloadState; + } + + public VMTemplateStoragePoolVO(long poolId, long templateId) { + super(); + this.poolId = poolId; + this.templateId = templateId; + this.downloadState = Status.NOT_DOWNLOADED; + this.markedForGC = false; + } + + public VMTemplateStoragePoolVO(long poolId, long templateId, Date lastUpdated, + int downloadPercent, Status downloadState, + String localDownloadPath, String errorString, String jobId, + String installPath, long templateSize) { + super(); + this.poolId = poolId; + this.templateId = templateId; + this.lastUpdated = lastUpdated; + this.downloadPercent = downloadPercent; + this.downloadState = downloadState; + this.localDownloadPath = localDownloadPath; + this.errorString = errorString; + this.jobId = jobId; + this.installPath = installPath; + this.templateSize = templateSize; + } + + protected VMTemplateStoragePoolVO() { + + } + @Override - public void setLocalDownloadPath(String localPath) { - this.localDownloadPath = localPath; - } - + public void setLocalDownloadPath(String localPath) { + this.localDownloadPath = localPath; + } + @Override - public String getLocalDownloadPath() { - return localDownloadPath; - } - + public String getLocalDownloadPath() { + return localDownloadPath; + } + @Override - public void setErrorString(String errorString) { - this.errorString = errorString; - } - + public void setErrorString(String errorString) { + this.errorString = errorString; + } + @Override - public String getErrorString() { - return errorString; - } - + public String getErrorString() { + return errorString; + } + @Override - public void setJobId(String jobId) { - this.jobId = jobId; - } - + public void setJobId(String jobId) { + this.jobId = jobId; + } + @Override - public String getJobId() { - return jobId; - } - - public void setTemplateSize(long templateSize) { - this.templateSize = templateSize; - } - - public boolean getMarkedForGC() { - return markedForGC; - } - - public void setMarkedForGC(boolean markedForGC) { - this.markedForGC = markedForGC; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof VMTemplateStoragePoolVO) { - VMTemplateStoragePoolVO other = (VMTemplateStoragePoolVO)obj; - return (this.templateId==other.getTemplateId() && this.poolId==other.getPoolId()); - } - return false; - } - - @Override - public int hashCode() { - Long tid = new Long(templateId); - Long hid = new Long(poolId); - return tid.hashCode()+hid.hashCode(); - } + public String getJobId() { + return jobId; + } + + public void setTemplateSize(long templateSize) { + this.templateSize = templateSize; + } + + public boolean getMarkedForGC() { + return markedForGC; + } + + public void setMarkedForGC(boolean markedForGC) { + this.markedForGC = markedForGC; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof VMTemplateStoragePoolVO) { + VMTemplateStoragePoolVO other = (VMTemplateStoragePoolVO)obj; + return (this.templateId==other.getTemplateId() && this.poolId==other.getPoolId()); + } + return false; + } + + @Override + public int hashCode() { + Long tid = new Long(templateId); + Long hid = new Long(poolId); + return tid.hashCode()+hid.hashCode(); + } @Override public String toString() { return new StringBuilder("TmplPool[").append(id).append("-").append(templateId).append("-").append("poolId").append("-").append(installPath).append("]").toString(); - } - -} + } + +} diff --git a/core/src/com/cloud/storage/VMTemplateSwiftVO.java b/core/src/com/cloud/storage/VMTemplateSwiftVO.java index 85d2453594a..921bdffbadd 100755 --- a/core/src/com/cloud/storage/VMTemplateSwiftVO.java +++ b/core/src/com/cloud/storage/VMTemplateSwiftVO.java @@ -99,4 +99,4 @@ public class VMTemplateSwiftVO { return new StringBuilder("TmplSwift[").append(id).append("-").append(templateId).append("-").append(swiftId).append("]").toString(); } -} +} diff --git a/core/src/com/cloud/storage/VMTemplateVO.java b/core/src/com/cloud/storage/VMTemplateVO.java index fae4cb8d4bb..ee147320791 100755 --- a/core/src/com/cloud/storage/VMTemplateVO.java +++ b/core/src/com/cloud/storage/VMTemplateVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage; - +package com.cloud.storage; + import java.util.Date; import java.util.Map; import java.util.UUID; @@ -33,66 +33,66 @@ import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; import com.cloud.template.VirtualMachineTemplate; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="vm_template") -public class VMTemplateVO implements VirtualMachineTemplate, Identity { - @Id - @TableGenerator(name="vm_template_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_template_seq", allocationSize=1) - @Column(name="id", nullable = false) - private long id; - - @Column(name="format") - private Storage.ImageFormat format; - - @Column(name="unique_name") - private String uniqueName; - - @Column(name="name") - private String name = null; - - @Column(name="public") + +@Entity +@Table(name="vm_template") +public class VMTemplateVO implements VirtualMachineTemplate, Identity { + @Id + @TableGenerator(name="vm_template_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_template_seq", allocationSize=1) + @Column(name="id", nullable = false) + private long id; + + @Column(name="format") + private Storage.ImageFormat format; + + @Column(name="unique_name") + private String uniqueName; + + @Column(name="name") + private String name = null; + + @Column(name="public") private boolean publicTemplate = true; @Column(name="featured") - private boolean featured; - - @Column(name="type") - private Storage.TemplateType templateType; - - @Column(name="url") - private String url = null; - - @Column(name="hvm") - private boolean requiresHvm; - - @Column(name="bits") - private int bits; - - @Temporal(value=TemporalType.TIMESTAMP) - @Column(name=GenericDao.CREATED_COLUMN) - private Date created = null; - + private boolean featured; + + @Column(name="type") + private Storage.TemplateType templateType; + + @Column(name="url") + private String url = null; + + @Column(name="hvm") + private boolean requiresHvm; + + @Column(name="bits") + private int bits; + + @Temporal(value=TemporalType.TIMESTAMP) + @Column(name=GenericDao.CREATED_COLUMN) + private Date created = null; + @Column(name=GenericDao.REMOVED) - @Temporal(TemporalType.TIMESTAMP) - private Date removed; - - @Column(name="account_id") - private long accountId; - - @Column(name="checksum") - private String checksum; - - @Column(name="display_text", length=4096) - private String displayText; - - @Column(name="enable_password") - private boolean enablePassword; - - @Column(name="guest_os_id") - private long guestOSId; - - @Column(name="bootable") + @Temporal(TemporalType.TIMESTAMP) + private Date removed; + + @Column(name="account_id") + private long accountId; + + @Column(name="checksum") + private String checksum; + + @Column(name="display_text", length=4096) + private String displayText; + + @Column(name="enable_password") + private boolean enablePassword; + + @Column(name="guest_os_id") + private long guestOSId; + + @Column(name="bootable") private boolean bootable = true; @Column(name="prepopulate") @@ -104,10 +104,10 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { @Column(name="hypervisor_type") @Enumerated(value=EnumType.STRING) private HypervisorType hypervisorType; - + @Column(name="extractable") private boolean extractable = true; - + @Column(name="source_template_id") private Long sourceTemplateId; @@ -127,23 +127,23 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { Map details; @Override - public String getUniqueName() { - return uniqueName; - } - - public void setUniqueName(String uniqueName) { - this.uniqueName = uniqueName; - } - + public String getUniqueName() { + return uniqueName; + } + + public void setUniqueName(String uniqueName) { + this.uniqueName = uniqueName; + } + protected VMTemplateVO() { - this.uuid = UUID.randomUUID().toString(); - } - - /** - * Proper constructor for a new vm template. - */ - public VMTemplateVO(long id, String name, ImageFormat format, boolean isPublic, boolean featured, boolean isExtractable, TemplateType type, String url, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType, Map details) { - this(id, generateUniqueName(id, accountId, name), name, format, isPublic, featured, isExtractable, type, url, null, requiresHvm, bits, accountId, cksum, displayText, enablePassword, guestOSId, bootable, hyperType, details); + this.uuid = UUID.randomUUID().toString(); + } + + /** + * Proper constructor for a new vm template. + */ + public VMTemplateVO(long id, String name, ImageFormat format, boolean isPublic, boolean featured, boolean isExtractable, TemplateType type, String url, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType, Map details) { + this(id, generateUniqueName(id, accountId, name), name, format, isPublic, featured, isExtractable, type, url, null, requiresHvm, bits, accountId, cksum, displayText, enablePassword, guestOSId, bootable, hyperType, details); this.uuid = UUID.randomUUID().toString(); } @@ -152,27 +152,27 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { this.templateTag = templateTag; this.uuid = UUID.randomUUID().toString(); this.enableSshKey = sshKeyEnabled; - } - - public VMTemplateVO(Long id, String uniqueName, String name, ImageFormat format, boolean isPublic, boolean featured, TemplateType type, String url, Date created, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType) { - this.id = id; - this.name = name; + } + + public VMTemplateVO(Long id, String uniqueName, String name, ImageFormat format, boolean isPublic, boolean featured, TemplateType type, String url, Date created, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType) { + this.id = id; + this.name = name; this.publicTemplate = isPublic; - this.featured = featured; - this.templateType = type; - this.url = url; - this.requiresHvm = requiresHvm; - this.bits = bits; - this.accountId = accountId; - this.checksum = cksum; - this.uniqueName = uniqueName; - this.displayText = displayText; - this.enablePassword = enablePassword; - this.format = format; - this.created = created; - this.guestOSId = guestOSId; + this.featured = featured; + this.templateType = type; + this.url = url; + this.requiresHvm = requiresHvm; + this.bits = bits; + this.accountId = accountId; + this.checksum = cksum; + this.uniqueName = uniqueName; + this.displayText = displayText; + this.enablePassword = enablePassword; + this.format = format; + this.created = created; + this.guestOSId = guestOSId; this.bootable = bootable; - this.hypervisorType = hyperType; + this.hypervisorType = hyperType; this.uuid = UUID.randomUUID().toString(); } @@ -190,81 +190,81 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { this.uuid = UUID.randomUUID().toString(); } - @Override + @Override public boolean getEnablePassword() { - return enablePassword; - } - + return enablePassword; + } + @Override - public Storage.ImageFormat getFormat() { - return format; - } - - public void setEnablePassword(boolean enablePassword) { - this.enablePassword = enablePassword; - } - - public void setFormat(ImageFormat format) { - this.format = format; - } - - private static String generateUniqueName(long id, long userId, String displayName) { - StringBuilder name = new StringBuilder(); - name.append(id); - name.append("-"); - name.append(userId); - name.append("-"); - name.append(UUID.nameUUIDFromBytes((displayName + System.currentTimeMillis()).getBytes()).toString()); - return name.toString(); - } - - @Override - public long getId() { - return id; - } - + public Storage.ImageFormat getFormat() { + return format; + } + + public void setEnablePassword(boolean enablePassword) { + this.enablePassword = enablePassword; + } + + public void setFormat(ImageFormat format) { + this.format = format; + } + + private static String generateUniqueName(long id, long userId, String displayName) { + StringBuilder name = new StringBuilder(); + name.append(id); + name.append("-"); + name.append(userId); + name.append("-"); + name.append(UUID.nameUUIDFromBytes((displayName + System.currentTimeMillis()).getBytes()).toString()); + return name.toString(); + } + @Override - public TemplateType getTemplateType() { - return templateType; - } - - public void setTemplateType(TemplateType type) { - this.templateType = type; - } - - public boolean requiresHvm() { - return requiresHvm; - } - + public long getId() { + return id; + } + @Override - public int getBits() { - return bits; - } - - public void setBits(int bits) { - this.bits = bits; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Date getRemoved() { - return removed; - } - - @Override - public boolean isPublicTemplate() { - return publicTemplate; - } - - public void setPublicTemplate(boolean publicTemplate) { - this.publicTemplate = publicTemplate; + public TemplateType getTemplateType() { + return templateType; + } + + public void setTemplateType(TemplateType type) { + this.templateType = type; + } + + public boolean requiresHvm() { + return requiresHvm; + } + + @Override + public int getBits() { + return bits; + } + + public void setBits(int bits) { + this.bits = bits; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getRemoved() { + return removed; + } + + @Override + public boolean isPublicTemplate() { + return publicTemplate; + } + + public void setPublicTemplate(boolean publicTemplate) { + this.publicTemplate = publicTemplate; } @Override @@ -274,70 +274,70 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public void setFeatured(boolean featured) { this.featured = featured; - } - + } + @Override - public Date getCreated() { - return created; - } - + public Date getCreated() { + return created; + } + @Override - public String getUrl() { - return url; + public String getUrl() { + return url; } public void setUrl(String url) { this.url = url; - } - + } + @Override - public boolean isRequiresHvm() { - return requiresHvm; - } - - public void setRequiresHvm(boolean value) { - requiresHvm = value; - } - + public boolean isRequiresHvm() { + return requiresHvm; + } + + public void setRequiresHvm(boolean value) { + requiresHvm = value; + } + @Override - public long getAccountId() { - return accountId; - } - + public long getAccountId() { + return accountId; + } + @Override - public String getChecksum() { - return checksum; - } - + public String getChecksum() { + return checksum; + } + public void setChecksum(String checksum) { this.checksum = checksum; } @Override - public String getDisplayText() { - return displayText; - } - - public void setDisplayText(String displayText) { - this.displayText = displayText; - } - + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + @Override - public long getGuestOSId() { - return guestOSId; - } - - public void setGuestOSId(long guestOSId) { - this.guestOSId = guestOSId; - } - + public long getGuestOSId() { + return guestOSId; + } + + public void setGuestOSId(long guestOSId) { + this.guestOSId = guestOSId; + } + @Override - public boolean isBootable() { - return bootable; - } - - public void setBootable(boolean bootable) { - this.bootable = bootable; + public boolean isBootable() { + return bootable; + } + + public void setBootable(boolean bootable) { + this.bootable = bootable; } public void setPrepopulate(boolean prepopulate) { @@ -463,5 +463,5 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public void setEnableSshKey(boolean enable) { enableSshKey = enable; } - -} + +} diff --git a/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java index 4c00852cdfe..d49dee96a04 100644 --- a/core/src/com/cloud/storage/template/VmdkProcessor.java +++ b/core/src/com/cloud/storage/template/VmdkProcessor.java @@ -10,73 +10,73 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.storage.template; - -import java.io.File; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; +package com.cloud.storage.template; + +import java.io.File; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - -import org.apache.log4j.Logger; - -import com.cloud.exception.InternalErrorException; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.storage.StorageLayer; -import com.cloud.utils.script.Script; - -@Local(value=Processor.class) -public class VmdkProcessor implements Processor { - private static final Logger s_logger = Logger.getLogger(VmdkProcessor.class); - - String _name; - StorageLayer _storage; - - @Override - public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { - if (format != null) { - if(s_logger.isInfoEnabled()) - s_logger.info("We currently don't handle conversion from " + format + " to VMDK."); - return null; - } - - s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); - if (!_storage.exists(templateFilePath)) { - if(s_logger.isInfoEnabled()) - s_logger.info("Unable to find the vmware template file: " + templateFilePath); - return null; - } - - s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFileFullPath = templatePath + templateName + "." + ImageFormat.OVA.getFileExtension(); - File templateFile = new File(templateFileFullPath); - + +import org.apache.log4j.Logger; + +import com.cloud.exception.InternalErrorException; +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.storage.StorageLayer; +import com.cloud.utils.script.Script; + +@Local(value=Processor.class) +public class VmdkProcessor implements Processor { + private static final Logger s_logger = Logger.getLogger(VmdkProcessor.class); + + String _name; + StorageLayer _storage; + + @Override + public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { + if (format != null) { + if(s_logger.isInfoEnabled()) + s_logger.info("We currently don't handle conversion from " + format + " to VMDK."); + return null; + } + + s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); + String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.OVA.getFileExtension(); + if (!_storage.exists(templateFilePath)) { + if(s_logger.isInfoEnabled()) + s_logger.info("Unable to find the vmware template file: " + templateFilePath); + return null; + } + + s_logger.info("Template processing - untar OVA package. templatePath: " + templatePath + ", templateName: " + templateName); + String templateFileFullPath = templatePath + templateName + "." + ImageFormat.OVA.getFileExtension(); + File templateFile = new File(templateFileFullPath); + Script command = new Script("tar", 0, s_logger); command.add("--no-same-owner"); - command.add("-xf", templateFileFullPath); - command.setWorkDir(templateFile.getParent()); - String result = command.execute(); - if (result != null) { - s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); - return null; - } - - FormatInfo info = new FormatInfo(); - info.format = ImageFormat.OVA; - info.filename = templateName + "." + ImageFormat.OVA.getFileExtension(); + command.add("-xf", templateFileFullPath); + command.setWorkDir(templateFile.getParent()); + String result = command.execute(); + if (result != null) { + s_logger.info("failed to untar OVA package due to " + result + ". templatePath: " + templatePath + ", templateName: " + templateName); + return null; + } + + FormatInfo info = new FormatInfo(); + info.format = ImageFormat.OVA; + info.filename = templateName + "." + ImageFormat.OVA.getFileExtension(); info.size = _storage.getSize(templateFilePath); info.virtualSize = getTemplateVirtualSize(templatePath, info.filename); - - // delete original OVA file - // templateFile.delete(); - return info; - } + + // delete original OVA file + // templateFile.delete(); + return info; + } public long getTemplateVirtualSize(String templatePath, String templateName) throws InternalErrorException { // get the virtual size from the OVF file meta data @@ -130,30 +130,30 @@ public class VmdkProcessor implements Processor { } return null; } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; - _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); - if (_storage == null) { - throw new ConfigurationException("Unable to get storage implementation"); - } - - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } -} + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); + if (_storage == null) { + throw new ConfigurationException("Unable to get storage implementation"); + } + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index 1cb2e2ab227..3ecf9b26de3 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - +package com.cloud.user; + import java.util.Date; import java.util.UUID; @@ -26,32 +26,32 @@ import javax.persistence.Table; import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="account") -public class AccountVO implements Account, Identity { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="account_name") - private String accountName = null; - - @Column(name="type") - private short type = ACCOUNT_TYPE_NORMAL; - - @Column(name="domain_id") - private long domainId; - + +@Entity +@Table(name="account") +public class AccountVO implements Account, Identity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="type") + private short type = ACCOUNT_TYPE_NORMAL; + + @Column(name="domain_id") + private long domainId; + @Column(name="state") - @Enumerated(value=EnumType.STRING) - private State state; - - @Column(name=GenericDao.REMOVED_COLUMN) - private Date removed; - - @Column(name="cleanup_needed") + @Enumerated(value=EnumType.STRING) + private State state; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="cleanup_needed") private boolean needsCleanup = false; @Column(name="network_domain") @@ -59,13 +59,13 @@ public class AccountVO implements Account, Identity { @Column(name="uuid") private String uuid; - + public AccountVO() { this.uuid = UUID.randomUUID().toString(); } - - public AccountVO(long id) { - this.id = id; + + public AccountVO(long id) { + this.id = id; this.uuid = UUID.randomUUID().toString(); } @@ -76,60 +76,60 @@ public class AccountVO implements Account, Identity { this.type = type; this.state = State.enabled; this.uuid = UUID.randomUUID().toString(); - } - - public void setNeedsCleanup(boolean value) { - needsCleanup = value; - } - - public boolean getNeedsCleanup() { - return needsCleanup; - } - - @Override - public long getId() { - return id; - } - - @Override - public String getAccountName() { - return accountName; } - - public void setAccountName(String accountName) { - this.accountName = accountName; + + public void setNeedsCleanup(boolean value) { + needsCleanup = value; } - - @Override - public short getType() { - return type; + + public boolean getNeedsCleanup() { + return needsCleanup; } - - public void setType(short type) { - this.type = type; - } - - @Override - public long getDomainId() { - return domainId; - } - - public void setDomainId(long domainId) { - this.domainId = domainId; - } - - @Override - public State getState() { - return state; - } - - public void setState(State state) { - this.state = state; - } @Override - public Date getRemoved() { - return removed; + public long getId() { + return id; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getType() { + return type; + } + + public void setType(short type) { + this.type = type; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + @Override + public Date getRemoved() { + return removed; } @Override @@ -158,5 +158,5 @@ public class AccountVO implements Account, Identity { public void setUuid(String uuid) { this.uuid = uuid; - } -} + } +} diff --git a/core/src/com/cloud/user/UserAccountVO.java b/core/src/com/cloud/user/UserAccountVO.java index 193db3f60b2..4211f62bf4c 100644 --- a/core/src/com/cloud/user/UserAccountVO.java +++ b/core/src/com/cloud/user/UserAccountVO.java @@ -10,64 +10,64 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.Table; - +package com.cloud.user; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + import com.cloud.utils.db.GenericDao; - -@Entity -@Table(name="user") -@SecondaryTable(name="account", - pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) -public class UserAccountVO implements UserAccount { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id = null; - - @Column(name="username") - private String username = null; - - @Column(name="password") - private String password = null; - - @Column(name="firstname") - private String firstname = null; - - @Column(name="lastname") - private String lastname = null; - - @Column(name="account_id") - private long accountId; - - @Column(name="email") - private String email = null; - - @Column(name="state") - private String state; - - @Column(name="api_key") - private String apiKey = null; - - @Column(name="secret_key", encryptable=true) - private String secretKey = null; - - @Column(name=GenericDao.CREATED_COLUMN) - private Date created; - - @Column(name=GenericDao.REMOVED_COLUMN) + +@Entity +@Table(name="user") +@SecondaryTable(name="account", + pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) +public class UserAccountVO implements UserAccount { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id = null; + + @Column(name="username") + private String username = null; + + @Column(name="password") + private String password = null; + + @Column(name="firstname") + private String firstname = null; + + @Column(name="lastname") + private String lastname = null; + + @Column(name="account_id") + private long accountId; + + @Column(name="email") + private String email = null; + + @Column(name="state") + private String state; + + @Column(name="api_key") + private String apiKey = null; + + @Column(name="secret_key", encryptable=true) + private String secretKey = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + @Column(name="timezone") private String timezone; @@ -76,166 +76,166 @@ public class UserAccountVO implements UserAccount { @Column(name="is_registered") boolean registered; - - @Column(name="account_name", table="account", insertable=false, updatable=false) - private String accountName = null; - - @Column(name="type", table="account", insertable=false, updatable=false) - private short type; - - @Column(name="domain_id", table="account", insertable=false, updatable=false) - private Long domainId = null; - - @Column(name="state", table="account", insertable=false, updatable=false) - private String accountState; - - public UserAccountVO() {} - - @Override - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - @Override - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @Override - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public String getFirstname() { - return firstname; - } - - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - @Override - public String getLastname() { - return lastname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - @Override - public long getAccountId() { - return accountId; - } - - public void setAccountId(long accountId) { - this.accountId = accountId; - } - - @Override - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - @Override - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - @Override - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - @Override - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - - @Override - public Date getCreated() { - return created; - } - -// public void setCreated(Date created) { -// this.created = created; -// } - - @Override - public Date getRemoved() { - return removed; - } - - public void setRemoved(Date removed) { - this.removed = removed; - } - - @Override - public String getAccountName() { - return accountName; - } - - public void setAccountName(String accountName) { - this.accountName = accountName; - } - - @Override - public short getType() { - return type; - } - - public void setType(short type) { - this.type = type; - } - - @Override - public Long getDomainId() { - return domainId; - } - - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - - @Override - public String getAccountState() { - return accountState; - } - - public void setAccountDisabled(String accountState) { - this.accountState = accountState; - } + + @Column(name="account_name", table="account", insertable=false, updatable=false) + private String accountName = null; + + @Column(name="type", table="account", insertable=false, updatable=false) + private short type; + + @Column(name="domain_id", table="account", insertable=false, updatable=false) + private Long domainId = null; + + @Column(name="state", table="account", insertable=false, updatable=false) + private String accountState; + + public UserAccountVO() {} + + @Override + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + @Override + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + @Override + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + @Override + public Date getCreated() { + return created; + } + +// public void setCreated(Date created) { +// this.created = created; +// } + + @Override + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getType() { + return type; + } + + public void setType(short type) { + this.type = type; + } + + @Override + public Long getDomainId() { + return domainId; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + @Override + public String getAccountState() { + return accountState; + } + + public void setAccountDisabled(String accountState) { + this.accountState = accountState; + } - @Override + @Override public String getTimezone(){ return timezone; } @@ -262,5 +262,5 @@ public class UserAccountVO implements UserAccount { public void setRegistered(boolean registered) { this.registered = registered; - } + } } \ No newline at end of file diff --git a/core/src/com/cloud/user/UserStatisticsVO.java b/core/src/com/cloud/user/UserStatisticsVO.java index 77e0286915a..d8c36b648a8 100644 --- a/core/src/com/cloud/user/UserStatisticsVO.java +++ b/core/src/com/cloud/user/UserStatisticsVO.java @@ -10,27 +10,27 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="user_statistics") -public class UserStatisticsVO { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private Long id; - - @Column(name="data_center_id", updatable=false) - private long dataCenterId; - - @Column(name="account_id", updatable=false) +package com.cloud.user; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="user_statistics") +public class UserStatisticsVO { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private Long id; + + @Column(name="data_center_id", updatable=false) + private long dataCenterId; + + @Column(name="account_id", updatable=false) private long accountId; @Column(name="public_ip_address") @@ -44,52 +44,52 @@ public class UserStatisticsVO { @Column(name="network_id") private Long networkId; - - - @Column(name="net_bytes_received") - private long netBytesReceived; - - @Column(name="net_bytes_sent") - private long netBytesSent; - - @Column(name="current_bytes_received") - private long currentBytesReceived; - - @Column(name="current_bytes_sent") + + + @Column(name="net_bytes_received") + private long netBytesReceived; + + @Column(name="net_bytes_sent") + private long netBytesSent; + + @Column(name="current_bytes_received") + private long currentBytesReceived; + + @Column(name="current_bytes_sent") private long currentBytesSent; @Column(name="agg_bytes_received") private long aggBytesReceived; @Column(name="agg_bytes_sent") - private long aggBytesSent; - - protected UserStatisticsVO() { - } - - public UserStatisticsVO(long accountId, long dcId, String publicIpAddress, Long deviceId, String deviceType, Long networkId) { + private long aggBytesSent; + + protected UserStatisticsVO() { + } + + public UserStatisticsVO(long accountId, long dcId, String publicIpAddress, Long deviceId, String deviceType, Long networkId) { this.accountId = accountId; this.dataCenterId = dcId; this.publicIpAddress = publicIpAddress; this.deviceId = deviceId; this.deviceType = deviceType; - this.networkId = networkId; - this.netBytesReceived = 0; - this.netBytesSent = 0; - this.currentBytesReceived = 0; + this.networkId = networkId; + this.netBytesReceived = 0; + this.netBytesSent = 0; + this.currentBytesReceived = 0; this.currentBytesSent = 0; - } - - public long getAccountId() { - return accountId; - } - - public Long getId() { - return id; - } - - public long getDataCenterId() { - return dataCenterId; + } + + public long getAccountId() { + return accountId; + } + + public Long getId() { + return id; + } + + public long getDataCenterId() { + return dataCenterId; } public String getPublicIpAddress() { @@ -98,7 +98,7 @@ public class UserStatisticsVO { public Long getDeviceId() { return deviceId; - } + } public String getDeviceType() { return deviceType; @@ -107,37 +107,37 @@ public class UserStatisticsVO { public Long getNetworkId() { return networkId; } - - public long getCurrentBytesReceived() { - return currentBytesReceived; - } - - public void setCurrentBytesReceived(long currentBytesReceived) { - this.currentBytesReceived = currentBytesReceived; - } - - public long getCurrentBytesSent() { - return currentBytesSent; - } - - public void setCurrentBytesSent(long currentBytesSent) { - this.currentBytesSent = currentBytesSent; - } - - public long getNetBytesReceived() { - return netBytesReceived; - } - - public long getNetBytesSent() { - return netBytesSent; - } - - public void setNetBytesReceived(long netBytesReceived) { - this.netBytesReceived = netBytesReceived; - } - - public void setNetBytesSent(long netBytesSent) { - this.netBytesSent = netBytesSent; + + public long getCurrentBytesReceived() { + return currentBytesReceived; + } + + public void setCurrentBytesReceived(long currentBytesReceived) { + this.currentBytesReceived = currentBytesReceived; + } + + public long getCurrentBytesSent() { + return currentBytesSent; + } + + public void setCurrentBytesSent(long currentBytesSent) { + this.currentBytesSent = currentBytesSent; + } + + public long getNetBytesReceived() { + return netBytesReceived; + } + + public long getNetBytesSent() { + return netBytesSent; + } + + public void setNetBytesReceived(long netBytesReceived) { + this.netBytesReceived = netBytesReceived; + } + + public void setNetBytesSent(long netBytesSent) { + this.netBytesSent = netBytesSent; } public long getAggBytesReceived() { @@ -155,5 +155,5 @@ public class UserStatisticsVO { public void setAggBytesSent(long aggBytesSent) { this.aggBytesSent = aggBytesSent; } - -} + +} diff --git a/core/src/com/cloud/user/UserStatsLogVO.java b/core/src/com/cloud/user/UserStatsLogVO.java index 4e78ee7eeba..7bf2076b63b 100644 --- a/core/src/com/cloud/user/UserStatsLogVO.java +++ b/core/src/com/cloud/user/UserStatsLogVO.java @@ -10,41 +10,41 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.user; - +package com.cloud.user; + import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; - -@Entity -@Table(name="op_user_stats_log") -public class UserStatsLogVO { - @Id - @Column(name="user_stats_id") - private long userStatsId; - - @Column(name="net_bytes_received") - private long netBytesReceived; - - @Column(name="net_bytes_sent") - private long netBytesSent; - - @Column(name="current_bytes_received") - private long currentBytesReceived; - - @Column(name="current_bytes_sent") + +@Entity +@Table(name="op_user_stats_log") +public class UserStatsLogVO { + @Id + @Column(name="user_stats_id") + private long userStatsId; + + @Column(name="net_bytes_received") + private long netBytesReceived; + + @Column(name="net_bytes_sent") + private long netBytesSent; + + @Column(name="current_bytes_received") + private long currentBytesReceived; + + @Column(name="current_bytes_sent") private long currentBytesSent; @Column(name="agg_bytes_received") private long aggBytesReceived; @Column(name="agg_bytes_sent") - private long aggBytesSent; + private long aggBytesSent; @Column(name="updated") @Temporal(value=TemporalType.TIMESTAMP) @@ -52,7 +52,7 @@ public class UserStatsLogVO { public UserStatsLogVO(){ } - + public UserStatsLogVO(long userStatsId, long netBytesReceived, long netBytesSent, long currentBytesReceived, long currentBytesSent, long aggBytesReceived, long aggBytesSent, Date updatedTime) { this.userStatsId = userStatsId; @@ -62,43 +62,43 @@ public class UserStatsLogVO { this.currentBytesSent = currentBytesSent; this.aggBytesReceived = aggBytesReceived; this.aggBytesSent = aggBytesSent; - this.updatedTime = updatedTime; - } - - public Long getUserStatsId() { - return userStatsId; - } + this.updatedTime = updatedTime; + } + + public Long getUserStatsId() { + return userStatsId; + } - public long getCurrentBytesReceived() { - return currentBytesReceived; - } - - public void setCurrentBytesReceived(long currentBytesReceived) { - this.currentBytesReceived = currentBytesReceived; - } - - public long getCurrentBytesSent() { - return currentBytesSent; - } - - public void setCurrentBytesSent(long currentBytesSent) { - this.currentBytesSent = currentBytesSent; - } - - public long getNetBytesReceived() { - return netBytesReceived; - } - - public long getNetBytesSent() { - return netBytesSent; - } - - public void setNetBytesReceived(long netBytesReceived) { - this.netBytesReceived = netBytesReceived; - } - - public void setNetBytesSent(long netBytesSent) { - this.netBytesSent = netBytesSent; + public long getCurrentBytesReceived() { + return currentBytesReceived; + } + + public void setCurrentBytesReceived(long currentBytesReceived) { + this.currentBytesReceived = currentBytesReceived; + } + + public long getCurrentBytesSent() { + return currentBytesSent; + } + + public void setCurrentBytesSent(long currentBytesSent) { + this.currentBytesSent = currentBytesSent; + } + + public long getNetBytesReceived() { + return netBytesReceived; + } + + public long getNetBytesSent() { + return netBytesSent; + } + + public void setNetBytesReceived(long netBytesReceived) { + this.netBytesReceived = netBytesReceived; + } + + public void setNetBytesSent(long netBytesSent) { + this.netBytesSent = netBytesSent; } public long getAggBytesReceived() { @@ -124,5 +124,5 @@ public class UserStatsLogVO { public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } - -} + +} diff --git a/core/src/com/cloud/vm/ConsoleProxy.java b/core/src/com/cloud/vm/ConsoleProxy.java index 2a3d246a5bd..9f2847a2392 100644 --- a/core/src/com/cloud/vm/ConsoleProxy.java +++ b/core/src/com/cloud/vm/ConsoleProxy.java @@ -10,14 +10,14 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm; - -/** - * ConsoleProxy is a system VM instance that is used - * to proxy VNC traffic - */ +package com.cloud.vm; + +/** + * ConsoleProxy is a system VM instance that is used + * to proxy VNC traffic + */ public interface ConsoleProxy extends SystemVm { public int getActiveSession(); - public byte[] getSessionDetails(); -} - + public byte[] getSessionDetails(); +} + diff --git a/core/src/com/cloud/vm/SecondaryStorageVm.java b/core/src/com/cloud/vm/SecondaryStorageVm.java index 554f61632d5..ba69f4ff8f8 100644 --- a/core/src/com/cloud/vm/SecondaryStorageVm.java +++ b/core/src/com/cloud/vm/SecondaryStorageVm.java @@ -10,13 +10,13 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm; - -/** - * Secondary Storage VM is a system VM instance that is used - * to interface the management server to secondary storage - */ +package com.cloud.vm; + +/** + * Secondary Storage VM is a system VM instance that is used + * to interface the management server to secondary storage + */ public interface SecondaryStorageVm extends SystemVm { - enum Role { templateProcessor, commandExecutor } -} - + enum Role { templateProcessor, commandExecutor } +} + diff --git a/core/src/com/cloud/vm/VMInstanceVO.java b/core/src/com/cloud/vm/VMInstanceVO.java index f9c57f5931e..8346719826d 100644 --- a/core/src/com/cloud/vm/VMInstanceVO.java +++ b/core/src/com/cloud/vm/VMInstanceVO.java @@ -10,8 +10,8 @@ // limitations under the License. // // Automatically generated by addcopyright.py at 04/03/2012 -package com.cloud.vm; - +package com.cloud.vm; + import java.util.Date; import java.util.Map; import java.util.Random; @@ -37,20 +37,20 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; import com.cloud.utils.fsm.FiniteStateObject; import com.cloud.vm.VirtualMachine.State; - -@Entity -@Table(name="vm_instance") -@Inheritance(strategy=InheritanceType.JOINED) -@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) + +@Entity +@Table(name="vm_instance") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) public class VMInstanceVO implements VirtualMachine, FiniteStateObject { - @Id - @TableGenerator(name="vm_instance_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_instance_seq", allocationSize=1) - @Column(name="id", updatable=false, nullable = false) - protected long id; - - @Column(name="name", updatable=false, nullable=false, length=255) - protected String hostName = null; - + @Id + @TableGenerator(name="vm_instance_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_instance_seq", allocationSize=1) + @Column(name="id", updatable=false, nullable = false) + protected long id; + + @Column(name="name", updatable=false, nullable=false, length=255) + protected String hostName = null; + @Column(name="vnc_password", updatable=true, nullable=false, length=255, encryptable=true) protected String vncPassword; @@ -60,65 +60,65 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject