diff --git a/LICENSE b/LICENSE index afb662a77e2..714f6847ae8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012 The Apache Software Foundation +Copyright (c) 2013 The Apache Software Foundation Apache License diff --git a/agent/pom.xml b/agent/pom.xml index 8aab8dec706..810f33fc572 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -55,6 +55,57 @@ + + maven-antrun-plugin + 1.7 + + + generate-resource + generate-resources + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/api/src/com/cloud/agent/api/AgentControlAnswer.java b/api/src/com/cloud/agent/api/AgentControlAnswer.java index 1cdcc1e8322..7dbf7b509eb 100644 --- a/api/src/com/cloud/agent/api/AgentControlAnswer.java +++ b/api/src/com/cloud/agent/api/AgentControlAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class AgentControlAnswer extends Answer { public AgentControlAnswer() { } - + public AgentControlAnswer(Command command) { super(command); } - + public AgentControlAnswer(Command command, boolean success, String details) { super(command, success, details); } diff --git a/api/src/com/cloud/agent/api/AgentControlCommand.java b/api/src/com/cloud/agent/api/AgentControlCommand.java index 6cc8e6fde9b..da187ac4ca8 100644 --- a/api/src/com/cloud/agent/api/AgentControlCommand.java +++ b/api/src/com/cloud/agent/api/AgentControlCommand.java @@ -17,10 +17,10 @@ package com.cloud.agent.api; public class AgentControlCommand extends Command { - + public AgentControlCommand() { } - + public boolean executeInSequence() { return false; } diff --git a/api/src/com/cloud/agent/api/Answer.java b/api/src/com/cloud/agent/api/Answer.java index 932da233a05..655f4470097 100755 --- a/api/src/com/cloud/agent/api/Answer.java +++ b/api/src/com/cloud/agent/api/Answer.java @@ -21,40 +21,40 @@ import com.cloud.utils.exception.ExceptionUtil; public class Answer extends Command { protected boolean result; protected String details; - + protected Answer() { } - + public Answer(Command command) { this(command, true, null); } - + public Answer(Command command, boolean success, String details) { result = success; this.details = details; } - + public Answer(Command command, Exception e) { this(command, false, ExceptionUtil.toString(e)); } - + public boolean getResult() { return result; } - + public String getDetails() { return details; } - + @Override public boolean executeInSequence() { return false; } - + public static UnsupportedAnswer createUnsupportedCommandAnswer(Command cmd) { return new UnsupportedAnswer(cmd, "Unsupported command issued:" + cmd.toString() + ". Are you sure you got the right type of server?"); } - + public static UnsupportedAnswer createUnsupportedVersionAnswer(Command cmd) { return new UnsupportedAnswer(cmd, "Unsuppored Version."); } diff --git a/api/src/com/cloud/agent/api/AttachIsoCommand.java b/api/src/com/cloud/agent/api/AttachIsoCommand.java index ff9da83669e..c6f0b6124b7 100644 --- a/api/src/com/cloud/agent/api/AttachIsoCommand.java +++ b/api/src/com/cloud/agent/api/AttachIsoCommand.java @@ -48,11 +48,11 @@ public class AttachIsoCommand extends Command { public boolean isAttach() { return attach; } - + public String getStoreUrl() { return storeUrl; } - + public void setStoreUrl(String url) { storeUrl = url; } diff --git a/api/src/com/cloud/agent/api/AttachVolumeAnswer.java b/api/src/com/cloud/agent/api/AttachVolumeAnswer.java index 253b4445667..b377b7c1386 100644 --- a/api/src/com/cloud/agent/api/AttachVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/AttachVolumeAnswer.java @@ -20,38 +20,38 @@ package com.cloud.agent.api; public class AttachVolumeAnswer extends Answer { private Long deviceId; private String chainInfo; - + protected AttachVolumeAnswer() { - + } - + public AttachVolumeAnswer(AttachVolumeCommand cmd, String result) { super(cmd, false, result); this.deviceId = null; } - + public AttachVolumeAnswer(AttachVolumeCommand cmd, Long deviceId) { super(cmd); this.deviceId = deviceId; } - + public AttachVolumeAnswer(AttachVolumeCommand cmd) { super(cmd); this.deviceId = null; } - + /** * @return the deviceId */ public Long getDeviceId() { return deviceId; } - + public void setChainInfo(String chainInfo) { this.chainInfo = chainInfo; } - + public String getChainInfo() { return chainInfo; } diff --git a/api/src/com/cloud/agent/api/AttachVolumeCommand.java b/api/src/com/cloud/agent/api/AttachVolumeCommand.java index 98bfb2e485e..302b8f80af3 100644 --- a/api/src/com/cloud/agent/api/AttachVolumeCommand.java +++ b/api/src/com/cloud/agent/api/AttachVolumeCommand.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.storage.Storage.StoragePoolType; public class AttachVolumeCommand extends Command { - + boolean attach; String vmName; StoragePoolType pooltype; @@ -29,10 +29,10 @@ public class AttachVolumeCommand extends Command { String volumeName; Long deviceId; String chainInfo; - + protected AttachVolumeCommand() { } - + public AttachVolumeCommand(boolean attach, String vmName, StoragePoolType pooltype, String volumeFolder, String volumePath, String volumeName, Long deviceId, String chainInfo) { this.attach = attach; this.vmName = vmName; @@ -43,20 +43,20 @@ public class AttachVolumeCommand extends Command { this.deviceId = deviceId; this.chainInfo = chainInfo; } - + @Override public boolean executeInSequence() { return true; } - + public boolean getAttach() { return attach; } - + public String getVmName() { return vmName; } - + public StoragePoolType getPooltype() { return pooltype; } @@ -68,11 +68,11 @@ public class AttachVolumeCommand extends Command { public String getVolumeFolder() { return volumeFolder; } - + public String getVolumePath() { return volumePath; } - + public String getVolumeName() { return volumeName; } @@ -84,15 +84,15 @@ public class AttachVolumeCommand extends Command { public void setDeviceId(Long deviceId) { this.deviceId = deviceId; } - + public String getPoolUuid() { return poolUuid; } - + public void setPoolUuid(String poolUuid) { this.poolUuid = poolUuid; } - + public String getChainInfo() { return chainInfo; } diff --git a/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java b/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java index 707092fff07..9e35db66f57 100644 --- a/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java @@ -20,11 +20,11 @@ package com.cloud.agent.api; public class BackupSnapshotAnswer extends Answer { private String backupSnapshotName; private boolean full; - + protected BackupSnapshotAnswer() { - + } - + public BackupSnapshotAnswer(BackupSnapshotCommand cmd, boolean success, String result, String backupSnapshotName, boolean full) { super(cmd, success, result); this.backupSnapshotName = backupSnapshotName; @@ -37,7 +37,7 @@ public class BackupSnapshotAnswer extends Answer { public String getBackupSnapshotName() { return backupSnapshotName; } - + public boolean isFull() { return full; } diff --git a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java index 7ea78356837..a0ac8d7ad71 100644 --- a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java @@ -23,7 +23,7 @@ import com.cloud.agent.api.to.SwiftTO; import com.cloud.storage.StoragePool; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class BackupSnapshotCommand extends SnapshotCommand { private String prevSnapshotUuid; @@ -37,18 +37,18 @@ public class BackupSnapshotCommand extends SnapshotCommand { StorageFilerTO pool; protected BackupSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The UUID of the primary storage Pool * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * @param snapshotUuid The UUID of the snapshot which is going to be backed up * @param prevSnapshotUuid The UUID of the previous snapshot for this volume. This will be destroyed on the primary storage. * @param prevBackupUuid This is the UUID of the vhd file which was last backed up on secondary storage. - * @param firstBackupUuid This is the backup of the first ever snapshot taken by the volume. + * @param firstBackupUuid This is the backup of the first ever snapshot taken by the volume. * @param isFirstSnapshotOfRootVolume true if this is the first snapshot of a root volume. Set the parent of the backup to null. - * @param isVolumeInactive True if the volume belongs to a VM that is not running or is detached. + * @param isVolumeInactive True if the volume belongs to a VM that is not running or is detached. */ public BackupSnapshotCommand(String secondaryStoragePoolURL, Long dcId, @@ -63,7 +63,7 @@ public class BackupSnapshotCommand extends SnapshotCommand { String prevBackupUuid, boolean isVolumeInactive, String vmName, - int wait) + int wait) { super(pool, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId); this.snapshotId = snapshotId; @@ -82,11 +82,11 @@ public class BackupSnapshotCommand extends SnapshotCommand { public String getPrevBackupUuid() { return prevBackupUuid; } - + public boolean isVolumeInactive() { return isVolumeInactive; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/CancelCommand.java b/api/src/com/cloud/agent/api/CancelCommand.java index 76382736148..0692055ae5a 100644 --- a/api/src/com/cloud/agent/api/CancelCommand.java +++ b/api/src/com/cloud/agent/api/CancelCommand.java @@ -21,19 +21,19 @@ package com.cloud.agent.api; public class CancelCommand extends Command { protected long sequence; protected String reason; - + protected CancelCommand() { } - + public CancelCommand(long sequence, String reason) { this.sequence = sequence; this.reason = reason; } - + public long getSequence() { return sequence; } - + public String getReason() { return reason; } diff --git a/api/src/com/cloud/agent/api/ChangeAgentAnswer.java b/api/src/com/cloud/agent/api/ChangeAgentAnswer.java index 4b3f103a8e2..537eabef2b0 100644 --- a/api/src/com/cloud/agent/api/ChangeAgentAnswer.java +++ b/api/src/com/cloud/agent/api/ChangeAgentAnswer.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; public class ChangeAgentAnswer extends Answer { protected ChangeAgentAnswer() { } - + public ChangeAgentAnswer(ChangeAgentCommand cmd, boolean result) { super(cmd, result, null); } diff --git a/api/src/com/cloud/agent/api/ChangeAgentCommand.java b/api/src/com/cloud/agent/api/ChangeAgentCommand.java index 1b7f8c8507c..abdb60a619e 100644 --- a/api/src/com/cloud/agent/api/ChangeAgentCommand.java +++ b/api/src/com/cloud/agent/api/ChangeAgentCommand.java @@ -21,19 +21,19 @@ import com.cloud.host.Status.Event; public class ChangeAgentCommand extends Command { long agentId; Event event; - + protected ChangeAgentCommand() { } - + public ChangeAgentCommand(long agentId, Event event) { this.agentId = agentId; this.event = event; } - + public long getAgentId() { return agentId; } - + public Event getEvent() { return event; } diff --git a/api/src/com/cloud/agent/api/CheckHealthCommand.java b/api/src/com/cloud/agent/api/CheckHealthCommand.java index 5298f5a76c8..ff4227678a9 100644 --- a/api/src/com/cloud/agent/api/CheckHealthCommand.java +++ b/api/src/com/cloud/agent/api/CheckHealthCommand.java @@ -22,7 +22,7 @@ public class CheckHealthCommand extends Command { setWait(50); } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/CheckNetworkAnswer.java b/api/src/com/cloud/agent/api/CheckNetworkAnswer.java index 2188fa632d9..52825fd1140 100644 --- a/api/src/com/cloud/agent/api/CheckNetworkAnswer.java +++ b/api/src/com/cloud/agent/api/CheckNetworkAnswer.java @@ -20,7 +20,7 @@ public class CheckNetworkAnswer extends Answer { // indicate if agent reconnect is needed after setupNetworkNames command private boolean _reconnect; public CheckNetworkAnswer() {} - + public CheckNetworkAnswer(CheckNetworkCommand cmd, boolean result, String details, boolean reconnect) { super(cmd, result, details); @@ -34,5 +34,5 @@ public class CheckNetworkAnswer extends Answer { public boolean needReconnect() { return _reconnect; } - + } diff --git a/api/src/com/cloud/agent/api/CheckOnHostAnswer.java b/api/src/com/cloud/agent/api/CheckOnHostAnswer.java index 2a053fdad1b..e5325e3e9dd 100644 --- a/api/src/com/cloud/agent/api/CheckOnHostAnswer.java +++ b/api/src/com/cloud/agent/api/CheckOnHostAnswer.java @@ -19,10 +19,10 @@ package com.cloud.agent.api; public class CheckOnHostAnswer extends Answer { boolean determined; boolean alive; - + protected CheckOnHostAnswer() { } - + public CheckOnHostAnswer(CheckOnHostCommand cmd, Boolean alive, String details) { super(cmd, true, details); if (alive == null) { @@ -32,7 +32,7 @@ public class CheckOnHostAnswer extends Answer { this.alive = alive; } } - + public CheckOnHostAnswer(CheckOnHostCommand cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/CheckOnHostCommand.java b/api/src/com/cloud/agent/api/CheckOnHostCommand.java index 3aadebd464d..596a53299a8 100644 --- a/api/src/com/cloud/agent/api/CheckOnHostCommand.java +++ b/api/src/com/cloud/agent/api/CheckOnHostCommand.java @@ -24,17 +24,17 @@ public class CheckOnHostCommand extends Command { protected CheckOnHostCommand() { } - - + + public CheckOnHostCommand(Host host) { this.host = new HostTO(host); setWait(20); } - + public HostTO getHost() { return host; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/CheckRouterAnswer.java b/api/src/com/cloud/agent/api/CheckRouterAnswer.java index 7240ba10cd5..da8189f552b 100644 --- a/api/src/com/cloud/agent/api/CheckRouterAnswer.java +++ b/api/src/com/cloud/agent/api/CheckRouterAnswer.java @@ -23,10 +23,10 @@ public class CheckRouterAnswer extends Answer { public static final String ROUTER_IP = "router.ip"; RedundantState state; boolean isBumped; - + protected CheckRouterAnswer() { } - + public CheckRouterAnswer(CheckRouterCommand cmd, String details, boolean parse) { super(cmd, true, details); if (parse) { @@ -35,7 +35,7 @@ public class CheckRouterAnswer extends Answer { } } } - + public CheckRouterAnswer(CheckRouterCommand cmd, String details) { super(cmd, false, details); } @@ -61,11 +61,11 @@ public class CheckRouterAnswer extends Answer { } return true; } - + public void setState(RedundantState state) { this.state = state; } - + public RedundantState getState() { return state; } @@ -73,9 +73,9 @@ public class CheckRouterAnswer extends Answer { public boolean isBumped() { return isBumped; } - + public void setIsBumped(boolean isBumped) { this.isBumped = isBumped; } - + } diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java index ef3be811870..0e9db96fb36 100644 --- a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -23,12 +23,12 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { Map ipToConnected; Map ipToDetail; String details; - + protected CheckS2SVpnConnectionsAnswer() { ipToConnected = new HashMap(); ipToDetail = new HashMap(); } - + public CheckS2SVpnConnectionsAnswer(CheckS2SVpnConnectionsCommand cmd, boolean result, String details) { super(cmd, result, details); ipToConnected = new HashMap(); @@ -38,7 +38,7 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { parseDetails(details); } } - + protected void parseDetails(String details) { String[] lines = details.split("&"); for (String line : lines) { @@ -54,14 +54,14 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { ipToDetail.put(ip, detail); } } - + public boolean isConnected(String ip) { if (this.getResult()) { return ipToConnected.get(ip); } return false; } - + public String getDetail(String ip) { if (this.getResult()) { return ipToDetail.get(ip); diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java index a736eab35ea..9cfb53b0828 100644 --- a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -22,17 +22,17 @@ import com.cloud.agent.api.routing.NetworkElementCommand; public class CheckS2SVpnConnectionsCommand extends NetworkElementCommand { List vpnIps; - + @Override public boolean executeInSequence() { return true; } - + public CheckS2SVpnConnectionsCommand(List vpnIps) { super(); this.vpnIps = vpnIps; } - + public List getVpnIps() { return vpnIps; } diff --git a/api/src/com/cloud/agent/api/CheckStateAnswer.java b/api/src/com/cloud/agent/api/CheckStateAnswer.java index 4864e390201..bf8ae0f330c 100755 --- a/api/src/com/cloud/agent/api/CheckStateAnswer.java +++ b/api/src/com/cloud/agent/api/CheckStateAnswer.java @@ -28,17 +28,17 @@ public class CheckStateAnswer extends Answer { public CheckStateAnswer(CheckStateCommand cmd, State state) { this(cmd, state, null); } - + public CheckStateAnswer(CheckStateCommand cmd, String details) { super(cmd, false, details); this.state = null; } - + public CheckStateAnswer(CheckStateCommand cmd, State state, String details) { super(cmd, true, details); this.state = state; } - + public State getState() { return state; } diff --git a/api/src/com/cloud/agent/api/CheckStateCommand.java b/api/src/com/cloud/agent/api/CheckStateCommand.java index 31c341db448..89fc7731f01 100755 --- a/api/src/com/cloud/agent/api/CheckStateCommand.java +++ b/api/src/com/cloud/agent/api/CheckStateCommand.java @@ -17,7 +17,7 @@ package com.cloud.agent.api; /** - * + * * */ public class CheckStateCommand extends Command { @@ -28,12 +28,12 @@ public class CheckStateCommand extends Command { public CheckStateCommand(String vmName) { this.vmName = vmName; } - + @Override public boolean executeInSequence() { return true; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java b/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java index 555b0ff79ed..3f0ffdbcea1 100644 --- a/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java +++ b/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java @@ -19,33 +19,33 @@ package com.cloud.agent.api; import com.cloud.vm.VirtualMachine.State; public class CheckVirtualMachineAnswer extends Answer { - + Integer vncPort; State state; - - + + protected CheckVirtualMachineAnswer() { } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, State state, Integer vncPort, String detail) { super(cmd, true, detail); this.state = state; this.vncPort = vncPort; } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, State state, Integer vncPort) { this(cmd, state, vncPort, null); } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, String detail) { super(cmd, false, detail); } - + public Integer getVncPort() { return vncPort; } - + public State getState() { return state; } diff --git a/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java b/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java index 9e63a935af1..62f4420a586 100644 --- a/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java +++ b/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java @@ -17,18 +17,18 @@ package com.cloud.agent.api; public class CheckVirtualMachineCommand extends Command { - + private String vmName; - + protected CheckVirtualMachineCommand() { - + } - + public CheckVirtualMachineCommand(String vmName) { this.vmName = vmName; setWait(20); } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java b/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java index 6302443b011..8b5172dfe2d 100644 --- a/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java +++ b/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java @@ -20,22 +20,22 @@ package com.cloud.agent.api; public class CleanupNetworkRulesCmd extends Command implements CronCommand { private int interval = 10*60; - + @Override public boolean executeInSequence() { return false; } - - + + public CleanupNetworkRulesCmd(int intervalSecs) { super(); interval = intervalSecs; } - + public CleanupNetworkRulesCmd() { - + } diff --git a/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java b/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java index aa85c3d2ec7..ae65a529c52 100644 --- a/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java +++ b/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java @@ -26,20 +26,20 @@ public class CleanupSnapshotBackupCommand extends Command { private List validBackupUUIDs; protected CleanupSnapshotBackupCommand() { - + } - - /* - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + + /* + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field - * If you have better ideas on how to get it, you are welcome. - * @param validBackupUUID The VHD which are valid + * If you have better ideas on how to get it, you are welcome. + * @param validBackupUUID The VHD which are valid */ public CleanupSnapshotBackupCommand(String secondaryStoragePoolURL, Long dcId, Long accountId, Long volumeId, - List validBackupUUIDs) + List validBackupUUIDs) { this.secondaryStoragePoolURL = secondaryStoragePoolURL; this.dcId = dcId; @@ -67,9 +67,9 @@ public class CleanupSnapshotBackupCommand extends Command { public List getValidBackupUUIDs() { return validBackupUUIDs; } - + @Override public boolean executeInSequence() { return false; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/ClusterSyncAnswer.java b/api/src/com/cloud/agent/api/ClusterSyncAnswer.java index ea83109fbcb..99fee2a9dd1 100644 --- a/api/src/com/cloud/agent/api/ClusterSyncAnswer.java +++ b/api/src/com/cloud/agent/api/ClusterSyncAnswer.java @@ -25,31 +25,31 @@ public class ClusterSyncAnswer extends Answer { private long _clusterId; private HashMap> _newStates; private boolean _isExecuted=false; - + // this is here because a cron command answer is being sent twice // AgentAttache.processAnswers // AgentManagerImpl.notifyAnswersToMonitors public boolean isExceuted(){ return _isExecuted; } - + public void setExecuted(){ _isExecuted = true; } - + public ClusterSyncAnswer(long clusterId, HashMap> newStates){ _clusterId = clusterId; _newStates = newStates; result = true; } - + public long getClusterId() { return _clusterId; } - + public HashMap> getNewStates() { return _newStates; - } + } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/ClusterSyncCommand.java b/api/src/com/cloud/agent/api/ClusterSyncCommand.java index e3a0da57669..17dbbd8dd7b 100644 --- a/api/src/com/cloud/agent/api/ClusterSyncCommand.java +++ b/api/src/com/cloud/agent/api/ClusterSyncCommand.java @@ -21,10 +21,10 @@ public class ClusterSyncCommand extends Command implements CronCommand { int _interval; long _clusterId; - + public ClusterSyncCommand() { } - + public ClusterSyncCommand(int interval, long clusterId){ _interval = interval; _clusterId = clusterId; @@ -34,7 +34,7 @@ public class ClusterSyncCommand extends Command implements CronCommand { public int getInterval() { return _interval; } - + public long getClusterId() { return _clusterId; } @@ -43,5 +43,5 @@ public class ClusterSyncCommand extends Command implements CronCommand { public boolean executeInSequence() { return false; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/Command.java b/api/src/com/cloud/agent/api/Command.java index 4c3810ef2dd..9cd67495e04 100755 --- a/api/src/com/cloud/agent/api/Command.java +++ b/api/src/com/cloud/agent/api/Command.java @@ -23,9 +23,9 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; /** * implemented by classes that extends the Command class. Command specifies - * + * */ -public abstract class Command { +public abstract class Command { // allow command to carry over hypervisor or other environment related context info @LogLevel(Log4jLevel.Trace) @@ -63,7 +63,7 @@ public abstract class Command { public String getContextParam(String name) { return contextMap.get(name); } - + public boolean allowCaching() { return true; } diff --git a/api/src/com/cloud/agent/api/ComputeChecksumCommand.java b/api/src/com/cloud/agent/api/ComputeChecksumCommand.java index f0771a89de4..a2c88c440a8 100755 --- a/api/src/com/cloud/agent/api/ComputeChecksumCommand.java +++ b/api/src/com/cloud/agent/api/ComputeChecksumCommand.java @@ -26,12 +26,12 @@ public class ComputeChecksumCommand extends ssCommand { public ComputeChecksumCommand() { super(); } - + public ComputeChecksumCommand(String secUrl, String templatePath) { super(secUrl); this.templatePath = templatePath; - } - + } + public String getTemplatePath() { return templatePath; } diff --git a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java index 53a975f4874..9f50a2f3b53 100644 --- a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java +++ b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java @@ -14,75 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api; - -public class ConsoleAccessAuthenticationAnswer extends AgentControlAnswer { - +package com.cloud.agent.api; + +public class ConsoleAccessAuthenticationAnswer extends AgentControlAnswer { + private boolean _success; - + private boolean _isReauthenticating; private String _host; private int _port; - + private String _tunnelUrl; private String _tunnelSession; - + public ConsoleAccessAuthenticationAnswer() { _success = false; _isReauthenticating = false; - _port = 0; - } - - public ConsoleAccessAuthenticationAnswer(Command cmd, boolean success) { - super(cmd); - _success = success; - } - - public boolean succeeded() { - return _success; + _port = 0; } - + + public ConsoleAccessAuthenticationAnswer(Command cmd, boolean success) { + super(cmd); + _success = success; + } + + public boolean succeeded() { + return _success; + } + public void setSuccess(boolean value) { _success = value; } - + public boolean isReauthenticating() { return _isReauthenticating; } - + public void setReauthenticating(boolean value) { _isReauthenticating = value; } - + public String getHost() { return _host; } - + public void setHost(String host) { _host = host; } - + public int getPort() { return _port; } - + public void setPort(int port) { _port = port; } - + public String getTunnelUrl() { return _tunnelUrl; } - + public void setTunnelUrl(String tunnelUrl) { - _tunnelUrl = tunnelUrl; + _tunnelUrl = tunnelUrl; } - + public String getTunnelSession() { return _tunnelSession; } - + public void setTunnelSession(String tunnelSession) { _tunnelSession = tunnelSession; - } -} + } +} diff --git a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java index acbc181c5b1..bd8093c7e7b 100644 --- a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java +++ b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java @@ -17,19 +17,19 @@ package com.cloud.agent.api; public class ConsoleAccessAuthenticationCommand extends AgentControlCommand { - + private String _host; private String _port; private String _vmId; private String _sid; private String _ticket; - - private boolean _isReauthenticating; - + + private boolean _isReauthenticating; + public ConsoleAccessAuthenticationCommand() { - _isReauthenticating = false; - } - + _isReauthenticating = false; + } + public ConsoleAccessAuthenticationCommand(String host, String port, String vmId, String sid, String ticket) { _host = host; _port = port; @@ -37,32 +37,32 @@ public class ConsoleAccessAuthenticationCommand extends AgentControlCommand { _sid = sid; _ticket = ticket; } - + public String getHost() { return _host; } - + public String getPort() { return _port; } - + public String getVmId() { return _vmId; } - + public String getSid() { return _sid; } - + public String getTicket() { return _ticket; } - + public boolean isReauthenticating() { return _isReauthenticating; } - + public void setReauthenticating(boolean value) { _isReauthenticating = value; - } -} + } +} diff --git a/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java b/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java index d4b101ae0d1..ebb06b64dc6 100644 --- a/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java +++ b/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java @@ -17,22 +17,22 @@ package com.cloud.agent.api; public class ConsoleProxyLoadReportCommand extends AgentControlCommand { - + private long _proxyVmId; private String _loadInfo; - + public ConsoleProxyLoadReportCommand() { } - + public ConsoleProxyLoadReportCommand(long proxyVmId, String loadInfo) { _proxyVmId = proxyVmId; _loadInfo = loadInfo; } - + public long getProxyVmId() { return _proxyVmId; } - + public String getLoadInfo() { return _loadInfo; } diff --git a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java index 0140a4e0a65..9e2680e49e6 100644 --- a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java @@ -19,28 +19,28 @@ package com.cloud.agent.api; import com.cloud.storage.StoragePool; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { private String origTemplateInstallPath; private Long newTemplateId; private String templateName; - + protected CreatePrivateTemplateFromSnapshotCommand() { - + } - + /** * Given the UUID of a backed up snapshot VHD file on the secondary storage, the execute of this command does * 1) Get the parent chain of this VHD all the way up to the root, say VHDList * 2) Copy all the files in the VHDlist to some temp location * 3) Coalesce all the VHDs to one VHD which contains all the data of the volume. This invokes the DeletePreviousBackupCommand for each VHD * 4) Rename the UUID of this VHD - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field * If you have better ideas on how to get it, you are welcome. * It may not be the UUID of the base copy of the snapshot, if no data was written since last snapshot. - * @param origTemplateInstallPath The install path of the original template VHD on the secondary + * @param origTemplateInstallPath The install path of the original template VHD on the secondary */ public CreatePrivateTemplateFromSnapshotCommand(StoragePool pool, @@ -53,7 +53,7 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { String origTemplateInstallPath, Long newTemplateId, String templateName, - int wait) + int wait) { super(pool, secondaryStoragePoolURL, backedUpSnapshotUuid, backedUpSnapshotName, dcId, accountId, volumeId); this.origTemplateInstallPath = origTemplateInstallPath; @@ -68,7 +68,7 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { public String getOrigTemplateInstallPath() { return origTemplateInstallPath; } - + public Long getNewTemplateId() { return newTemplateId; } diff --git a/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java b/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java index ecba6c232e2..7a4d768e5cb 100644 --- a/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java @@ -20,10 +20,10 @@ import com.cloud.storage.StoragePool; public class CreateStoragePoolCommand extends ModifyStoragePoolCommand { - + public CreateStoragePoolCommand() { } - + public CreateStoragePoolCommand(boolean add, StoragePool pool) { super(add, pool); } diff --git a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java index a57d6fa3c50..2f7cd9446e8 100644 --- a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class CreateVolumeFromSnapshotAnswer extends Answer { private String vdiUUID; - + protected CreateVolumeFromSnapshotAnswer() { - + } - + public CreateVolumeFromSnapshotAnswer(CreateVolumeFromSnapshotCommand cmd, boolean success, String result, String vdiUUID) { super(cmd, success, result); this.vdiUUID = vdiUUID; diff --git a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java index 9bc9b36ae0c..a19d34436f7 100644 --- a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java @@ -19,14 +19,14 @@ package com.cloud.agent.api; import com.cloud.storage.StoragePool; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { - + protected CreateVolumeFromSnapshotCommand() { - + } - + /** * Given the UUID of a backed up snapshot VHD file on the secondary storage, the execute of this command does * 1) Get the parent chain of this VHD all the way up to the root, say VHDList @@ -35,11 +35,11 @@ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { * 4) Rename the UUID of this VHD * 5) Move this VHD to primary storage * @param primaryStoragePoolNameLabel The primary storage Pool - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field * If you have better ideas on how to get it, you are welcome. * It may not be the UUID of the base copy of the snapshot, if no data was written since last snapshot. - * @param templatePath The install path of the template VHD on the secondary, if this a root volume + * @param templatePath The install path of the template VHD on the secondary, if this a root volume */ public CreateVolumeFromSnapshotCommand(StoragePool pool, diff --git a/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java b/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java index 01de89163a8..3d62c507b89 100644 --- a/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java +++ b/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class DeleteObjectFromSwiftCommand extends Command { @@ -31,9 +31,9 @@ public class DeleteObjectFromSwiftCommand extends Command { private String object; protected DeleteObjectFromSwiftCommand() { - + } - + public DeleteObjectFromSwiftCommand(SwiftTO swift, String container, String object) { this.swift = swift; this.container = container; @@ -58,4 +58,4 @@ public class DeleteObjectFromSwiftCommand extends Command { return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java b/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java index b458aa0edb0..9a895d8471a 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java @@ -18,15 +18,15 @@ package com.cloud.agent.api; public class DeleteSnapshotBackupAnswer extends Answer { - + protected DeleteSnapshotBackupAnswer() { - + } public DeleteSnapshotBackupAnswer(DeleteSnapshotBackupCommand cmd, boolean success, String details) { super(cmd, success, details); } - - - + + + } diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java index 5e5557002e6..6114148954f 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java @@ -22,7 +22,7 @@ import com.cloud.agent.api.to.SwiftTO; /** * This command encapsulates a primitive operation which enables coalescing the backed up VHD snapshots on the secondary server - * This currently assumes that the secondary storage are mounted on the XenServer. + * This currently assumes that the secondary storage are mounted on the XenServer. */ public class DeleteSnapshotBackupCommand extends SnapshotCommand { @LogLevel(Log4jLevel.Off) @@ -52,31 +52,31 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { protected DeleteSnapshotBackupCommand() { } - + /** * Given 2 VHD files on the secondary storage which are linked in a parent chain as follows: * backupUUID = parent(childUUID) - * It gets another VHD + * It gets another VHD * previousBackupVHD = parent(backupUUID) - * + * * And * 1) it coalesces backupUuid into its parent. * 2) It deletes the VHD file corresponding to backupUuid * 3) It sets the parent VHD of childUUID to that of previousBackupUuid - * + * * It takes care of the cases when * 1) childUUID is null. - Step 3 is not done. - * 2) previousBackupUUID is null + * 2) previousBackupUUID is null * - Merge childUUID into its parent backupUUID * - Set the UUID of the resultant VHD to childUUID - * - Essentially we are deleting the oldest VHD file and setting the current oldest VHD to childUUID - * - * @param volumeName The name of the volume whose snapshot was taken (something like i-3-SV-ROOT) - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * - Essentially we are deleting the oldest VHD file and setting the current oldest VHD to childUUID + * + * @param volumeName The name of the volume whose snapshot was taken (something like i-3-SV-ROOT) + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field - * If you have better ideas on how to get it, you are welcome. - * @param backupUUID The VHD which has to be deleted - * @param childUUID The child VHD file of the backup whose parent is reset to its grandparent. + * If you have better ideas on how to get it, you are welcome. + * @param backupUUID The VHD which has to be deleted + * @param childUUID The child VHD file of the backup whose parent is reset to its grandparent. */ public DeleteSnapshotBackupCommand(SwiftTO swift, S3TO s3, @@ -91,4 +91,4 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { this.s3 = s3; setAll(all); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java b/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java index 6879d2343e8..e2071d7f746 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java @@ -18,18 +18,18 @@ package com.cloud.agent.api; /** * This command encapsulates a primitive operation which enables coalescing the backed up VHD snapshots on the secondary server - * This currently assumes that the secondary storage are mounted on the XenServer. + * This currently assumes that the secondary storage are mounted on the XenServer. */ public class DeleteSnapshotsDirCommand extends Command { String secondaryStorageUrl; Long dcId; Long accountId; Long volumeId; - + protected DeleteSnapshotsDirCommand() { - + } - + public DeleteSnapshotsDirCommand(String secondaryStorageUrl, Long dcId, Long accountId, Long volumeId) { @@ -60,4 +60,4 @@ public class DeleteSnapshotsDirCommand extends Command { return volumeId; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java b/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java index 7fa60adb0fe..4618d59da26 100644 --- a/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java @@ -23,20 +23,20 @@ import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.storage.StoragePool; public class DeleteStoragePoolCommand extends Command { - + StorageFilerTO pool; public static final String LOCAL_PATH_PREFIX="/mnt/"; String localPath; - + public DeleteStoragePoolCommand() { - + } - + public DeleteStoragePoolCommand(StoragePool pool, String localPath) { this.pool = new StorageFilerTO(pool); this.localPath = localPath; } - + public DeleteStoragePoolCommand(StoragePool pool) { this(pool, LOCAL_PATH_PREFIX + File.separator + UUID.nameUUIDFromBytes((pool.getHostAddress() + pool.getPath()).getBytes())); } @@ -48,7 +48,7 @@ public class DeleteStoragePoolCommand extends Command { public void setPool(StoragePool pool) { this.pool = new StorageFilerTO(pool); } - + @Override public boolean executeInSequence() { return false; @@ -57,5 +57,5 @@ public class DeleteStoragePoolCommand extends Command { public String getLocalPath() { return localPath; } - + } diff --git a/api/src/com/cloud/agent/api/FenceAnswer.java b/api/src/com/cloud/agent/api/FenceAnswer.java index 13ee3017660..7af18f5e7b3 100644 --- a/api/src/com/cloud/agent/api/FenceAnswer.java +++ b/api/src/com/cloud/agent/api/FenceAnswer.java @@ -20,15 +20,15 @@ public class FenceAnswer extends Answer { public FenceAnswer() { super(); } - + public FenceAnswer(FenceCommand cmd) { super(cmd, true, null); } - + public FenceAnswer(FenceCommand cmd, String details) { super(cmd, true, details); } - + public FenceAnswer(FenceCommand cmd, boolean result, String details) { super(cmd, result, details); } diff --git a/api/src/com/cloud/agent/api/FenceCommand.java b/api/src/com/cloud/agent/api/FenceCommand.java index 5ba293af1a3..a89194442ab 100644 --- a/api/src/com/cloud/agent/api/FenceCommand.java +++ b/api/src/com/cloud/agent/api/FenceCommand.java @@ -20,16 +20,16 @@ import com.cloud.host.Host; import com.cloud.vm.VirtualMachine; public class FenceCommand extends Command { - + public FenceCommand() { super(); } - + String vmName; String hostGuid; String hostIp; boolean inSeq; - + public FenceCommand(VirtualMachine vm, Host host) { super(); vmName = vm.getInstanceName(); @@ -37,19 +37,19 @@ public class FenceCommand extends Command { hostIp = host.getPrivateIpAddress(); inSeq = false; } - + public void setSeq(boolean inseq) { inSeq = inseq; } - + public String getVmName() { return vmName; } - + public String getHostGuid() { return hostGuid; } - + public String getHostIp() { return hostIp; } diff --git a/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java b/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java index 992b5076db7..7487b57c73c 100644 --- a/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java +++ b/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java @@ -21,24 +21,24 @@ public class GetDomRVersionAnswer extends Answer { public static final String ROUTER_IP = "router.ip"; String templateVersion; String scriptsVersion; - + protected GetDomRVersionAnswer() { } - + public GetDomRVersionAnswer(GetDomRVersionCmd cmd, String details, String templateVersion, String scriptsVersion) { super(cmd, true, details); this.templateVersion = templateVersion; this.scriptsVersion = scriptsVersion; } - + public GetDomRVersionAnswer(GetDomRVersionCmd cmd, String details) { super(cmd, false, details); } - + public String getTemplateVersion() { return this.templateVersion; } - + public String getScriptsVersion() { return this.scriptsVersion; } diff --git a/api/src/com/cloud/agent/api/GetVncPortAnswer.java b/api/src/com/cloud/agent/api/GetVncPortAnswer.java index da464264c5b..5e94a18d3d9 100644 --- a/api/src/com/cloud/agent/api/GetVncPortAnswer.java +++ b/api/src/com/cloud/agent/api/GetVncPortAnswer.java @@ -19,29 +19,29 @@ package com.cloud.agent.api; public class GetVncPortAnswer extends Answer { String address; int port; - + protected GetVncPortAnswer() { } - + public GetVncPortAnswer(GetVncPortCommand cmd, int port) { super(cmd, true, null); this.port = port; } - + public GetVncPortAnswer(GetVncPortCommand cmd, String address, int port) { super(cmd, true, null); this.address = address; this.port = port; } - + public GetVncPortAnswer(GetVncPortCommand cmd, String details) { super(cmd, false, details); } - + public String getAddress() { return address; } - + public int getPort() { return port; } diff --git a/api/src/com/cloud/agent/api/GetVncPortCommand.java b/api/src/com/cloud/agent/api/GetVncPortCommand.java index cff787e595b..06165dce8ff 100644 --- a/api/src/com/cloud/agent/api/GetVncPortCommand.java +++ b/api/src/com/cloud/agent/api/GetVncPortCommand.java @@ -22,21 +22,21 @@ public class GetVncPortCommand extends Command { public GetVncPortCommand() { } - + public GetVncPortCommand(long id, String name) { this.id = id; this.name = name; } - + @Override public boolean executeInSequence() { return false; } - + public String getName() { return name; } - + public long getId() { return id; } diff --git a/api/src/com/cloud/agent/api/HostStatsEntry.java b/api/src/com/cloud/agent/api/HostStatsEntry.java index d34e0d76f5c..0d8cfb2d349 100644 --- a/api/src/com/cloud/agent/api/HostStatsEntry.java +++ b/api/src/com/cloud/agent/api/HostStatsEntry.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.host.HostStats; public class HostStatsEntry implements HostStats { - + long hostId; String entityType; double cpuUtilization; @@ -27,12 +27,12 @@ public class HostStatsEntry implements HostStats { double networkWriteKBs; double totalMemoryKBs; double freeMemoryKBs; - + public HostStatsEntry() { } - + public HostStatsEntry(long hostId,double cpuUtilization, double networkReadKBs, double networkWriteKBs, String entityType, - double totalMemoryKBs, double freeMemoryKBs, double xapiMemoryUsageKBs, double averageLoad) + double totalMemoryKBs, double freeMemoryKBs, double xapiMemoryUsageKBs, double averageLoad) { this.hostId = hostId; this.entityType = entityType; @@ -47,16 +47,16 @@ public class HostStatsEntry implements HostStats { public double getNetworkReadKBs() { return networkReadKBs; } - + public void setNetworkReadKBs(double networkReadKBs) { this.networkReadKBs = networkReadKBs; } - + @Override public double getNetworkWriteKBs() { return networkWriteKBs; } - + public void setNetworkWriteKBs(double networkWriteKBs) { this.networkWriteKBs = networkWriteKBs; } @@ -65,16 +65,16 @@ public class HostStatsEntry implements HostStats { public String getEntityType(){ return this.entityType; } - + public void setEntityType(String entityType){ this.entityType = entityType; } - + @Override public double getTotalMemoryKBs(){ return this.totalMemoryKBs; } - + public void setTotalMemoryKBs(double totalMemoryKBs){ this.totalMemoryKBs = totalMemoryKBs; } @@ -83,11 +83,11 @@ public class HostStatsEntry implements HostStats { public double getFreeMemoryKBs(){ return this.freeMemoryKBs; } - + public void setFreeMemoryKBs(double freeMemoryKBs){ this.freeMemoryKBs = freeMemoryKBs; } - + @Override public double getCpuUtilization() { return this.cpuUtilization; @@ -106,7 +106,7 @@ public class HostStatsEntry implements HostStats { public HostStats getHostStats() { return this; } - + public void setHostId(long hostId) { this.hostId = hostId; } diff --git a/api/src/com/cloud/agent/api/MaintainAnswer.java b/api/src/com/cloud/agent/api/MaintainAnswer.java index c36286934ee..dcfdab31708 100644 --- a/api/src/com/cloud/agent/api/MaintainAnswer.java +++ b/api/src/com/cloud/agent/api/MaintainAnswer.java @@ -18,28 +18,28 @@ package com.cloud.agent.api; public class MaintainAnswer extends Answer { boolean willMigrate; - + public MaintainAnswer() { } - + public MaintainAnswer(MaintainCommand cmd) { this(cmd, true, null); } - + public MaintainAnswer(MaintainCommand cmd, boolean willMigrate) { this(cmd, true, null); this.willMigrate = willMigrate; } - + public MaintainAnswer(MaintainCommand cmd, String details) { this(cmd, true, details); } - + public MaintainAnswer(MaintainCommand cmd, boolean result, String details) { super(cmd, result, details); this.willMigrate = true; } - + public boolean getMigrate() { return this.willMigrate; } diff --git a/api/src/com/cloud/agent/api/MaintainCommand.java b/api/src/com/cloud/agent/api/MaintainCommand.java index 654476a58b6..2a9b9a5ae7d 100644 --- a/api/src/com/cloud/agent/api/MaintainCommand.java +++ b/api/src/com/cloud/agent/api/MaintainCommand.java @@ -20,7 +20,7 @@ public class MaintainCommand extends Command { public MaintainCommand() { } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java b/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java index 6dd757505b1..e490bdf076b 100644 --- a/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java @@ -20,13 +20,13 @@ package com.cloud.agent.api; public class ManageSnapshotAnswer extends Answer { // For create Snapshot private String _snapshotPath; - + public ManageSnapshotAnswer() {} public ManageSnapshotAnswer(Command cmd, boolean success, String result) { super(cmd, success, result); } - + // For XenServer public ManageSnapshotAnswer(ManageSnapshotCommand cmd, long snapshotId, String snapshotPath, boolean success, String result) { super(cmd, success, result); @@ -36,5 +36,5 @@ public class ManageSnapshotAnswer extends Answer { public String getSnapshotPath() { return _snapshotPath; } - + } diff --git a/api/src/com/cloud/agent/api/ManageSnapshotCommand.java b/api/src/com/cloud/agent/api/ManageSnapshotCommand.java index 9a5f424167c..5effc542c5b 100644 --- a/api/src/com/cloud/agent/api/ManageSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/ManageSnapshotCommand.java @@ -25,9 +25,9 @@ public class ManageSnapshotCommand extends Command { // XXX: Anyway there is something called inheritance in Java public static String CREATE_SNAPSHOT = "-c"; public static String DESTROY_SNAPSHOT = "-d"; - + private String _commandSwitch; - + // Information about the volume that the snapshot is based on private String _volumePath = null; StorageFilerTO _pool; @@ -43,7 +43,7 @@ public class ManageSnapshotCommand extends Command { public ManageSnapshotCommand(long snapshotId, String volumePath, StoragePool pool, String preSnapshotPath ,String snapshotName, String vmName) { _commandSwitch = ManageSnapshotCommand.CREATE_SNAPSHOT; _volumePath = volumePath; - _pool = new StorageFilerTO(pool); + _pool = new StorageFilerTO(pool); _snapshotPath = preSnapshotPath; _snapshotName = snapshotName; _snapshotId = snapshotId; @@ -54,8 +54,8 @@ public class ManageSnapshotCommand extends Command { _commandSwitch = ManageSnapshotCommand.DESTROY_SNAPSHOT; _snapshotPath = snapshotPath; } - - + + @Override public boolean executeInSequence() { return false; @@ -64,15 +64,15 @@ public class ManageSnapshotCommand extends Command { public String getCommandSwitch() { return _commandSwitch; } - + public String getVolumePath() { return _volumePath; } - + public StorageFilerTO getPool() { return _pool; } - + public String getSnapshotPath() { return _snapshotPath; } @@ -84,9 +84,9 @@ public class ManageSnapshotCommand extends Command { public long getSnapshotId() { return _snapshotId; } - + public String getVmName() { return _vmName; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/MigrateAnswer.java b/api/src/com/cloud/agent/api/MigrateAnswer.java index 4b5dd19d06f..19d690a2d99 100644 --- a/api/src/com/cloud/agent/api/MigrateAnswer.java +++ b/api/src/com/cloud/agent/api/MigrateAnswer.java @@ -18,15 +18,15 @@ package com.cloud.agent.api; public class MigrateAnswer extends Answer { Integer vncPort = null; - + protected MigrateAnswer() { } - + public MigrateAnswer(MigrateCommand cmd, boolean result, String detail, Integer vncPort) { super(cmd, result, detail); this.vncPort = vncPort; } - + public Integer getVncPort() { return vncPort; } diff --git a/api/src/com/cloud/agent/api/MigrateCommand.java b/api/src/com/cloud/agent/api/MigrateCommand.java index 18a2be19d88..5042b8c1971 100644 --- a/api/src/com/cloud/agent/api/MigrateCommand.java +++ b/api/src/com/cloud/agent/api/MigrateCommand.java @@ -25,29 +25,29 @@ public class MigrateCommand extends Command { protected MigrateCommand() { } - + public MigrateCommand(String vmName, String destIp, boolean isWindows) { this.vmName = vmName; this.destIp = destIp; this.isWindows = isWindows; } - + public boolean isWindows() { return isWindows; } - + public String getDestinationIp() { return destIp; } - + public String getVmName() { return vmName; } - + public void setHostGuid(String guid) { this.hostGuid = guid; } - + public String getHostGuid() { return this.hostGuid; } diff --git a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java index a8ab78dec99..df77985248f 100644 --- a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java +++ b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java @@ -30,13 +30,13 @@ public class ModifyStoragePoolAnswer extends Answer { public ModifyStoragePoolAnswer(ModifyStoragePoolCommand cmd, long capacityBytes, long availableBytes, Map tInfo) { super(cmd); this.result = true; - this.poolInfo = new StoragePoolInfo(null, - cmd.getPool().getHost(), cmd.getPool().getPath(), cmd.getLocalPath(), + this.poolInfo = new StoragePoolInfo(null, + cmd.getPool().getHost(), cmd.getPool().getPath(), cmd.getLocalPath(), cmd.getPool().getType(), capacityBytes, availableBytes ); - + this.templateInfo = tInfo; } - + public StoragePoolInfo getPoolInfo() { return poolInfo; } diff --git a/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java b/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java index 04f14e3de8f..8bc956d54d0 100644 --- a/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java @@ -23,25 +23,25 @@ import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.storage.StoragePool; public class ModifyStoragePoolCommand extends Command { - + boolean add; StorageFilerTO pool; String localPath; String [] options; public static final String LOCAL_PATH_PREFIX="/mnt/"; - + public ModifyStoragePoolCommand() { - + } - + public ModifyStoragePoolCommand(boolean add, StoragePool pool, String localPath) { this.add = add; this.pool = new StorageFilerTO(pool); this.localPath = localPath; } - + public ModifyStoragePoolCommand(boolean add, StoragePool pool) { this(add, pool, LOCAL_PATH_PREFIX + File.separator + UUID.nameUUIDFromBytes((pool.getHostAddress() + pool.getPath()).getBytes())); } @@ -53,11 +53,11 @@ public class ModifyStoragePoolCommand extends Command { public void setPool(StoragePool pool) { this.pool = new StorageFilerTO(pool); } - + public boolean getAdd() { return add; } - + @Override public boolean executeInSequence() { return false; @@ -71,5 +71,5 @@ public class ModifyStoragePoolCommand extends Command { this.options = options; } - + } diff --git a/api/src/com/cloud/agent/api/NetworkUsageAnswer.java b/api/src/com/cloud/agent/api/NetworkUsageAnswer.java index 7d5d49b3a71..fd8ebda4d2a 100644 --- a/api/src/com/cloud/agent/api/NetworkUsageAnswer.java +++ b/api/src/com/cloud/agent/api/NetworkUsageAnswer.java @@ -33,7 +33,7 @@ public class NetworkUsageAnswer extends Answer { this.bytesSent = bytesSent; routerName = cmd.getDomRName(); } - + public NetworkUsageAnswer(Command command, Exception e) { super(command, e); } diff --git a/api/src/com/cloud/agent/api/NetworkUsageCommand.java b/api/src/com/cloud/agent/api/NetworkUsageCommand.java index acb23cf61d8..6cbf93b3ef2 100644 --- a/api/src/com/cloud/agent/api/NetworkUsageCommand.java +++ b/api/src/com/cloud/agent/api/NetworkUsageCommand.java @@ -57,7 +57,7 @@ public class NetworkUsageCommand extends Command { this.option = "create"; this.vpcCIDR = vpcCIDR; } - + public NetworkUsageCommand(String privateIP, String domRName, String option, boolean forVpc, String gatewayIP) { this.privateIP = privateIP; @@ -66,7 +66,7 @@ public class NetworkUsageCommand extends Command { this.gatewayIP = gatewayIP; this.option = option; } - + public String getPrivateIP() { return privateIP; } diff --git a/api/src/com/cloud/agent/api/PingAnswer.java b/api/src/com/cloud/agent/api/PingAnswer.java index 388d67db0fb..d9ed89cc5df 100644 --- a/api/src/com/cloud/agent/api/PingAnswer.java +++ b/api/src/com/cloud/agent/api/PingAnswer.java @@ -21,7 +21,7 @@ public class PingAnswer extends Answer { protected PingAnswer() { } - + public PingAnswer(PingCommand cmd) { super(cmd); _command = cmd; diff --git a/api/src/com/cloud/agent/api/PingCommand.java b/api/src/com/cloud/agent/api/PingCommand.java index 3b3ca61685a..8d9681f9fa9 100755 --- a/api/src/com/cloud/agent/api/PingCommand.java +++ b/api/src/com/cloud/agent/api/PingCommand.java @@ -21,23 +21,23 @@ import com.cloud.host.Host; public class PingCommand extends Command { Host.Type hostType; long hostId; - + protected PingCommand() { } - + public PingCommand(Host.Type type, long id) { hostType = type; hostId = id; } - + public Host.Type getHostType() { return hostType; } - + public long getHostId() { return hostId; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/PingRoutingCommand.java b/api/src/com/cloud/agent/api/PingRoutingCommand.java index eebe041ff21..e25ac62786f 100755 --- a/api/src/com/cloud/agent/api/PingRoutingCommand.java +++ b/api/src/com/cloud/agent/api/PingRoutingCommand.java @@ -25,15 +25,15 @@ public class PingRoutingCommand extends PingCommand { Map newStates; boolean _gatewayAccessible = true; boolean _vnetAccessible = true; - + protected PingRoutingCommand() { } - + public PingRoutingCommand(Host.Type type, long id, Map states) { super(type, id); this.newStates = states; } - + public Map getNewStates() { return newStates; } diff --git a/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java b/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java index 5842f385402..d44987b20fd 100644 --- a/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java +++ b/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java @@ -25,17 +25,17 @@ import com.cloud.vm.VirtualMachine.State; public class PingRoutingWithOvsCommand extends PingRoutingCommand { List> states; - + protected PingRoutingWithOvsCommand() { super(); } - + public PingRoutingWithOvsCommand(Host.Type type, long id, Map states, List> ovsStates) { super(type, id, states); this.states = ovsStates; } - + public List> getStates() { return states; } diff --git a/api/src/com/cloud/agent/api/PingStorageCommand.java b/api/src/com/cloud/agent/api/PingStorageCommand.java index 963bc7b2a6b..438ab507852 100755 --- a/api/src/com/cloud/agent/api/PingStorageCommand.java +++ b/api/src/com/cloud/agent/api/PingStorageCommand.java @@ -25,12 +25,12 @@ public class PingStorageCommand extends PingCommand { protected PingStorageCommand() { } - + public PingStorageCommand(Host.Type type, long id, Map changes) { super(type, id); this.changes = changes; } - + public Map getChanges() { return changes; } diff --git a/api/src/com/cloud/agent/api/PlugNicCommand.java b/api/src/com/cloud/agent/api/PlugNicCommand.java index aa5141eab8e..b896e4540cb 100644 --- a/api/src/com/cloud/agent/api/PlugNicCommand.java +++ b/api/src/com/cloud/agent/api/PlugNicCommand.java @@ -19,22 +19,22 @@ package com.cloud.agent.api; import com.cloud.agent.api.to.NicTO; public class PlugNicCommand extends Command { - + NicTO nic; String instanceName; - + public NicTO getNic() { return nic; } - + @Override public boolean executeInSequence() { return true; } - + protected PlugNicCommand() { } - + public PlugNicCommand(NicTO nic, String instanceName) { this.nic = nic; this.instanceName = instanceName; diff --git a/api/src/com/cloud/agent/api/PoolEjectCommand.java b/api/src/com/cloud/agent/api/PoolEjectCommand.java index faea30e3f86..3085042eeb4 100644 --- a/api/src/com/cloud/agent/api/PoolEjectCommand.java +++ b/api/src/com/cloud/agent/api/PoolEjectCommand.java @@ -18,22 +18,22 @@ package com.cloud.agent.api; public class PoolEjectCommand extends Command { private String hostuuid; - + public String getHostuuid() { return hostuuid; } - + public void setHostuuid(String hostuuid) { this.hostuuid = hostuuid; } public PoolEjectCommand() { super(); } - public PoolEjectCommand(String hostuuid) { + public PoolEjectCommand(String hostuuid) { super(); setHostuuid(hostuuid); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java b/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java index bbd63cc2cea..1b215bc086e 100644 --- a/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java +++ b/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java @@ -19,15 +19,15 @@ package com.cloud.agent.api; public class PrepareForMigrationAnswer extends Answer { protected PrepareForMigrationAnswer() { } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd, String detail) { super(cmd, false, detail); } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd, Exception ex) { super(cmd, ex); } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd) { super(cmd, true, null); } diff --git a/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java b/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java index e10bca0ba72..c0e136883f9 100644 --- a/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java +++ b/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java @@ -20,18 +20,18 @@ import com.cloud.agent.api.to.VirtualMachineTO; public class PrepareForMigrationCommand extends Command { VirtualMachineTO vm; - + protected PrepareForMigrationCommand() { } - + public PrepareForMigrationCommand(VirtualMachineTO vm) { this.vm = vm; } - + public VirtualMachineTO getVirtualMachine() { return vm; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java b/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java index eda0fd9740f..0c80bfa6f08 100755 --- a/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java +++ b/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java @@ -23,7 +23,7 @@ import com.cloud.utils.Ternary; public class PrepareOCFS2NodesCommand extends Command { List> nodes; String clusterName; - + @Override public boolean executeInSequence() { return true; @@ -33,11 +33,11 @@ public class PrepareOCFS2NodesCommand extends Command { this.nodes = nodes; this.clusterName = clusterName; } - + public List> getNodes() { return nodes; } - + public String getClusterName() { return clusterName; } diff --git a/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java b/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java index 3442c7715e1..45cd4b30ef1 100755 --- a/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java +++ b/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java @@ -21,24 +21,24 @@ import com.cloud.resource.ResourceState; public class PropagateResourceEventCommand extends Command { long hostId; ResourceState.Event event; - + protected PropagateResourceEventCommand() { - + } - + public PropagateResourceEventCommand(long hostId, ResourceState.Event event) { this.hostId = hostId; this.event = event; } - + public long getHostId() { return hostId; } - + public ResourceState.Event getEvent() { return event; } - + @Override public boolean executeInSequence() { // TODO Auto-generated method stub diff --git a/api/src/com/cloud/agent/api/ReadyAnswer.java b/api/src/com/cloud/agent/api/ReadyAnswer.java index 3f8172c39e5..b5dd0b7d360 100644 --- a/api/src/com/cloud/agent/api/ReadyAnswer.java +++ b/api/src/com/cloud/agent/api/ReadyAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class ReadyAnswer extends Answer { protected ReadyAnswer() { } - + public ReadyAnswer(ReadyCommand cmd) { super(cmd, true, null); } - + public ReadyAnswer(ReadyCommand cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/ReadyCommand.java b/api/src/com/cloud/agent/api/ReadyCommand.java index 0c91a2555fa..c6ca799a132 100644 --- a/api/src/com/cloud/agent/api/ReadyCommand.java +++ b/api/src/com/cloud/agent/api/ReadyCommand.java @@ -24,29 +24,29 @@ public class ReadyCommand extends Command { private Long dcId; private Long hostId; - + public ReadyCommand(Long dcId) { super(); this.dcId = dcId; } - + public ReadyCommand(Long dcId, Long hostId) { this(dcId); this.hostId = hostId; } - + public void setDetails(String details) { _details = details; } - + public String getDetails() { return _details; } - + public Long getDataCenterId() { return dcId; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/RebootAnswer.java b/api/src/com/cloud/agent/api/RebootAnswer.java index da53b4fb1a3..244bf1e21ce 100644 --- a/api/src/com/cloud/agent/api/RebootAnswer.java +++ b/api/src/com/cloud/agent/api/RebootAnswer.java @@ -18,24 +18,24 @@ package com.cloud.agent.api; public class RebootAnswer extends Answer { Integer vncPort; - + protected RebootAnswer() { } - + public RebootAnswer(RebootCommand cmd, String details, Integer vncport) { super(cmd, true, details); this.vncPort = vncport; } - + public RebootAnswer(RebootCommand cmd, String details, boolean success) { super(cmd, success, details); this.vncPort = null; } - + public RebootAnswer(RebootCommand cmd, Exception e) { super(cmd, e); } - + public Integer getVncPort() { return vncPort; } diff --git a/api/src/com/cloud/agent/api/RebootCommand.java b/api/src/com/cloud/agent/api/RebootCommand.java index 2925e2a8a2b..299e61b76af 100755 --- a/api/src/com/cloud/agent/api/RebootCommand.java +++ b/api/src/com/cloud/agent/api/RebootCommand.java @@ -20,25 +20,25 @@ import com.cloud.vm.VirtualMachine; public class RebootCommand extends Command { String vmName; - + protected RebootCommand() { } - + public RebootCommand(VirtualMachine vm) { vmName = vm.getInstanceName(); } - + public RebootCommand(String vmName) { this.vmName = vmName; } - + public String getVmName() { return vmName; } - + @Override public boolean executeInSequence() { return true; } - + } diff --git a/api/src/com/cloud/agent/api/RebootRouterCommand.java b/api/src/com/cloud/agent/api/RebootRouterCommand.java index bf5d866b0dc..c5027b326a3 100644 --- a/api/src/com/cloud/agent/api/RebootRouterCommand.java +++ b/api/src/com/cloud/agent/api/RebootRouterCommand.java @@ -18,7 +18,7 @@ package com.cloud.agent.api; public class RebootRouterCommand extends RebootCommand { - + protected String privateIp; protected RebootRouterCommand() { diff --git a/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java b/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java index 276ed065182..41a779b7d7a 100755 --- a/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java @@ -33,7 +33,7 @@ public class SecStorageFirewallCfgCommand extends Command { this.intf = intf; } public PortConfig() { - + } public boolean isAdd() { return add; @@ -48,28 +48,28 @@ public class SecStorageFirewallCfgCommand extends Command { return intf; } } - + private List portConfigs = new ArrayList(); - private boolean isAppendAIp = false; - + private boolean isAppendAIp = false; + public SecStorageFirewallCfgCommand() { - + } - + public SecStorageFirewallCfgCommand(boolean isAppend) { this.isAppendAIp = isAppend; - } - + } + public void addPortConfig(String sourceIp, String port, boolean add, String intf) { PortConfig pc = new PortConfig(sourceIp, port, add, intf); this.portConfigs.add(pc); - + } public boolean getIsAppendAIp() { return isAppendAIp; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java b/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java index 494bce53c3b..bb0c01652d5 100644 --- a/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java +++ b/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java @@ -20,12 +20,12 @@ public class SecStorageSetupAnswer extends Answer { private String _dir; protected SecStorageSetupAnswer() { } - + public SecStorageSetupAnswer(String dir) { super(null, true, "success"); this._dir = dir; } - + public String get_dir() { return _dir; } diff --git a/api/src/com/cloud/agent/api/SecStorageSetupCommand.java b/api/src/com/cloud/agent/api/SecStorageSetupCommand.java index 208b8a6cd5b..50c06cffa43 100644 --- a/api/src/com/cloud/agent/api/SecStorageSetupCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageSetupCommand.java @@ -21,7 +21,7 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; public class SecStorageSetupCommand extends Command { private String secUrl; private Certificates certs; - + public static class Certificates { @LogLevel(Log4jLevel.Off) private String privKey; @@ -29,30 +29,30 @@ public class SecStorageSetupCommand extends Command { private String privCert; @LogLevel(Log4jLevel.Off) private String certChain; - + public Certificates() { - + } - + public Certificates(String prvKey, String privCert, String certChain) { this.privKey = prvKey; this.privCert = privCert; this.certChain = certChain; } - + public String getPrivKey() { return this.privKey; } - + public String getPrivCert() { return this.privCert; } - + public String getCertChain() { return this.certChain; } } - + public SecStorageSetupCommand() { super(); } @@ -62,7 +62,7 @@ public class SecStorageSetupCommand extends Command { this.secUrl = secUrl; this.certs = certs; } - + @Override public boolean executeInSequence() { return true; @@ -71,13 +71,13 @@ public class SecStorageSetupCommand extends Command { public String getSecUrl() { return secUrl; } - + public Certificates getCerts() { return this.certs; } public void setSecUrl(String secUrl) { this.secUrl = secUrl; - + } } diff --git a/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java b/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java index 03f2321a355..be977097f06 100644 --- a/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java @@ -20,11 +20,11 @@ public class SecStorageVMSetupCommand extends Command { String [] allowedInternalSites = new String[0]; String copyUserName; String copyPassword; - + public SecStorageVMSetupCommand() { super(); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java b/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java index 00cdbe83ffd..144fea2ae87 100644 --- a/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java +++ b/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java @@ -26,24 +26,24 @@ public class SecurityGroupRuleAnswer extends Answer { Long logSequenceNumber = null; Long vmId = null; FailureReason reason = FailureReason.NONE; - - + + protected SecurityGroupRuleAnswer() { } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd) { super(cmd); this.logSequenceNumber = cmd.getSeqNum(); this.vmId = cmd.getVmId(); } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail) { super(cmd, result, detail); this.logSequenceNumber = cmd.getSeqNum(); this.vmId = cmd.getVmId(); reason = FailureReason.PROGRAMMING_FAILED; } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail, FailureReason r) { super(cmd, result, detail); this.logSequenceNumber = cmd.getSeqNum(); diff --git a/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java b/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java index 32550df8448..affad1f9b9d 100644 --- a/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java +++ b/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java @@ -126,7 +126,7 @@ public class SecurityGroupRulesCmd extends Command { public void setEgressRuleSet(IpPortAndProto[] egressRuleSet) { this.egressRuleSet = egressRuleSet; } - + public String getGuestIp() { return guestIp; } @@ -156,15 +156,15 @@ public class SecurityGroupRulesCmd extends Command { } return ruleBuilder.toString(); } - + //convert cidrs in the form "a.b.c.d/e" to "hexvalue of 32bit ip/e" private String compressCidr(String cidr) { String [] toks = cidr.split("/"); long ipnum = NetUtils.ip2Long(toks[0]); return Long.toHexString(ipnum) + "/" + toks[1]; } - - + + public String stringifyCompressedRules() { StringBuilder ruleBuilder = new StringBuilder(); for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getIngressRuleSet()) { @@ -187,7 +187,7 @@ public class SecurityGroupRulesCmd extends Command { } return ruleBuilder.toString(); } - + /* * Compress the security group rules using zlib compression to allow the call to the hypervisor * to scale beyond 8k cidrs. @@ -243,7 +243,7 @@ public class SecurityGroupRulesCmd extends Command { public Long getVmId() { return vmId; } - + public int getTotalNumCidrs() { //useful for logging int count = 0; @@ -255,11 +255,11 @@ public class SecurityGroupRulesCmd extends Command { } return count; } - + public void setMsId(long msId) { this.msId = msId; } - + public Long getMsId() { return msId; } diff --git a/api/src/com/cloud/agent/api/SetupAnswer.java b/api/src/com/cloud/agent/api/SetupAnswer.java index beee79fb84c..97252a2708e 100644 --- a/api/src/com/cloud/agent/api/SetupAnswer.java +++ b/api/src/com/cloud/agent/api/SetupAnswer.java @@ -33,5 +33,5 @@ public class SetupAnswer extends Answer { public boolean needReconnect() { return _reconnect; } - + } diff --git a/api/src/com/cloud/agent/api/SetupCommand.java b/api/src/com/cloud/agent/api/SetupCommand.java index 0397813b9aa..ee43c5933da 100644 --- a/api/src/com/cloud/agent/api/SetupCommand.java +++ b/api/src/com/cloud/agent/api/SetupCommand.java @@ -23,7 +23,7 @@ public class SetupCommand extends Command { HostEnvironment env; boolean multipath; boolean needSetup; - + public boolean needSetup() { return needSetup; } @@ -37,18 +37,18 @@ public class SetupCommand extends Command { this.multipath = false; this.needSetup = false; } - + public HostEnvironment getEnvironment() { return env; } - + protected SetupCommand() { } - + public void setMultipathOn() { this.multipath = true; } - + public boolean useMultipath() { return multipath; } diff --git a/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java b/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java index 10dab557bf5..2cf5bf8ffaa 100644 --- a/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java +++ b/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java @@ -28,7 +28,7 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand{ Integer priority; boolean add = true; NicTO nic; - + public NicTO getNic() { return nic; } @@ -53,12 +53,12 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand{ public boolean executeInSequence() { return true; } - + protected SetupGuestNetworkCommand() { } - - - public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority, + + + public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority, String defaultDns1, String defaultDns2, boolean add, NicTO nic) { this.dhcpRange = dhcpRange; this.networkDomain = networkDomain; diff --git a/api/src/com/cloud/agent/api/ShutdownCommand.java b/api/src/com/cloud/agent/api/ShutdownCommand.java index fa66e34b176..5412f35c583 100644 --- a/api/src/com/cloud/agent/api/ShutdownCommand.java +++ b/api/src/com/cloud/agent/api/ShutdownCommand.java @@ -24,31 +24,31 @@ public class ShutdownCommand extends Command { public static final String Update = "update"; public static final String Unknown = "unknown"; public static final String DeleteHost = "deleteHost"; - + private String reason; private String detail; protected ShutdownCommand() { super(); } - + public ShutdownCommand(String reason, String detail) { super(); this.reason = reason; this.detail = detail; } - + /** - * @return return the reason the agent shutdown. If Unknown, call getDetail() for any details. + * @return return the reason the agent shutdown. If Unknown, call getDetail() for any details. */ public String getReason() { return reason; } - + public String getDetail() { return detail; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/StartAnswer.java b/api/src/com/cloud/agent/api/StartAnswer.java index d4a3f63bc96..922d060cfae 100644 --- a/api/src/com/cloud/agent/api/StartAnswer.java +++ b/api/src/com/cloud/agent/api/StartAnswer.java @@ -21,20 +21,20 @@ import com.cloud.agent.api.to.VirtualMachineTO; public class StartAnswer extends Answer { VirtualMachineTO vm; String host_guid; - + protected StartAnswer() { } - + public StartAnswer(StartCommand cmd, String msg) { super(cmd, false, msg); this.vm = cmd.getVirtualMachine(); } - + public StartAnswer(StartCommand cmd, Exception e) { super(cmd, false, e.getMessage()); this.vm = cmd.getVirtualMachine(); } - + public StartAnswer(StartCommand cmd) { super(cmd, true, null); this.vm = cmd.getVirtualMachine(); @@ -46,7 +46,7 @@ public class StartAnswer extends Answer { this.vm = cmd.getVirtualMachine(); this.host_guid = guid; } - + public VirtualMachineTO getVirtualMachine() { return vm; } diff --git a/api/src/com/cloud/agent/api/StartCommand.java b/api/src/com/cloud/agent/api/StartCommand.java index 4d871389836..ec707d6e851 100644 --- a/api/src/com/cloud/agent/api/StartCommand.java +++ b/api/src/com/cloud/agent/api/StartCommand.java @@ -28,12 +28,12 @@ public class StartCommand extends Command { public VirtualMachineTO getVirtualMachine() { return vm; } - + @Override public boolean executeInSequence() { return true; } - + protected StartCommand() { } diff --git a/api/src/com/cloud/agent/api/StartupAnswer.java b/api/src/com/cloud/agent/api/StartupAnswer.java index a078c2dc4df..c0925cbdd6f 100755 --- a/api/src/com/cloud/agent/api/StartupAnswer.java +++ b/api/src/com/cloud/agent/api/StartupAnswer.java @@ -20,24 +20,24 @@ package com.cloud.agent.api; public class StartupAnswer extends Answer { long hostId; int pingInterval; - + protected StartupAnswer() { } - + public StartupAnswer(StartupCommand cmd, long hostId, int pingInterval) { super(cmd); this.hostId = hostId; this.pingInterval = pingInterval; } - + public StartupAnswer(StartupCommand cmd, String details) { super(cmd, false, details); } - + public long getHostId() { return hostId; } - + public int getPingInterval() { return pingInterval; } diff --git a/api/src/com/cloud/agent/api/StartupCommand.java b/api/src/com/cloud/agent/api/StartupCommand.java index 6088beac785..dd2d3907e7b 100755 --- a/api/src/com/cloud/agent/api/StartupCommand.java +++ b/api/src/com/cloud/agent/api/StartupCommand.java @@ -43,11 +43,11 @@ public class StartupCommand extends Command { String agentTag; String resourceName; String gatewayIpAddress; - + public StartupCommand(Host.Type type) { this.type = type; } - + public StartupCommand(Long id, Host.Type type, String name, String dataCenter, String pod, String guid, String version) { super(); this.id = id; @@ -58,48 +58,48 @@ public class StartupCommand extends Command { this.version = version; this.type = type; } - + public StartupCommand(Long id, Host.Type type, String name, String dataCenter, String pod, String guid, String version, String gatewayIpAddress) { this(id, type, name, dataCenter, pod, guid, version); this.gatewayIpAddress = gatewayIpAddress; - } - + } + public Host.Type getHostType() { return type; } - + public void setHostType(Host.Type type) { this.type = type; } - + public String getIqn() { return iqn; } - + public void setCluster(String cluster) { this.cluster = cluster; } - + public String getCluster() { return cluster; } - + public void setIqn(String iqn) { this.iqn = iqn; } - + public String getDataCenter() { return dataCenter; } - + public String getPod() { return pod; } - + public Long getId() { return id; } - + public String getStorageIpAddressDeux() { return storageIpAddressDeux; } @@ -131,11 +131,11 @@ public class StartupCommand extends Command { public String getName() { return name; } - + public String getVersion() { return version; } - + public void setDataCenter(String dataCenter) { this.dataCenter = dataCenter; } @@ -147,7 +147,7 @@ public class StartupCommand extends Command { public void setGuid(String guid) { this.guid = guid; } - + public void setGuid(String guid, String resourceName) { this.resourceName = resourceName; this.guid = guid + "-" + resourceName; @@ -232,15 +232,15 @@ public class StartupCommand extends Command { public void setVersion(String version) { this.version = version; } - + public void setPublicIpAddress(String publicIpAddress) { this.publicIpAddress = publicIpAddress; } - + public String getAgentTag() { return agentTag; } - + public void setAgentTag(String tag) { agentTag = tag; } @@ -248,7 +248,7 @@ public class StartupCommand extends Command { public void setResourceName(String resourceName) { this.resourceName = resourceName; } - + public String getGuidWithoutResource() { if (resourceName == null) { return guid; @@ -265,11 +265,11 @@ public class StartupCommand extends Command { } } } - + public String getResourceName() { return resourceName; } - + public String getGatewayIpAddress() { return gatewayIpAddress; } @@ -277,8 +277,8 @@ public class StartupCommand extends Command { public void setGatewayIpAddress(String gatewayIpAddress) { this.gatewayIpAddress = gatewayIpAddress; } - - + + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java b/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java index 2ba4ab9eb40..c4ed10729fe 100644 --- a/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java +++ b/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.host.Host; public class StartupExternalFirewallCommand extends StartupCommand { - + public StartupExternalFirewallCommand() { super(Host.Type.ExternalFirewall); } diff --git a/api/src/com/cloud/agent/api/StartupProxyCommand.java b/api/src/com/cloud/agent/api/StartupProxyCommand.java index 63991573bea..25cd769e650 100644 --- a/api/src/com/cloud/agent/api/StartupProxyCommand.java +++ b/api/src/com/cloud/agent/api/StartupProxyCommand.java @@ -21,12 +21,12 @@ import com.cloud.host.Host; public class StartupProxyCommand extends StartupCommand { private int proxyPort; private long proxyVmId; - + public StartupProxyCommand() { super(Host.Type.ConsoleProxy); setIqn("NoIqn"); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/StartupRoutingCommand.java b/api/src/com/cloud/agent/api/StartupRoutingCommand.java index e6989403c11..5961ab0017e 100755 --- a/api/src/com/cloud/agent/api/StartupRoutingCommand.java +++ b/api/src/com/cloud/agent/api/StartupRoutingCommand.java @@ -90,7 +90,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr long memory, long dom0MinMemory, final String caps, - final HypervisorType hypervisorType, + final HypervisorType hypervisorType, final Map hostDetails, Map vms) { super(Host.Type.Routing); @@ -114,7 +114,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public StartupRoutingCommand(int cpus, long speed, long memory, long dom0MinMemory, final String caps, final HypervisorType hypervisorType, final Map hostDetails, Map vms, String hypervisorVersion) { this(cpus, speed, memory, dom0MinMemory, caps, hypervisorType, hostDetails, vms); this.hypervisorVersion = hypervisorVersion; - } + } public void setChanges(Map vms) { this.vms = vms; @@ -128,7 +128,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr this.vms.put(vm_name, new VmState(vms.get(vm_name), null)); } } - + public void setClusterVMStateChanges(HashMap> allStates){ _clusterVMStates = allStates; } @@ -156,7 +156,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public Map getVmStates() { return vms; } - + public HashMap> getClusterVMStateChanges() { return _clusterVMStates; } @@ -219,6 +219,6 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public void setHypervisorVersion(String hypervisorVersion) { this.hypervisorVersion = hypervisorVersion; - } + } } diff --git a/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java index 35896fb6e48..c19ea99e9e1 100644 --- a/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java @@ -19,12 +19,12 @@ package com.cloud.agent.api; import com.cloud.host.Host; public class StartupSecondaryStorageCommand extends StartupCommand { - + public StartupSecondaryStorageCommand() { super(Host.Type.SecondaryStorage); setIqn("NoIqn"); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/StartupStorageCommand.java b/api/src/com/cloud/agent/api/StartupStorageCommand.java index d1e67d48800..3c3b058ce39 100755 --- a/api/src/com/cloud/agent/api/StartupStorageCommand.java +++ b/api/src/com/cloud/agent/api/StartupStorageCommand.java @@ -26,7 +26,7 @@ import com.cloud.storage.template.TemplateInfo; public class StartupStorageCommand extends StartupCommand { - + String parent; Map templateInfo; long totalSize; @@ -39,7 +39,7 @@ public class StartupStorageCommand extends StartupCommand { public StartupStorageCommand() { super(Host.Type.Storage); } - + public StartupStorageCommand(String parent, StoragePoolType fsType, long totalSize, Map info) { super(Host.Type.Storage); this.parent = parent; @@ -48,7 +48,7 @@ public class StartupStorageCommand extends StartupCommand { this.poolInfo = null; this.fsType = fsType; } - + public StartupStorageCommand(String parent, StoragePoolType fsType, Map templateInfo, StoragePoolInfo poolInfo) { super(Host.Type.Storage); @@ -62,7 +62,7 @@ public class StartupStorageCommand extends StartupCommand { public String getParent() { return parent; } - + public void setParent(String parent) { this.parent = parent; } @@ -70,15 +70,15 @@ public class StartupStorageCommand extends StartupCommand { public void setNfsShare(String nfsShare) { this.nfsShare = nfsShare; } - + public String getNfsShare() { return nfsShare; } - + public long getTotalSize() { return totalSize; } - + public Map getTemplateInfo() { return templateInfo; } diff --git a/api/src/com/cloud/agent/api/StopAnswer.java b/api/src/com/cloud/agent/api/StopAnswer.java index 52f28f165f2..1111fed1375 100755 --- a/api/src/com/cloud/agent/api/StopAnswer.java +++ b/api/src/com/cloud/agent/api/StopAnswer.java @@ -18,28 +18,28 @@ package com.cloud.agent.api; public class StopAnswer extends RebootAnswer { Integer vncPort; - + protected StopAnswer() { } - + public StopAnswer(StopCommand cmd, String details, Integer vncPort, boolean success) { super(cmd, details, success); this.vncPort = vncPort; } - + public StopAnswer(StopCommand cmd, String details, boolean success) { super(cmd, details, success); vncPort = null; } - + public StopAnswer(StopCommand cmd, Exception e) { super(cmd, e); } - + @Override public Integer getVncPort() { return vncPort; } - + } diff --git a/api/src/com/cloud/agent/api/StopCommand.java b/api/src/com/cloud/agent/api/StopCommand.java index 176a7fb86ee..9ee7ce3c874 100755 --- a/api/src/com/cloud/agent/api/StopCommand.java +++ b/api/src/com/cloud/agent/api/StopCommand.java @@ -23,35 +23,35 @@ public class StopCommand extends RebootCommand { private boolean isProxy=false; private String urlPort=null; private String publicConsoleProxyIpAddress=null; - + protected StopCommand() { } - + public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress) { super(vm); this.isProxy = isProxy; this.urlPort = urlPort; this.publicConsoleProxyIpAddress = publicConsoleProxyIpAddress; } - + public StopCommand(VirtualMachine vm, String vnet) { super(vm); this.vnet = vnet; } - + public StopCommand(VirtualMachine vm, String vmName, String vnet) { super(vmName); this.vnet = vnet; } - + public StopCommand(String vmName) { super(vmName); } - + public String getVnet() { return vnet; } - + @Override public boolean executeInSequence() { return true; @@ -60,11 +60,11 @@ public class StopCommand extends RebootCommand { public boolean isProxy() { return this.isProxy; } - + public String getURLPort() { return this.urlPort; } - + public String getPublicConsoleProxyIpAddress() { return this.publicConsoleProxyIpAddress; } diff --git a/api/src/com/cloud/agent/api/StoragePoolInfo.java b/api/src/com/cloud/agent/api/StoragePoolInfo.java index 4ac6b296ba3..475205f2704 100644 --- a/api/src/com/cloud/agent/api/StoragePoolInfo.java +++ b/api/src/com/cloud/agent/api/StoragePoolInfo.java @@ -29,7 +29,7 @@ public class StoragePoolInfo { long capacityBytes; long availableBytes; Map details; - + protected StoragePoolInfo() { super(); } @@ -46,14 +46,14 @@ public class StoragePoolInfo { this.capacityBytes = capacityBytes; this.availableBytes = availableBytes; } - + public StoragePoolInfo(String uuid, String host, String hostPath, String localPath, StoragePoolType poolType, long capacityBytes, long availableBytes, Map details) { this(uuid, host, hostPath, localPath, poolType, capacityBytes, availableBytes); this.details = details; } - + public long getCapacityBytes() { return capacityBytes; } @@ -84,4 +84,4 @@ public class StoragePoolInfo { public Map getDetails() { return details; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/TransferAgentCommand.java b/api/src/com/cloud/agent/api/TransferAgentCommand.java index f6f63b79361..0dfde7eea0c 100644 --- a/api/src/com/cloud/agent/api/TransferAgentCommand.java +++ b/api/src/com/cloud/agent/api/TransferAgentCommand.java @@ -23,10 +23,10 @@ public class TransferAgentCommand extends Command { protected long futureOwner; protected long currentOwner; Event event; - + protected TransferAgentCommand() { } - + public TransferAgentCommand(long agentId, long currentOwner, long futureOwner, Event event) { this.agentId = agentId; this.currentOwner = currentOwner; diff --git a/api/src/com/cloud/agent/api/UnPlugNicCommand.java b/api/src/com/cloud/agent/api/UnPlugNicCommand.java index 0530527d5ba..b6cab8872f5 100644 --- a/api/src/com/cloud/agent/api/UnPlugNicCommand.java +++ b/api/src/com/cloud/agent/api/UnPlugNicCommand.java @@ -21,7 +21,7 @@ import com.cloud.agent.api.to.NicTO; public class UnPlugNicCommand extends Command{ NicTO nic; String instanceName; - + public NicTO getNic() { return nic; } @@ -30,10 +30,10 @@ public class UnPlugNicCommand extends Command{ public boolean executeInSequence() { return true; } - + protected UnPlugNicCommand() { } - + public UnPlugNicCommand(NicTO nic, String instanceName) { this.nic = nic; this.instanceName = instanceName; diff --git a/api/src/com/cloud/agent/api/UnsupportedAnswer.java b/api/src/com/cloud/agent/api/UnsupportedAnswer.java index 10a2b8addb8..7d0f24460d4 100644 --- a/api/src/com/cloud/agent/api/UnsupportedAnswer.java +++ b/api/src/com/cloud/agent/api/UnsupportedAnswer.java @@ -20,7 +20,7 @@ public class UnsupportedAnswer extends Answer { protected UnsupportedAnswer() { super(); } - + public UnsupportedAnswer(Command cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/UpgradeAnswer.java b/api/src/com/cloud/agent/api/UpgradeAnswer.java index b93131bdd37..00b0f25b050 100644 --- a/api/src/com/cloud/agent/api/UpgradeAnswer.java +++ b/api/src/com/cloud/agent/api/UpgradeAnswer.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; public class UpgradeAnswer extends Answer { protected UpgradeAnswer() { } - + public UpgradeAnswer(UpgradeCommand cmd, String failure) { super(cmd, false, failure); } diff --git a/api/src/com/cloud/agent/api/UpgradeCommand.java b/api/src/com/cloud/agent/api/UpgradeCommand.java index e85e72c8ea8..0e1b6d2e7c4 100644 --- a/api/src/com/cloud/agent/api/UpgradeCommand.java +++ b/api/src/com/cloud/agent/api/UpgradeCommand.java @@ -22,18 +22,18 @@ package com.cloud.agent.api; public class UpgradeCommand extends Command { String url; - + protected UpgradeCommand() { } - + public UpgradeCommand(String url) { this.url = url; } - + public String getUpgradeUrl() { return url; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java index 703aea06be0..f00f4902970 100644 --- a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java @@ -21,16 +21,16 @@ public class UpgradeSnapshotCommand extends SnapshotCommand { private String version; private Long templateId; private Long tmpltAccountId; - + protected UpgradeSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The UUID of the primary storage Pool * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * @param snapshotUuid The UUID of the snapshot which is going to be upgraded - * @param _version version for this snapshot + * @param _version version for this snapshot */ public UpgradeSnapshotCommand(StoragePool pool, String secondaryStoragePoolURL, @@ -60,5 +60,5 @@ public class UpgradeSnapshotCommand extends SnapshotCommand { public Long getTmpltAccountId() { return tmpltAccountId; - } + } } diff --git a/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java b/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java index d9b0e61cda0..f5bb5448be0 100644 --- a/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java @@ -21,11 +21,11 @@ public class ValidateSnapshotAnswer extends Answer { private String expectedSnapshotBackupUuid; private String actualSnapshotBackupUuid; private String actualSnapshotUuid; - + protected ValidateSnapshotAnswer() { - + } - + public ValidateSnapshotAnswer(ValidateSnapshotCommand cmd, boolean success, String result, String expectedSnapshotBackupUuid, String actualSnapshotBackupUuid, String actualSnapshotUuid) { super(cmd, success, result); this.expectedSnapshotBackupUuid = expectedSnapshotBackupUuid; @@ -39,14 +39,14 @@ public class ValidateSnapshotAnswer extends Answer { public String getExpectedSnapshotBackupUuid() { return expectedSnapshotBackupUuid; } - + /** * @return the actualSnapshotBackupUuid */ public String getActualSnapshotBackupUuid() { return actualSnapshotBackupUuid; } - + public String getActualSnapshotUuid() { return actualSnapshotUuid; } diff --git a/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java b/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java index 527502c28b3..9ffbf292281 100644 --- a/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java @@ -22,24 +22,24 @@ public class ValidateSnapshotCommand extends Command { private String firstBackupUuid; private String previousSnapshotUuid; private String templateUuid; - + protected ValidateSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The primary storage Pool Name Label * @param volumeUuid The UUID of the volume for which the snapshot was taken * @param firstBackupUuid This UUID of the first snapshot that was ever taken for this volume, even it was deleted. * @param previousSnapshotUuid The UUID of the previous snapshot on the primary. - * @param templateUuid If this is a root volume and no snapshot has been taken for it, - * this is the UUID of the template VDI. + * @param templateUuid If this is a root volume and no snapshot has been taken for it, + * this is the UUID of the template VDI. */ public ValidateSnapshotCommand(String primaryStoragePoolNameLabel, String volumeUuid, String firstBackupUuid, String previousSnapshotUuid, - String templateUuid) + String templateUuid) { this.primaryStoragePoolNameLabel = primaryStoragePoolNameLabel; this.volumeUuid = volumeUuid; @@ -51,7 +51,7 @@ public class ValidateSnapshotCommand extends Command { public String getPrimaryStoragePoolNameLabel() { return primaryStoragePoolNameLabel; } - + /** * @return the volumeUuid */ @@ -65,11 +65,11 @@ public class ValidateSnapshotCommand extends Command { public String getFirstBackupUuid() { return firstBackupUuid; } - + public String getPreviousSnapshotUuid() { return previousSnapshotUuid; } - + /** * @return the templateUuid */ @@ -81,4 +81,4 @@ public class ValidateSnapshotCommand extends Command { public boolean executeInSequence() { return false; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/VmStatsEntry.java b/api/src/com/cloud/agent/api/VmStatsEntry.java index 55694f86054..8828e9114f4 100755 --- a/api/src/com/cloud/agent/api/VmStatsEntry.java +++ b/api/src/com/cloud/agent/api/VmStatsEntry.java @@ -19,17 +19,17 @@ package com.cloud.agent.api; import com.cloud.vm.VmStats; public class VmStatsEntry implements VmStats { - + double cpuUtilization; double networkReadKBs; double networkWriteKBs; - int numCPUs; + int numCPUs; String entityType; - + public VmStatsEntry() { } - - public VmStatsEntry(double cpuUtilization, double networkReadKBs, double networkWriteKBs, int numCPUs, String entityType) + + public VmStatsEntry(double cpuUtilization, double networkReadKBs, double networkWriteKBs, int numCPUs, String entityType) { this.cpuUtilization = cpuUtilization; this.networkReadKBs = networkReadKBs; @@ -41,7 +41,7 @@ public class VmStatsEntry implements VmStats { public double getCPUUtilization() { return cpuUtilization; } - + public void setCPUUtilization(double cpuUtilization) { this.cpuUtilization = cpuUtilization; } @@ -49,23 +49,23 @@ public class VmStatsEntry implements VmStats { public double getNetworkReadKBs() { return networkReadKBs; } - + public void setNetworkReadKBs(double networkReadKBs) { this.networkReadKBs = networkReadKBs; } - + public double getNetworkWriteKBs() { return networkWriteKBs; } - + public void setNetworkWriteKBs(double networkWriteKBs) { this.networkWriteKBs = networkWriteKBs; } - + public int getNumCPUs() { return numCPUs; } - + public void setNumCPUs(int numCPUs) { this.numCPUs = numCPUs; } @@ -73,10 +73,10 @@ public class VmStatsEntry implements VmStats { public String getEntityType(){ return this.entityType; } - + public void setEntityType(String entityType){ this.entityType = entityType; } - + } diff --git a/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java b/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java index e0f4a28a156..fdd1fe910e9 100644 --- a/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java @@ -18,23 +18,23 @@ package com.cloud.agent.api.baremetal; import com.cloud.agent.api.Command; -public class IpmISetBootDevCommand extends Command { +public class IpmISetBootDevCommand extends Command { public enum BootDev { pxe(), disk(), cdrom(), } - + BootDev bootDev; - + public BootDev getBootDev() { return bootDev; } - + public IpmISetBootDevCommand(BootDev dev) { bootDev = dev; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java index 1190cb30033..d8f0529b44e 100644 --- a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java +++ b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java @@ -22,8 +22,8 @@ public class PreparePxeServerAnswer extends Answer { public PreparePxeServerAnswer(PreparePxeServerCommand cmd) { super(cmd, true, "SUCCESS"); } - + public PreparePxeServerAnswer(PreparePxeServerCommand cmd, String details) { super(cmd, false, details); - } + } } diff --git a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java index 0cda0f11464..6c735637034 100644 --- a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java @@ -28,12 +28,12 @@ public class PreparePxeServerCommand extends Command { String template; String vmName; String hostName; - + @Override public boolean executeInSequence() { return true; } - + public PreparePxeServerCommand(String ip, String mac, String netMask, String gateway, String dns, String template, String vmName, String hostName) { this.ip = ip; this.mac = mac; @@ -44,7 +44,7 @@ public class PreparePxeServerCommand extends Command { this.vmName = vmName; this.hostName = hostName; } - + public String getIp() { return ip; } @@ -68,11 +68,11 @@ public class PreparePxeServerCommand extends Command { public String getTemplate() { return template; } - + public String getVmName() { return vmName; } - + public String getHostName() { return hostName; } diff --git a/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java b/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java index 03d178e309a..b18742055df 100644 --- a/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java @@ -25,12 +25,12 @@ public class prepareCreateTemplateCommand extends Command { String gateway; String dns; String template; - + @Override public boolean executeInSequence() { return true; } - + public prepareCreateTemplateCommand(String ip, String mac, String netMask, String gateway, String dns, String template) { this.ip = ip; this.mac = mac; @@ -43,23 +43,23 @@ public class prepareCreateTemplateCommand extends Command { public String getIp() { return ip; } - + public String getMac() { return mac; } - + public String getNetMask() { return netMask; } - + public String getGateWay() { return gateway; } - + public String getDns() { return dns; } - + public String getTemplate() { return template; } diff --git a/api/src/com/cloud/agent/api/check/CheckSshAnswer.java b/api/src/com/cloud/agent/api/check/CheckSshAnswer.java index 7618159e63e..3414eb07c14 100644 --- a/api/src/com/cloud/agent/api/check/CheckSshAnswer.java +++ b/api/src/com/cloud/agent/api/check/CheckSshAnswer.java @@ -20,17 +20,17 @@ import com.cloud.agent.api.Answer; public class CheckSshAnswer extends Answer { protected CheckSshAnswer() { - + } - + public CheckSshAnswer(CheckSshCommand cmd) { super(cmd, true, null); } - + public CheckSshAnswer(CheckSshCommand cmd, String details) { super(cmd, false, details); } - + public CheckSshAnswer(CheckSshCommand cmd, Throwable th) { super(cmd, false, th.getMessage()); } diff --git a/api/src/com/cloud/agent/api/check/CheckSshCommand.java b/api/src/com/cloud/agent/api/check/CheckSshCommand.java index fb4210fc725..e384983e206 100644 --- a/api/src/com/cloud/agent/api/check/CheckSshCommand.java +++ b/api/src/com/cloud/agent/api/check/CheckSshCommand.java @@ -24,11 +24,11 @@ public class CheckSshCommand extends Command { int interval; int retries; String name; - + protected CheckSshCommand() { super(); } - + public CheckSshCommand(String instanceName, String ip, int port) { super(); this.ip = ip; @@ -37,7 +37,7 @@ public class CheckSshCommand extends Command { this.retries = 100; this.name = instanceName; } - + public String getName() { return name; } diff --git a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java index 6021762dcf0..a2ae611d316 100644 --- a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java +++ b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java @@ -20,7 +20,7 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { @LogLevel(Log4jLevel.Off) @@ -29,9 +29,9 @@ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { private String _parent; protected downloadSnapshotFromSwiftCommand() { - + } - + public downloadSnapshotFromSwiftCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long volumeId, String parent, String BackupUuid, int wait) { super(null, secondaryStorageUrl, BackupUuid, "", dcId, accountId, volumeId); diff --git a/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java index 0bf6e98e7cb..82290656095 100644 --- a/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command { @@ -35,9 +35,9 @@ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command private String path; protected downloadTemplateFromSwiftToSecondaryStorageCommand() { - + } - + public downloadTemplateFromSwiftToSecondaryStorageCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long templateId, String path, int wait) { this.swift = swift; @@ -87,4 +87,4 @@ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java b/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java index 318d9398d83..7582b0d880c 100644 --- a/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java +++ b/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java @@ -26,33 +26,33 @@ public class CheckConsoleProxyLoadCommand extends ProxyCommand { private String proxyVmName; private String proxyManagementIp; private int proxyCmdPort; - + public CheckConsoleProxyLoadCommand() { } - + public CheckConsoleProxyLoadCommand(long proxyVmId, String proxyVmName, String proxyManagementIp, int proxyCmdPort) { this.proxyVmId = proxyVmId; this.proxyVmName = proxyVmName; this.proxyManagementIp = proxyManagementIp; this.proxyCmdPort = proxyCmdPort; } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } - + public String getProxyManagementIp() { return proxyManagementIp; } - + public int getProxyCmdPort() { return proxyCmdPort; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java b/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java index df8f47d3557..ae93f51789b 100644 --- a/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java +++ b/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java @@ -23,21 +23,21 @@ public class ConsoleProxyLoadAnswer extends Answer { private long proxyVmId; private String proxyVmName; - + protected ConsoleProxyLoadAnswer() { } - + public ConsoleProxyLoadAnswer(Command command, long proxyVmId, String proxyVmName, boolean success, String details) { super(command, success, details); - + this.proxyVmId = proxyVmId; this.proxyVmName = proxyVmName; } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } diff --git a/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java b/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java index fd306ff2a92..c5af38eb724 100644 --- a/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java +++ b/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java @@ -27,21 +27,21 @@ public class StartConsoleProxyAgentHttpHandlerCommand extends Command { private String keystorePassword; @LogLevel(Log4jLevel.Off) private String encryptorPassword; - + public StartConsoleProxyAgentHttpHandlerCommand() { super(); } - + public StartConsoleProxyAgentHttpHandlerCommand(byte[] ksBits, String ksPassword) { this.keystoreBits = ksBits; this.keystorePassword = ksPassword; } - + @Override public boolean executeInSequence() { return true; } - + public byte[] getKeystoreBits() { return keystoreBits; } diff --git a/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java b/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java index b918ba49f84..ef4a549daf3 100644 --- a/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java +++ b/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java @@ -25,7 +25,7 @@ public class WatchConsoleProxyLoadCommand extends ProxyCommand implements CronCo private String proxyManagementIp; private int proxyCmdPort; int interval; - + public WatchConsoleProxyLoadCommand(int interval, long proxyVmId, String proxyVmName, String proxyManagementIp, int proxyCmdPort) { this.interval = interval; @@ -34,30 +34,30 @@ public class WatchConsoleProxyLoadCommand extends ProxyCommand implements CronCo this.proxyManagementIp = proxyManagementIp; this.proxyCmdPort = proxyCmdPort; } - + protected WatchConsoleProxyLoadCommand() { } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } - + public String getProxyManagementIp() { return proxyManagementIp; } - + public int getProxyCmdPort() { return proxyCmdPort; } - + public int getInterval() { return interval; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java b/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java index ed972a22f51..dc7f1a188fd 100644 --- a/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java +++ b/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java @@ -27,7 +27,7 @@ public class CreateLoadBalancerApplianceCommand extends NetworkElementCommand { String password; String publicInterface; String privateInterface; - + public CreateLoadBalancerApplianceCommand(String ip, String netmask, String gateway) { this.ip = ip; this.netmask = netmask; @@ -45,4 +45,4 @@ public class CreateLoadBalancerApplianceCommand extends NetworkElementCommand { public String getGateway() { return gateway; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java b/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java index ff38941f0a2..5c2cd582d4c 100644 --- a/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java +++ b/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java @@ -29,56 +29,56 @@ public class DhcpEntryCommand extends NetworkElementCommand { String staticRoutes; String defaultDns; - + protected DhcpEntryCommand() { - + } - + @Override public boolean executeInSequence() { return true; } - + public DhcpEntryCommand(String vmMac, String vmIpAddress, String vmName) { this.vmMac = vmMac; this.vmIpAddress = vmIpAddress; this.vmName = vmName; } - + public DhcpEntryCommand(String vmMac, String vmIpAddress, String vmName, String dns, String gateway) { this(vmMac, vmIpAddress, vmName); this.dns = dns; this.gateway = gateway; } - + public String getDns() { return dns; } - + public String getGateway() { return gateway; } - + public String getVmMac() { return vmMac; } - + public String getVmIpAddress() { return vmIpAddress; } - + public String getVmName() { return vmName; } - + public void setNextServer(String ip) { nextServer = ip; } - + public String getNextServer() { return nextServer; } - + public String getDefaultRouter() { return defaultRouter; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java b/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java index 18921969f75..194923c497e 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java @@ -20,13 +20,13 @@ import com.cloud.agent.api.Answer; public class IpAssocAnswer extends Answer{ String[] results; - + public static final String errorResult = "Failed"; - + protected IpAssocAnswer() { super(); } - + public IpAssocAnswer(IpAssocCommand cmd, String[] results) { boolean finalResult = true; @@ -41,7 +41,7 @@ public class IpAssocAnswer extends Answer{ assert(cmd.getIpAddresses().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocCommand.java b/api/src/com/cloud/agent/api/routing/IpAssocCommand.java index 5326b119352..5cdc2da2efa 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocCommand.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocCommand.java @@ -19,12 +19,12 @@ package com.cloud.agent.api.routing; import com.cloud.agent.api.to.IpAddressTO; public class IpAssocCommand extends NetworkElementCommand { - + IpAddressTO[] ipAddresses; protected IpAssocCommand() { } - + public IpAssocCommand(IpAddressTO[] ips) { this.ipAddresses = ips; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java b/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java index cc7fcb00f09..e5c900d19e2 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java @@ -22,7 +22,7 @@ public class IpAssocVpcCommand extends IpAssocCommand{ protected IpAssocVpcCommand() { super(); } - + public IpAssocVpcCommand(IpAddressTO[] ips) { super(ips); } diff --git a/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java b/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java index a5505e1e688..1c1fb914da3 100644 --- a/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java +++ b/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java @@ -31,13 +31,13 @@ public class LoadBalancerConfigCommand extends NetworkElementCommand { public String lbStatsPort = "8081"; /*load balancer listen on this port for stats */ public String lbStatsSrcCidrs = "0/0" ; /* TODO : currently there is no filtering based on the source ip */ public String lbStatsAuth = "admin1:AdMiN123"; - public String lbStatsUri = "/admin?stats"; + public String lbStatsUri = "/admin?stats"; NicTO nic; Long vpcId; - + protected LoadBalancerConfigCommand() { } - + public LoadBalancerConfigCommand(LoadBalancerTO[] loadBalancers, Long vpcId) { this.loadBalancers = loadBalancers; this.vpcId = vpcId; @@ -51,11 +51,11 @@ public class LoadBalancerConfigCommand extends NetworkElementCommand { this.nic = nic; this.vpcId = vpcId; } - + public NicTO getNic() { return nic; } - + public LoadBalancerTO[] getLoadBalancers() { return loadBalancers; } diff --git a/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java b/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java index 61e41e8f424..41ae80fe223 100644 --- a/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java +++ b/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java @@ -22,7 +22,7 @@ import com.cloud.agent.api.Command; public abstract class NetworkElementCommand extends Command { HashMap accessDetails = new HashMap(0); - + public static final String ACCOUNT_ID = "account.id"; public static final String GUEST_NETWORK_CIDR = "guest.network.cidr"; public static final String GUEST_NETWORK_GATEWAY = "guest.network.gateway"; @@ -32,19 +32,19 @@ public abstract class NetworkElementCommand extends Command { public static final String ROUTER_GUEST_IP = "router.guest.ip"; public static final String ZONE_NETWORK_TYPE = "zone.network.type"; public static final String GUEST_BRIDGE = "guest.bridge"; - + protected NetworkElementCommand() { super(); } - + public void setAccessDetail(String name, String value) { accessDetails.put(name, value); } - + public String getAccessDetail(String name) { return accessDetails.get(name); } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java b/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java index 8cf3ba2f89c..68d7caf016f 100644 --- a/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java @@ -18,17 +18,17 @@ package com.cloud.agent.api.routing; public class RemoteAccessVpnCfgCommand extends NetworkElementCommand { - + boolean create; String vpnServerIp; String ipRange; String presharedKey; String localIp; - + protected RemoteAccessVpnCfgCommand() { this.create = false; } - + public boolean isCreate() { return create; } @@ -37,12 +37,12 @@ public class RemoteAccessVpnCfgCommand extends NetworkElementCommand { public boolean executeInSequence() { return true; } - - + + public RemoteAccessVpnCfgCommand(boolean create, String vpnServerAddress, String localIp, String ipRange, String ipsecPresharedKey) { this.vpnServerIp = vpnServerAddress; this.ipRange = ipRange; - this.presharedKey = ipsecPresharedKey; + this.presharedKey = ipsecPresharedKey; this.localIp = localIp; this.create = create; } diff --git a/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java b/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java index 92cf671db6f..6dac1488e11 100644 --- a/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java +++ b/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java @@ -22,25 +22,25 @@ public class SavePasswordCommand extends NetworkElementCommand { String password; String vmIpAddress; String vmName; - - protected SavePasswordCommand() { + + protected SavePasswordCommand() { } - + @Override public boolean executeInSequence() { return true; } - + public SavePasswordCommand(String password, String vmIpAddress, String vmName) { this.password = password; this.vmIpAddress = vmIpAddress; this.vmName = vmName; } - + public String getPassword() { return password; } - + public String getVmIpAddress() { return vmIpAddress; } @@ -48,7 +48,7 @@ public class SavePasswordCommand extends NetworkElementCommand { public String getVmName() { return vmName; } - - - + + + } diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java index 82730bd7ea2..5268c3dda76 100644 --- a/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java @@ -20,16 +20,16 @@ import com.cloud.agent.api.Answer; public class SetFirewallRulesAnswer extends Answer { String[] results; - + protected SetFirewallRulesAnswer() { } - + public SetFirewallRulesAnswer(SetFirewallRulesCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getRules().length == results.length) : "rules and their results should be the same length don't you think?"; this.results = results; } - + public String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java index 528f36bfa81..3841bd7a157 100644 --- a/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java @@ -23,7 +23,7 @@ import java.util.Set; import com.cloud.agent.api.to.FirewallRuleTO; /** - * + * * AccessDetails allow different components to put in information about * how to access the components inside the command. */ @@ -32,11 +32,11 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { protected SetFirewallRulesCommand() { } - + public SetFirewallRulesCommand(List rules) { - this.rules = rules.toArray(new FirewallRuleTO[rules.size()]); + this.rules = rules.toArray(new FirewallRuleTO[rules.size()]); } - + public FirewallRuleTO[] getRules() { return rules; } @@ -45,34 +45,34 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { String [][] result = new String [2][]; Set toAdd = new HashSet(); - + for (FirewallRuleTO fwTO: rules) { - /* example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:, + /* example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:, * each entry format :protocol:srcport:destport:scidr: * reverted entry format :reverted:0:0:0: */ - if (fwTO.revoked() == true) + if (fwTO.revoked() == true) { StringBuilder sb = new StringBuilder(); /* This entry is added just to make sure atleast there will one entry in the list to get the ipaddress */ - sb.append(fwTO.getSrcIp()).append(":reverted:0:0:0:"); + sb.append(fwTO.getSrcIp()).append(":reverted:0:0:0:"); String fwRuleEntry = sb.toString(); toAdd.add(fwRuleEntry); continue; } - + List cidr; StringBuilder sb = new StringBuilder(); sb.append(fwTO.getSrcIp()).append(":").append(fwTO.getProtocol()).append(":"); if ("icmp".compareTo(fwTO.getProtocol()) == 0) { sb.append(fwTO.getIcmpType()).append(":").append(fwTO.getIcmpCode()).append(":"); - + }else if (fwTO.getStringSrcPortRange() == null) sb.append("0:0").append(":"); else sb.append(fwTO.getStringSrcPortRange()).append(":"); - + cidr = fwTO.getSourceCidrList(); if (cidr == null || cidr.isEmpty()) { @@ -80,19 +80,19 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { }else{ Boolean firstEntry = true; for (String tag : cidr) { - if (!firstEntry) sb.append("-"); + if (!firstEntry) sb.append("-"); sb.append(tag); firstEntry = false; } } sb.append(":"); String fwRuleEntry = sb.toString(); - + toAdd.add(fwRuleEntry); - + } result[0] = toAdd.toArray(new String[toAdd.size()]); - + return result; } } diff --git a/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java b/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java index cc14295e227..dc192add20b 100644 --- a/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java @@ -20,17 +20,17 @@ import com.cloud.agent.api.Answer; public class SetNetworkACLAnswer extends Answer { String[] results; - + protected SetNetworkACLAnswer() { } - + public SetNetworkACLAnswer(SetNetworkACLCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getRules().length == results.length) : "ACLs and their results should be the same length"; this.results = results; } - + public String[] getResults() { return results; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java b/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java index b8fe119176f..dba7354c8f2 100644 --- a/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java @@ -30,12 +30,12 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ protected SetNetworkACLCommand() { } - + public SetNetworkACLCommand(List rules, NicTO nic) { - this.rules = rules.toArray(new NetworkACLTO[rules.size()]); + this.rules = rules.toArray(new NetworkACLTO[rules.size()]); this.nic = nic; } - + public NetworkACLTO[] getRules() { return rules; } @@ -43,22 +43,22 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ String [][] result = new String [2][]; Set toAdd = new HashSet(); - + for (NetworkACLTO aclTO: rules) { - /* example : Ingress:tcp:80:80:0.0.0.0/0:,Egress:tcp:220:220:0.0.0.0/0:, + /* example : Ingress:tcp:80:80:0.0.0.0/0:,Egress:tcp:220:220:0.0.0.0/0:, * each entry format Ingress/Egress:protocol:start port: end port:scidrs: * reverted entry format Ingress/Egress:reverted:0:0:0: */ - if (aclTO.revoked() == true) + if (aclTO.revoked() == true) { StringBuilder sb = new StringBuilder(); /* This entry is added just to make sure atleast there will one entry in the list to get the ipaddress */ - sb.append(aclTO.getTrafficType().toString()).append(":reverted:0:0:0:"); + sb.append(aclTO.getTrafficType().toString()).append(":reverted:0:0:0:"); String aclRuleEntry = sb.toString(); toAdd.add(aclRuleEntry); continue; } - + List cidr; StringBuilder sb = new StringBuilder(); sb.append(aclTO.getTrafficType().toString()).append(":").append(aclTO.getProtocol()).append(":"); @@ -75,22 +75,22 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ }else{ Boolean firstEntry = true; for (String tag : cidr) { - if (!firstEntry) sb.append("-"); + if (!firstEntry) sb.append("-"); sb.append(tag); firstEntry = false; } } sb.append(":"); String aclRuleEntry = sb.toString(); - + toAdd.add(aclRuleEntry); - + } result[0] = toAdd.toArray(new String[toAdd.size()]); - + return result; } - + public NicTO getNic() { return nic; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java index 9aa2f6db5d2..15306fbe645 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java @@ -23,14 +23,14 @@ public class SetPortForwardingRulesAnswer extends Answer { protected SetPortForwardingRulesAnswer() { super(); } - + public SetPortForwardingRulesAnswer(SetPortForwardingRulesCommand cmd, String[] results, boolean success) { super(cmd, success, null); - + assert(cmd.getRules().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java index dc820431e36..a7bf37f83ef 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java @@ -25,7 +25,7 @@ public class SetPortForwardingRulesCommand extends NetworkElementCommand { protected SetPortForwardingRulesCommand() { } - + public SetPortForwardingRulesCommand(List pfRules) { rules = new PortForwardingRuleTO[pfRules.size()]; int i = 0; @@ -33,7 +33,7 @@ public class SetPortForwardingRulesCommand extends NetworkElementCommand { rules[i++] = rule; } } - + public PortForwardingRuleTO[] getRules() { return rules; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java index 042e788b4ce..7228457d890 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java @@ -23,7 +23,7 @@ import com.cloud.agent.api.to.PortForwardingRuleTO; public class SetPortForwardingRulesVpcCommand extends SetPortForwardingRulesCommand{ protected SetPortForwardingRulesVpcCommand() { } - + public SetPortForwardingRulesVpcCommand(List pfRules) { super(pfRules); } diff --git a/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java b/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java index 165a15d5640..96aa001de84 100644 --- a/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java @@ -21,10 +21,10 @@ import com.cloud.agent.api.to.IpAddressTO; public class SetSourceNatCommand extends NetworkElementCommand{ IpAddressTO ipAddress; boolean add; - + protected SetSourceNatCommand() { } - + public SetSourceNatCommand(IpAddressTO ip, boolean add) { this.ipAddress = ip; this.add = add; @@ -38,5 +38,5 @@ public class SetSourceNatCommand extends NetworkElementCommand{ public IpAddressTO getIpAddress() { return ipAddress; } - + } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java index e57b3277850..9b5d09b25c5 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java @@ -23,14 +23,14 @@ public class SetStaticNatRulesAnswer extends Answer { protected SetStaticNatRulesAnswer() { super(); } - + public SetStaticNatRulesAnswer(SetStaticNatRulesCommand cmd, String[] results, boolean success) { super(cmd, success, null); - + assert(cmd.getRules().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java index c28032ccdfb..852d16167ab 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java @@ -21,13 +21,13 @@ import java.util.List; import com.cloud.agent.api.to.StaticNatRuleTO; public class SetStaticNatRulesCommand extends NetworkElementCommand{ - + StaticNatRuleTO[] rules; Long vpcId; protected SetStaticNatRulesCommand() { } - + public SetStaticNatRulesCommand(List staticNatRules, Long vpcId) { rules = new StaticNatRuleTO[staticNatRules.size()]; int i = 0; @@ -36,7 +36,7 @@ public class SetStaticNatRulesCommand extends NetworkElementCommand{ } this.vpcId = vpcId; } - + public StaticNatRuleTO[] getRules() { return rules; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java b/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java index c13bda060e2..76f5bb96b1e 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java @@ -20,16 +20,16 @@ import com.cloud.agent.api.Answer; public class SetStaticRouteAnswer extends Answer{ String[] results; - + protected SetStaticRouteAnswer() { } - + public SetStaticRouteAnswer(SetStaticRouteCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getStaticRoutes().length == results.length) : "Static routes and their results should be the same length"; this.results = results; } - + public String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java b/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java index 0c91a9efa74..c9c2056816b 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java @@ -27,12 +27,12 @@ import com.cloud.utils.net.NetUtils; public class SetStaticRouteCommand extends NetworkElementCommand{ StaticRouteProfile[] staticRoutes; - + protected SetStaticRouteCommand() { } - + public SetStaticRouteCommand(List staticRoutes) { - this.staticRoutes = staticRoutes.toArray(new StaticRouteProfile[staticRoutes.size()]); + this.staticRoutes = staticRoutes.toArray(new StaticRouteProfile[staticRoutes.size()]); } public StaticRouteProfile[] getStaticRoutes() { diff --git a/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java b/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java index 97db2f96cc3..83163039f51 100644 --- a/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -30,16 +30,16 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { private long ikeLifetime; private long espLifetime; private boolean dpd; - + @Override public boolean executeInSequence() { return true; } - + public Site2SiteVpnCfgCommand () { this.create = false; } - + public Site2SiteVpnCfgCommand (boolean create, String localPublicIp, String localPublicGateway, String localGuestCidr, String peerGatewayIp, String peerGuestCidrList, String ikePolicy, String espPolicy, String ipsecPsk, Long ikeLifetime, Long espLifetime, Boolean dpd) { this.create = create; @@ -55,11 +55,11 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { this.espLifetime = espLifetime; this.dpd = dpd; } - + public boolean isCreate() { return create; } - + public void setCreate(boolean create) { this.create = create; } diff --git a/api/src/com/cloud/agent/api/routing/UserDataCommand.java b/api/src/com/cloud/agent/api/routing/UserDataCommand.java index 103bd91f804..f7b38c8c364 100644 --- a/api/src/com/cloud/agent/api/routing/UserDataCommand.java +++ b/api/src/com/cloud/agent/api/routing/UserDataCommand.java @@ -23,31 +23,31 @@ public class UserDataCommand extends NetworkElementCommand { String vmIpAddress; String routerPrivateIpAddress; String vmName; - + protected UserDataCommand() { - + } - + @Override public boolean executeInSequence() { return true; } - + public UserDataCommand(String userData, String vmIpAddress, String routerPrivateIpAddress, String vmName) { this.userData = userData; this.vmIpAddress = vmIpAddress; this.routerPrivateIpAddress = routerPrivateIpAddress; this.vmName = vmName; } - + public String getRouterPrivateIpAddress() { return routerPrivateIpAddress; } - + public String getVmIpAddress() { return vmIpAddress; } - + public String getVmName() { return vmName; } @@ -59,5 +59,5 @@ public class UserDataCommand extends NetworkElementCommand { public void setUserData(String userData) { this.userData = userData; } - + } diff --git a/api/src/com/cloud/agent/api/routing/VmDataCommand.java b/api/src/com/cloud/agent/api/routing/VmDataCommand.java index d5053840e0b..df882554479 100644 --- a/api/src/com/cloud/agent/api/routing/VmDataCommand.java +++ b/api/src/com/cloud/agent/api/routing/VmDataCommand.java @@ -23,24 +23,24 @@ import com.cloud.agent.api.LogLevel; import com.cloud.agent.api.LogLevel.Log4jLevel; public class VmDataCommand extends NetworkElementCommand { - + String vmIpAddress; String vmName; @LogLevel(Log4jLevel.Trace) List vmData; - + protected VmDataCommand() { } - + @Override public boolean executeInSequence() { return true; } - + public VmDataCommand(String vmIpAddress) { this(vmIpAddress, null); } - + public String getVmName() { return vmName; } @@ -50,18 +50,18 @@ public class VmDataCommand extends NetworkElementCommand { this.vmIpAddress = vmIpAddress; this.vmData = new ArrayList(); } - - + + public String getVmIpAddress() { return vmIpAddress; } - + public List getVmData() { return vmData; } - + public void addVmData(String folder, String file, String contents) { vmData.add(new String[]{folder, file, contents}); } - + } diff --git a/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java b/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java index 249c2358d2f..ebe725d2911 100644 --- a/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java @@ -23,12 +23,12 @@ import com.cloud.network.VpnUser; public class VpnUsersCfgCommand extends NetworkElementCommand { - public static class UsernamePassword{ + public static class UsernamePassword{ private String username; @LogLevel(Log4jLevel.Off) private String password; boolean add = true; - + public boolean isAdd() { return add; } @@ -66,11 +66,11 @@ public class VpnUsersCfgCommand extends NetworkElementCommand { } } UsernamePassword [] userpwds; - + protected VpnUsersCfgCommand() { - + } - + public VpnUsersCfgCommand(List addUsers, List removeUsers) { userpwds = new UsernamePassword[addUsers.size() + removeUsers.size()]; int i = 0; @@ -86,7 +86,7 @@ public class VpnUsersCfgCommand extends NetworkElementCommand { public boolean executeInSequence() { return true; } - + public UsernamePassword[] getUserpwds() { return userpwds; } diff --git a/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java b/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java index 5737a05d98b..04b3d4360d5 100644 --- a/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java @@ -24,46 +24,46 @@ public abstract class AbstractDownloadCommand extends ssCommand { private ImageFormat format; private long accountId; private String name; - + protected AbstractDownloadCommand() { } - + protected AbstractDownloadCommand(String name, String url, ImageFormat format, long accountId) { assert(url != null); url = url.replace('\\', '/'); - + this.url = url; this.format = format; this.accountId = accountId; this.name = name; } - + protected AbstractDownloadCommand(AbstractDownloadCommand that) { super(that); assert(that.url != null); - + this.url = that.url.replace('\\', '/'); this.format = that.format; this.accountId = that.accountId; this.name = that.name; } - + public String getUrl() { return url; } - + public String getName() { return name; } - + public ImageFormat getFormat() { return format; } - + public long getAccountId() { return accountId; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java b/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java index 1c55e8fafd6..49c04b16a81 100644 --- a/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java +++ b/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java @@ -25,37 +25,37 @@ public class AbstractUploadCommand extends StorageCommand{ private ImageFormat format; private long accountId; private String name; - + protected AbstractUploadCommand() { } - + protected AbstractUploadCommand(String name, String url, ImageFormat format, long accountId) { this.url = url; this.format = format; this.accountId = accountId; this.name = name; } - + protected AbstractUploadCommand(AbstractUploadCommand that) { this(that.name, that.url, that.format, that.accountId); } - + public String getUrl() { return url; } - + public String getName() { return name; } - + public ImageFormat getFormat() { return format; } - + public long getAccountId() { return accountId; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java index 7704569b37a..8c55ac3eecc 100644 --- a/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java @@ -22,20 +22,20 @@ import com.cloud.agent.api.Command; public class CopyVolumeAnswer extends Answer { private String volumeFolder; private String volumePath; - + protected CopyVolumeAnswer() { } - + public CopyVolumeAnswer(Command command, boolean success, String details, String volumeFolder, String volumePath) { super(command, success, details); this.volumeFolder = volumeFolder; this.volumePath = volumePath; } - + public String getVolumeFolder() { return volumeFolder; } - + public String getVolumePath() { return volumePath; } diff --git a/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java b/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java index 26bd1871138..3d05e9ba69c 100644 --- a/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java @@ -23,49 +23,49 @@ import com.cloud.storage.StoragePool; public class CopyVolumeCommand extends Command { long volumeId; - String volumePath; + String volumePath; StorageFilerTO pool; String secondaryStorageURL; boolean toSecondaryStorage; String vmName; - - public CopyVolumeCommand() { + + public CopyVolumeCommand() { } - + public CopyVolumeCommand(long volumeId, String volumePath, StoragePool pool, String secondaryStorageURL, boolean toSecondaryStorage, int wait) { this.volumeId = volumeId; - this.volumePath = volumePath; + this.volumePath = volumePath; this.pool = new StorageFilerTO(pool); this.secondaryStorageURL = secondaryStorageURL; this.toSecondaryStorage = toSecondaryStorage; setWait(wait); } - + @Override public boolean executeInSequence() { return true; } - + public String getVolumePath() { return volumePath; } - + public long getVolumeId() { return volumeId; } - + public StorageFilerTO getPool() { return pool; } - + public String getSecondaryStorageURL() { return secondaryStorageURL; } - + public boolean toSecondaryStorage() { return toSecondaryStorage; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/storage/CreateAnswer.java b/api/src/com/cloud/agent/api/storage/CreateAnswer.java index 695b6bad316..ab6cc038604 100644 --- a/api/src/com/cloud/agent/api/storage/CreateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreateAnswer.java @@ -24,29 +24,29 @@ public class CreateAnswer extends Answer { boolean requestTemplateReload = false; protected CreateAnswer() { } - + public CreateAnswer(CreateCommand cmd, VolumeTO volume) { super(cmd, true, null); this.volume = volume; } - + public CreateAnswer(CreateCommand cmd, String details) { super(cmd, false, details); } - + public CreateAnswer(CreateCommand cmd, String details, boolean requestTemplateReload) { super(cmd, false, details); this.requestTemplateReload = requestTemplateReload; } - + public CreateAnswer(CreateCommand cmd, Exception e) { super(cmd, e); } - + public VolumeTO getVolume() { return volume; } - + public boolean templateReloadRequested() { return requestTemplateReload; } diff --git a/api/src/com/cloud/agent/api/storage/CreateCommand.java b/api/src/com/cloud/agent/api/storage/CreateCommand.java index b8b2446216d..fd0375aa6e7 100644 --- a/api/src/com/cloud/agent/api/storage/CreateCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreateCommand.java @@ -26,14 +26,14 @@ public class CreateCommand extends Command { private StorageFilerTO pool; private DiskProfile diskCharacteristics; private String templateUrl; - + protected CreateCommand() { super(); } /** * Construction for template based volumes. - * + * * @param vol * @param vm * @param diskCharacteristics @@ -47,7 +47,7 @@ public class CreateCommand extends Command { /** * Construction for regular volumes. - * + * * @param vol * @param vm * @param diskCharacteristics @@ -55,19 +55,19 @@ public class CreateCommand extends Command { */ public CreateCommand(DiskProfile diskCharacteristics, StorageFilerTO pool) { this.volId = diskCharacteristics.getVolumeId(); - this.diskCharacteristics = diskCharacteristics; + this.diskCharacteristics = diskCharacteristics; this.pool = pool; this.templateUrl = null; } - + public CreateCommand(DiskProfile diskCharacteristics, String templateUrl, StoragePool pool) { this(diskCharacteristics, templateUrl, new StorageFilerTO(pool)); } - + public CreateCommand(DiskProfile diskCharacteristics, StoragePool pool) { this(diskCharacteristics, new StorageFilerTO(pool)); } - + @Override public boolean executeInSequence() { return true; @@ -76,19 +76,19 @@ public class CreateCommand extends Command { public String getTemplateUrl() { return templateUrl; } - + public StorageFilerTO getPool() { return pool; } - + public DiskProfile getDiskCharacteristics() { return diskCharacteristics; } - + public long getVolumeId() { return volId; } - + @Deprecated public String getInstanceName() { return null; diff --git a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java index 550a9490e90..808a67f994f 100644 --- a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java @@ -19,19 +19,19 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Answer; public class CreateEntityDownloadURLAnswer extends Answer{ - + String resultString; short resultCode; public static final short RESULT_SUCCESS = 1; public static final short RESULT_FAILURE = 0; - + public CreateEntityDownloadURLAnswer(String resultString, short resultCode) { super(); this.resultString = resultString; this.resultCode = resultCode; - } - - public CreateEntityDownloadURLAnswer(){ + } + + public CreateEntityDownloadURLAnswer(){ } } diff --git a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java index f32002257ca..c80179a0560 100755 --- a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java @@ -26,7 +26,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { this.installPath = installPath; this.extractLinkUUID = uuid; } - + public CreateEntityDownloadURLCommand(String installPath, String uuid) { super(); this.parent = parent; @@ -40,7 +40,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { private String installPath; private String parent; private String extractLinkUUID; - + @Override public boolean executeInSequence() { return false; @@ -53,7 +53,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { public void setInstallPath(String installPath) { this.installPath = installPath; } - + public String getParent() { return parent; } diff --git a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java index 2dfcf211c0f..83db84d8b87 100644 --- a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java @@ -29,7 +29,7 @@ public class CreatePrivateTemplateAnswer extends Answer { public CreatePrivateTemplateAnswer() {} - public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result, String path, long virtualSize, + public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result, String path, long virtualSize, long physicalSize, String uniqueName, ImageFormat format) { super(cmd, success, result); _path = path; @@ -42,23 +42,23 @@ public class CreatePrivateTemplateAnswer extends Answer { public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result) { super(cmd, success, result); } - + public String getPath() { return _path; } - + public void setPath(String path) { _path = path; } - + public long getVirtualSize() { return _virtualSize; } - + public void setVirtualSize(long virtualSize) { _virtualSize = virtualSize; } - + public void setphysicalSize(long _physicalSize) { this._physicalSize = _physicalSize; } @@ -70,7 +70,7 @@ public class CreatePrivateTemplateAnswer extends Answer { public String getUniqueName() { return _uniqueName; } - + public ImageFormat getImageFormat() { return _format; } diff --git a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java index 5fd186cb37f..d392a89ec38 100644 --- a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java @@ -24,7 +24,7 @@ public class CreatePrivateTemplateCommand extends StorageCommand { private String _uniqueName; private long _templateId; private long _accountId; - + // For XenServer private String _secondaryStorageURL; private String _snapshotName; @@ -44,10 +44,10 @@ public class CreatePrivateTemplateCommand extends StorageCommand { } @Override - public boolean executeInSequence() { + public boolean executeInSequence() { return false; } - + public String getSecondaryStorageURL() { return _secondaryStorageURL; } @@ -67,23 +67,23 @@ public class CreatePrivateTemplateCommand extends StorageCommand { public String getSnapshotPath() { return _snapshotPath; } - + public String getSnapshotName() { return _snapshotName; } - + public String getUserFolder() { return _userFolder; } - + public long getTemplateId() { return _templateId; } - + public long getAccountId() { return _accountId; } - + public void setTemplateId(long templateId) { _templateId = templateId; } diff --git a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java index 69a2b495a30..c6fdf3cb6fe 100644 --- a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java @@ -19,19 +19,19 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Answer; public class DeleteEntityDownloadURLAnswer extends Answer{ - + String resultString; short resultCode; public static final short RESULT_SUCCESS = 1; public static final short RESULT_FAILURE = 0; - + public DeleteEntityDownloadURLAnswer(String resultString, short resultCode) { super(); this.resultString = resultString; this.resultCode = resultCode; - } - - public DeleteEntityDownloadURLAnswer(){ + } + + public DeleteEntityDownloadURLAnswer(){ } } diff --git a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java index 772e6c6b251..fbfacb97c85 100755 --- a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java @@ -19,9 +19,9 @@ package com.cloud.agent.api.storage; import com.cloud.storage.Upload; public class DeleteEntityDownloadURLCommand extends AbstractDownloadCommand { - + private String path; - private String extractUrl; + private String extractUrl; private Upload.Type type; private String parentPath; diff --git a/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java b/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java index ce349dda522..69f465c6b16 100644 --- a/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java @@ -21,19 +21,19 @@ public class DeleteTemplateCommand extends ssCommand { private String templatePath; - public DeleteTemplateCommand() { + public DeleteTemplateCommand() { } - + public DeleteTemplateCommand(String secUrl, String templatePath) { this.setSecUrl(secUrl); this.templatePath = templatePath; } - + @Override public boolean executeInSequence() { return true; } - + public String getTemplatePath() { return templatePath; } diff --git a/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java b/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java index ea729e81bda..949af010423 100755 --- a/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -public class DeleteVolumeCommand extends ssCommand { - private String volumePath; - - public DeleteVolumeCommand() { - } - - public DeleteVolumeCommand(String secUrl, String volumePath) { - this.setSecUrl(secUrl); - this.volumePath = volumePath; - } - - @Override - public boolean executeInSequence() { - return true; - } - - public String getVolumePath() { - return volumePath; - } -} +package com.cloud.agent.api.storage; + +public class DeleteVolumeCommand extends ssCommand { + private String volumePath; + + public DeleteVolumeCommand() { + } + + public DeleteVolumeCommand(String secUrl, String volumePath) { + this.setSecUrl(secUrl); + this.volumePath = volumePath; + } + + @Override + public boolean executeInSequence() { + return true; + } + + public String getVolumePath() { + return volumePath; + } +} diff --git a/api/src/com/cloud/agent/api/storage/DestroyAnswer.java b/api/src/com/cloud/agent/api/storage/DestroyAnswer.java index 2f01c1bcd28..ac60015944f 100644 --- a/api/src/com/cloud/agent/api/storage/DestroyAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DestroyAnswer.java @@ -22,7 +22,7 @@ public class DestroyAnswer extends Answer { public DestroyAnswer(DestroyCommand cmd, boolean result, String details) { super(cmd, result, details); } - + // Constructor for gson. protected DestroyAnswer() { super(); diff --git a/api/src/com/cloud/agent/api/storage/DestroyCommand.java b/api/src/com/cloud/agent/api/storage/DestroyCommand.java index 29c564c3bc3..6732ea59c23 100755 --- a/api/src/com/cloud/agent/api/storage/DestroyCommand.java +++ b/api/src/com/cloud/agent/api/storage/DestroyCommand.java @@ -25,25 +25,25 @@ public class DestroyCommand extends StorageCommand { // in VMware, things are designed around VM instead of volume, we need it the volume VM context if the volume is attached String vmName; VolumeTO volume; - + protected DestroyCommand() { } - + public DestroyCommand(StoragePool pool, Volume volume, String vmName) { this.volume = new VolumeTO(volume, pool); this.vmName = vmName; } - + public DestroyCommand(StoragePool pool, VMTemplateStorageResourceAssoc templatePoolRef) { - volume = new VolumeTO(templatePoolRef.getId(), null, pool.getPoolType(), pool.getUuid(), - null, pool.getPath(), templatePoolRef.getInstallPath(), + volume = new VolumeTO(templatePoolRef.getId(), null, pool.getPoolType(), pool.getUuid(), + null, pool.getPath(), templatePoolRef.getInstallPath(), templatePoolRef.getTemplateSize(), null); } - + public VolumeTO getVolume() { return volume; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/storage/DownloadAnswer.java b/api/src/com/cloud/agent/api/storage/DownloadAnswer.java index 52c32455d80..bb7b8a9239c 100755 --- a/api/src/com/cloud/agent/api/storage/DownloadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DownloadAnswer.java @@ -33,40 +33,40 @@ public class DownloadAnswer extends Answer { private long templateSize = 0L; private long templatePhySicalSize = 0L; private String checkSum; - + public String getCheckSum() { return checkSum; } - + public int getDownloadPct() { return downloadPct; } public String getErrorString() { return errorString; } - + public String getDownloadStatusString() { return downloadStatus.toString(); } - + public VMTemplateStorageResourceAssoc.Status getDownloadStatus() { return downloadStatus; } - + public String getDownloadPath() { return downloadPath; } protected DownloadAnswer() { - + } - + public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } - + public DownloadAnswer(String errorString, Status status) { super(); this.downloadPct = 0; @@ -74,7 +74,7 @@ public class DownloadAnswer extends Answer { this.downloadStatus = status; this.details = errorString; } - + public DownloadAnswer(String jobId, int downloadPct, String errorString, Status downloadStatus, String fileSystemPath, String installPath, long templateSize, long templatePhySicalSize, String checkSum) { super(); @@ -89,7 +89,7 @@ public class DownloadAnswer extends Answer { this.templatePhySicalSize = templatePhySicalSize; this.checkSum = checkSum; } - + public DownloadAnswer(String jobId, int downloadPct, Command command, Status downloadStatus, String fileSystemPath, String installPath) { super(command); @@ -99,7 +99,7 @@ public class DownloadAnswer extends Answer { this.downloadPath = fileSystemPath; this.installPath = installPath; } - + private static String fixPath(String path){ if (path == null) { return path; @@ -112,11 +112,11 @@ public class DownloadAnswer extends Answer { } return path; } - + public void setDownloadStatus(VMTemplateStorageResourceAssoc.Status downloadStatus) { this.downloadStatus = downloadStatus; } - + public String getInstallPath() { return installPath; } @@ -127,7 +127,7 @@ public class DownloadAnswer extends Answer { public void setTemplateSize(long templateSize) { this.templateSize = templateSize; } - + public Long getTemplateSize() { return templateSize; } @@ -137,5 +137,5 @@ public class DownloadAnswer extends Answer { public long getTemplatePhySicalSize() { return templatePhySicalSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/DownloadCommand.java b/api/src/com/cloud/agent/api/storage/DownloadCommand.java index af9ff40b0f2..efb5ecb5256 100644 --- a/api/src/com/cloud/agent/api/storage/DownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/DownloadCommand.java @@ -21,14 +21,15 @@ import java.net.URI; import com.cloud.storage.Volume; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class DownloadCommand extends AbstractDownloadCommand { +public class DownloadCommand extends AbstractDownloadCommand implements InternalIdentity { public static class PasswordAuth { String userName; String password; public PasswordAuth() { - + } public PasswordAuth(String user, String password) { this.userName = user; @@ -41,28 +42,28 @@ public class DownloadCommand extends AbstractDownloadCommand { return password; } } - + public static enum ResourceType { VOLUME, TEMPLATE } - + public static class Proxy { private String _host; private int _port; private String _userName; private String _password; - + public Proxy() { - + } - + public Proxy(String host, int port, String userName, String password) { this._host = host; this._port = port; this._userName = userName; this._password = password; } - + public Proxy(URI uri) { this._host = uri.getHost(); this._port = uri.getPort() == -1 ? 3128 : uri.getPort(); @@ -78,19 +79,19 @@ public class DownloadCommand extends AbstractDownloadCommand { } } } - + public String getHost() { return _host; } - + public int getPort() { return _port; } - + public String getUserName() { return _userName; } - + public String getPassword() { return _password; } @@ -103,11 +104,11 @@ public class DownloadCommand extends AbstractDownloadCommand { private Long maxDownloadSizeInBytes = null; private long id; private ResourceType resourceType = ResourceType.TEMPLATE; - + protected DownloadCommand() { } - - + + public DownloadCommand(DownloadCommand that) { super(that); this.hvm = that.hvm; @@ -119,7 +120,7 @@ public class DownloadCommand extends AbstractDownloadCommand { this.maxDownloadSizeInBytes = that.getMaxDownloadSizeInBytes(); this.resourceType = that.resourceType; } - + public DownloadCommand(String secUrl, VirtualMachineTemplate template, Long maxDownloadSizeInBytes) { super(template.getUniqueName(), template.getUrl(), template.getFormat(), template.getAccountId()); this.hvm = template.isRequiresHvm(); @@ -129,7 +130,7 @@ public class DownloadCommand extends AbstractDownloadCommand { this.setSecUrl(secUrl); this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; } - + public DownloadCommand(String secUrl, Volume volume, Long maxDownloadSizeInBytes, String checkSum, String url, ImageFormat format) { super(volume.getName(), url, format, volume.getAccountId()); //this.hvm = volume.isRequiresHvm(); @@ -150,11 +151,11 @@ public class DownloadCommand extends AbstractDownloadCommand { this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; auth = new PasswordAuth(user, passwd); } - + public long getId() { return id; } - + public void setHvm(boolean hvm) { this.hvm = hvm; } @@ -188,19 +189,19 @@ public class DownloadCommand extends AbstractDownloadCommand { public PasswordAuth getAuth() { return auth; } - + public void setCreds(String userName, String passwd) { auth = new PasswordAuth(userName, passwd); } - + public Proxy getProxy() { return _proxy; } - + public void setProxy(Proxy proxy) { _proxy = proxy; } - + public Long getMaxDownloadSizeInBytes() { return maxDownloadSizeInBytes; } diff --git a/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java b/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java index 205ba801527..835847bedeb 100644 --- a/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java +++ b/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java @@ -26,7 +26,7 @@ public class DownloadProgressCommand extends DownloadCommand { protected DownloadProgressCommand() { super(); } - + public DownloadProgressCommand(DownloadCommand cmd, String jobId, RequestType req) { super(cmd); diff --git a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java index 45622faffd3..06e95fe4265 100644 --- a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java @@ -25,17 +25,17 @@ import com.cloud.storage.template.TemplateInfo; public class ListTemplateAnswer extends Answer { private String secUrl; private Map templateInfos; - + public ListTemplateAnswer() { - + } - + public ListTemplateAnswer(String secUrl, Map templateInfos) { super(null, true, "success"); this.setSecUrl(secUrl); - this.templateInfos = templateInfos; + this.templateInfos = templateInfos; } - + public Map getTemplateInfo() { return templateInfos; } diff --git a/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java b/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java index 18123fa1997..da25ed56bf3 100644 --- a/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java @@ -24,15 +24,15 @@ public class ListTemplateCommand extends StorageCommand { private String secUrl; @LogLevel(Log4jLevel.Off) private SwiftTO swift; - + public ListTemplateCommand() { } - + public ListTemplateCommand(String secUrl) { this.secUrl = secUrl; this.swift = null; } - + public ListTemplateCommand(SwiftTO swift) { this.secUrl = null; this.swift = swift; diff --git a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java index e2dc447ec6d..6bbb2e82c33 100755 --- a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java @@ -14,40 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -import java.util.Map; - -import com.cloud.agent.api.Answer; -import com.cloud.storage.template.TemplateInfo; - -public class ListVolumeAnswer extends Answer { - private String secUrl; - private Map templateInfos; - - public ListVolumeAnswer() { - - } - - public ListVolumeAnswer(String secUrl, Map templateInfos) { - super(null, true, "success"); - this.setSecUrl(secUrl); - this.templateInfos = templateInfos; - } - - public Map getTemplateInfo() { - return templateInfos; - } - - public void setTemplateInfo(Map templateInfos) { - this.templateInfos = templateInfos; - } - - public void setSecUrl(String secUrl) { - this.secUrl = secUrl; - } - - public String getSecUrl() { - return secUrl; - } -} +package com.cloud.agent.api.storage; + +import java.util.Map; + +import com.cloud.agent.api.Answer; +import com.cloud.storage.template.TemplateInfo; + +public class ListVolumeAnswer extends Answer { + private String secUrl; + private Map templateInfos; + + public ListVolumeAnswer() { + + } + + public ListVolumeAnswer(String secUrl, Map templateInfos) { + super(null, true, "success"); + this.setSecUrl(secUrl); + this.templateInfos = templateInfos; + } + + public Map getTemplateInfo() { + return templateInfos; + } + + public void setTemplateInfo(Map templateInfos) { + this.templateInfos = templateInfos; + } + + public void setSecUrl(String secUrl) { + this.secUrl = secUrl; + } + + public String getSecUrl() { + return secUrl; + } +} diff --git a/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java b/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java index afec624b984..a2776c2af46 100755 --- a/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java @@ -14,30 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -import com.cloud.agent.api.LogLevel; -import com.cloud.agent.api.LogLevel.Log4jLevel; -import com.cloud.agent.api.to.SwiftTO; - -public class ListVolumeCommand extends StorageCommand { - - private String secUrl; - - public ListVolumeCommand() { - } - - public ListVolumeCommand(String secUrl) { - this.secUrl = secUrl; - } - - @Override - public boolean executeInSequence() { - return true; - } - - public String getSecUrl() { - return secUrl; - } - -} +package com.cloud.agent.api.storage; + +import com.cloud.agent.api.LogLevel; +import com.cloud.agent.api.LogLevel.Log4jLevel; +import com.cloud.agent.api.to.SwiftTO; + +public class ListVolumeCommand extends StorageCommand { + + private String secUrl; + + public ListVolumeCommand() { + } + + public ListVolumeCommand(String secUrl) { + this.secUrl = secUrl; + } + + @Override + public boolean executeInSequence() { + return true; + } + + public String getSecUrl() { + return secUrl; + } + +} diff --git a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java index 354a693ee9d..edd283090b1 100644 --- a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java @@ -20,12 +20,12 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; public class ManageVolumeAvailabilityAnswer extends Answer { - + protected ManageVolumeAvailabilityAnswer() { } - + public ManageVolumeAvailabilityAnswer(Command command, boolean success, String details) { super(command, success, details); } - + } diff --git a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java index e27fe8ce2b3..1a7d4807f28 100644 --- a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java +++ b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java @@ -19,36 +19,36 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Command; public class ManageVolumeAvailabilityCommand extends Command { - + boolean attach; String primaryStorageSRUuid; String volumeUuid; - - - public ManageVolumeAvailabilityCommand() { + + + public ManageVolumeAvailabilityCommand() { } - + public ManageVolumeAvailabilityCommand(boolean attach, String primaryStorageSRUuid, String volumeUuid) { this.attach = attach; this.primaryStorageSRUuid = primaryStorageSRUuid; this.volumeUuid = volumeUuid; } - + @Override public boolean executeInSequence() { return false; } - + public boolean getAttach() { return attach; } - + public String getPrimaryStorageSRUuid() { return primaryStorageSRUuid; } - + public String getVolumeUuid() { return volumeUuid; } - + } diff --git a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java index 3d5c55645ae..a5a6c49e9ab 100644 --- a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java @@ -21,24 +21,24 @@ import com.cloud.agent.api.Answer; public class PrimaryStorageDownloadAnswer extends Answer { private String installPath; private long templateSize = 0L; - + protected PrimaryStorageDownloadAnswer() { } - + public PrimaryStorageDownloadAnswer(String detail) { super(null, false, detail); } - + public PrimaryStorageDownloadAnswer(String installPath, long templateSize ) { super(null); this.installPath = installPath; - this.templateSize = templateSize; + this.templateSize = templateSize; } - + public String getInstallPath() { return installPath; } - + public void setInstallPath(String installPath) { this.installPath = installPath; } @@ -50,5 +50,5 @@ public class PrimaryStorageDownloadAnswer extends Answer { public Long getTemplateSize() { return templateSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java index f66d00eb8cb..b450041597f 100644 --- a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java @@ -27,8 +27,9 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { String localPath; String poolUuid; long poolId; - StorageFilerTO primaryPool; - + + StorageFilerTO primaryPool; + String secondaryStorageUrl; String primaryStorageUrl; @@ -42,11 +43,11 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { this.primaryPool = new StorageFilerTO(pool); setWait(wait); } - + public String getPoolUuid() { return poolUuid; } - + public long getPoolId() { return poolId; } @@ -58,27 +59,27 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { public void setLocalPath(String path) { this.localPath = path; } - + public String getLocalPath() { return localPath; } - + public void setSecondaryStorageUrl(String url) { secondaryStorageUrl = url; } - + public String getSecondaryStorageUrl() { return secondaryStorageUrl; } - + public void setPrimaryStorageUrl(String url) { primaryStorageUrl = url; } - + public String getPrimaryStorageUrl() { return primaryStorageUrl; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/ResizeVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/ResizeVolumeAnswer.java new file mode 100644 index 00000000000..3434b985aaa --- /dev/null +++ b/api/src/com/cloud/agent/api/storage/ResizeVolumeAnswer.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api.storage; + +import com.cloud.agent.api.Answer; + +public class ResizeVolumeAnswer extends Answer { + private long newSize; + + protected ResizeVolumeAnswer() { + + } + + public ResizeVolumeAnswer(ResizeVolumeCommand cmd, boolean result, String details, long newSize) { + super(cmd, result, details); + this.newSize = newSize; + } + + public ResizeVolumeAnswer(ResizeVolumeCommand cmd, boolean result, String details) { + super(cmd, result, details); + } + + public long getNewSize() { + return newSize; + } +} diff --git a/api/src/com/cloud/agent/api/storage/ResizeVolumeCommand.java b/api/src/com/cloud/agent/api/storage/ResizeVolumeCommand.java new file mode 100644 index 00000000000..8af23a0ab81 --- /dev/null +++ b/api/src/com/cloud/agent/api/storage/ResizeVolumeCommand.java @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api.storage; + +import com.cloud.agent.api.Command; +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.storage.StoragePool; + +public class ResizeVolumeCommand extends Command { + private String path; + private StorageFilerTO pool; + private String vmInstance; + private Long newSize; + private Long currentSize; + private boolean shrinkOk; + + protected ResizeVolumeCommand() { + + } + + public ResizeVolumeCommand(String path, + StorageFilerTO pool, + Long currentSize, + Long newSize, + boolean shrinkOk, + String vmInstance) + { + this.path = path; + this.pool = pool; + this.vmInstance = vmInstance; + this.currentSize = currentSize; + this.newSize = newSize; + this.shrinkOk = shrinkOk; + } + + public String getPath() { + return path; + } + + public String getPoolUuid() { + return pool.getUuid(); + } + + public StorageFilerTO getPool() { + return pool; + } + + public long getNewSize() { + return newSize; + } + + public long getCurrentSize() { + return currentSize; + } + + public boolean getShrinkOk() { + return shrinkOk; + } + + public String getInstanceName() { + return vmInstance; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean executeInSequence() { + return false; + } + +} diff --git a/api/src/com/cloud/agent/api/storage/UploadAnswer.java b/api/src/com/cloud/agent/api/storage/UploadAnswer.java index 430eb83c9b0..f2d9788e8dc 100755 --- a/api/src/com/cloud/agent/api/storage/UploadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/UploadAnswer.java @@ -24,7 +24,7 @@ import com.cloud.storage.Upload; public class UploadAnswer extends Answer { - + private String jobId; private int uploadPct; private String errorString; @@ -32,29 +32,29 @@ public class UploadAnswer extends Answer { private String uploadPath; private String installPath; public Long templateSize = 0L; - + public int getUploadPct() { return uploadPct; } public String getErrorString() { return errorString; } - + public String getUploadStatusString() { return uploadStatus.toString(); } - + public Upload.Status getUploadStatus() { return uploadStatus; } - + public String getUploadPath() { return uploadPath; } protected UploadAnswer() { - + } - + public void setErrorString(String errorString) { this.errorString = errorString; } @@ -64,7 +64,7 @@ public class UploadAnswer extends Answer { public void setJobId(String jobId) { this.jobId = jobId; } - + public UploadAnswer(String jobId, int uploadPct, String errorString, Upload.Status uploadStatus, String fileSystemPath, String installPath, long templateSize) { super(); @@ -87,7 +87,7 @@ public class UploadAnswer extends Answer { this.uploadPath = fileSystemPath; this.installPath = installPath; } - + private static String fixPath(String path){ if (path == null) { return path; @@ -100,11 +100,11 @@ public class UploadAnswer extends Answer { } return path; } - + public void setUploadStatus(Upload.Status uploadStatus) { this.uploadStatus = uploadStatus; } - + public String getInstallPath() { return installPath; } @@ -115,9 +115,9 @@ public class UploadAnswer extends Answer { public void setTemplateSize(long templateSize) { this.templateSize = templateSize; } - + public Long getTemplateSize() { return templateSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/UploadCommand.java b/api/src/com/cloud/agent/api/storage/UploadCommand.java index 4b004c91ed7..2a7c60a51ff 100644 --- a/api/src/com/cloud/agent/api/storage/UploadCommand.java +++ b/api/src/com/cloud/agent/api/storage/UploadCommand.java @@ -20,13 +20,14 @@ import com.cloud.agent.api.storage.DownloadCommand.PasswordAuth; import com.cloud.agent.api.to.TemplateTO; import com.cloud.storage.Upload.Type; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class UploadCommand extends AbstractUploadCommand { +public class UploadCommand extends AbstractUploadCommand implements InternalIdentity { private TemplateTO template; private String url; - private String installPath; + private String installPath; private boolean hvm; private String description; private String checksum; @@ -36,16 +37,16 @@ public class UploadCommand extends AbstractUploadCommand { private Type type; public UploadCommand(VirtualMachineTemplate template, String url, String installPath, long sizeInBytes) { - + this.template = new TemplateTO(template); this.url = url; this.installPath = installPath; this.checksum = template.getChecksum(); this.id = template.getId(); this.templateSizeInBytes = sizeInBytes; - + } - + public UploadCommand(String url, long id, long sizeInBytes, String installPath, Type type){ this.template = null; this.url = url; @@ -54,10 +55,10 @@ public class UploadCommand extends AbstractUploadCommand { this.type = type; this.templateSizeInBytes = sizeInBytes; } - + protected UploadCommand() { } - + public UploadCommand(UploadCommand that) { this.template = that.template; this.url = that.url; diff --git a/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java b/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java index 36b1437ef90..7f6d584045d 100644 --- a/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java +++ b/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java @@ -25,7 +25,7 @@ public class UploadProgressCommand extends UploadCommand { protected UploadProgressCommand() { super(); } - + public UploadProgressCommand(UploadCommand cmd, String jobId, RequestType req) { super(cmd); @@ -44,5 +44,5 @@ public class UploadProgressCommand extends UploadCommand { public RequestType getRequest() { return request; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/storage/ssCommand.java b/api/src/com/cloud/agent/api/storage/ssCommand.java index c7b75ea3873..c218a8d5b79 100644 --- a/api/src/com/cloud/agent/api/storage/ssCommand.java +++ b/api/src/com/cloud/agent/api/storage/ssCommand.java @@ -22,21 +22,21 @@ public abstract class ssCommand extends Command { private String secUrl; - public ssCommand() { + public ssCommand() { } - + protected ssCommand(ssCommand that) { this.secUrl = that.secUrl; } public ssCommand(String secUrl) { this.secUrl = secUrl; } - + @Override public boolean executeInSequence() { return true; } - + public String getSecUrl() { return secUrl; } @@ -44,5 +44,5 @@ public abstract class ssCommand extends Command { public void setSecUrl(String secUrl) { this.secUrl = secUrl; } - + } diff --git a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java index 01860204c00..95ac57c3867 100644 --- a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java +++ b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java @@ -22,22 +22,23 @@ import java.util.List; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.State; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; /** * FirewallRuleTO transfers a port range for an ip to be opened. - * + * * There are essentially three states transferred with each state. - * sent multiple times to the destination. If the rule is not on + * sent multiple times to the destination. If the rule is not on * 2. alreadyAdded - the rule has been successfully added before. Rules * in this state are sent for completeness and optimization. * If the rule already exists on the destination, the destination should * reply the rule is successfully applied. - * + * * - srcPortRange: port range to open. * - protocol: protocol to open for. Usually tcp and udp. * */ -public class FirewallRuleTO { +public class FirewallRuleTO implements InternalIdentity { long id; String srcVlanTag; String srcIp; @@ -49,34 +50,35 @@ public class FirewallRuleTO { FirewallRule.Purpose purpose; private Integer icmpType; private Integer icmpCode; - + protected FirewallRuleTO() { } - + public FirewallRuleTO(long id, String srcIp, String protocol, Integer srcPortStart, Integer srcPortEnd, boolean revoked, boolean alreadyAdded, FirewallRule.Purpose purpose, List sourceCidr,Integer icmpType,Integer icmpCode) { this(id,null,srcIp,protocol,srcPortStart,srcPortEnd,revoked,alreadyAdded,purpose,sourceCidr,icmpType,icmpCode); - } + } public FirewallRuleTO(long id,String srcVlanTag, String srcIp, String protocol, Integer srcPortStart, Integer srcPortEnd, boolean revoked, boolean alreadyAdded, FirewallRule.Purpose purpose, List sourceCidr,Integer icmpType,Integer icmpCode) { + this.id = id; this.srcVlanTag = srcVlanTag; this.srcIp = srcIp; this.protocol = protocol; - + if (srcPortStart != null) { List portRange = new ArrayList(); portRange.add(srcPortStart); if (srcPortEnd != null) { portRange.add(srcPortEnd); } - + srcPortRange = new int[portRange.size()]; int i = 0; for (Integer port : portRange) { srcPortRange[i] = port.intValue(); i ++; - } - } - + } + } + this.revoked = revoked; this.alreadyAdded = alreadyAdded; this.purpose = purpose; @@ -87,11 +89,11 @@ public class FirewallRuleTO { public FirewallRuleTO(FirewallRule rule, String srcVlanTag, String srcIp) { this(rule.getId(),srcVlanTag, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(),rule.getSourceCidrList(),rule.getIcmpType(),rule.getIcmpCode()); } - + public FirewallRuleTO(FirewallRule rule, String srcIp) { this(rule.getId(),null, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(),rule.getSourceCidrList(),rule.getIcmpType(),rule.getIcmpCode()); } - + public long getId() { return id; } @@ -99,7 +101,7 @@ public class FirewallRuleTO { public String getSrcVlanTag() { return srcVlanTag; } - + public String getSrcIp() { return srcIp; } @@ -111,15 +113,15 @@ public class FirewallRuleTO { public int[] getSrcPortRange() { return srcPortRange; } - + public Integer getIcmpType(){ return icmpType; } - + public Integer getIcmpCode(){ - return icmpCode; + return icmpCode; } - + public String getStringSrcPortRange() { if (srcPortRange == null || srcPortRange.length < 2) return "0:0"; @@ -130,11 +132,11 @@ public class FirewallRuleTO { public boolean revoked() { return revoked; } - + public List getSourceCidrList() { return sourceCidrList; } - + public boolean isAlreadyAdded() { return alreadyAdded; } @@ -142,5 +144,5 @@ public class FirewallRuleTO { public FirewallRule.Purpose getPurpose() { return purpose; } - + } diff --git a/api/src/com/cloud/agent/api/to/HostTO.java b/api/src/com/cloud/agent/api/to/HostTO.java index f7b734c19d2..967a63d63b5 100644 --- a/api/src/com/cloud/agent/api/to/HostTO.java +++ b/api/src/com/cloud/agent/api/to/HostTO.java @@ -24,10 +24,10 @@ public class HostTO { private NetworkTO publicNetwork; private NetworkTO storageNetwork1; private NetworkTO storageNetwork2; - + protected HostTO() { } - + public HostTO(Host vo) { guid = vo.getGuid(); privateNetwork = new NetworkTO(vo.getPrivateIpAddress(), vo.getPrivateNetmask(), vo.getPrivateMacAddress()); diff --git a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java index 2e19af05569..2d166ea1e1e 100644 --- a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java +++ b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java @@ -43,12 +43,13 @@ public class LoadBalancerTO { String algorithm; boolean revoked; boolean alreadyAdded; + boolean inline; DestinationTO[] destinations; private StickinessPolicyTO[] stickinessPolicies; private AutoScaleVmGroupTO autoScaleVmGroupTO; final static int MAX_STICKINESS_POLICIES = 1; - public LoadBalancerTO(String uuid, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, List destinations) { + public LoadBalancerTO(String uuid, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, boolean inline, List destinations) { if (destinations == null) { // for autoscaleconfig destinations will be null; destinations = new ArrayList(); } @@ -59,6 +60,7 @@ public class LoadBalancerTO { this.algorithm = algorithm; this.revoked = revoked; this.alreadyAdded = alreadyAdded; + this.inline = inline; this.destinations = new DestinationTO[destinations.size()]; this.stickinessPolicies = null; int i = 0; @@ -67,8 +69,8 @@ public class LoadBalancerTO { } } - public LoadBalancerTO(String id, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, List arg_destinations, List stickinessPolicies) { - this(id, srcIp, srcPort, protocol, algorithm, revoked, alreadyAdded, arg_destinations); + public LoadBalancerTO(String id, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, boolean inline, List arg_destinations, List stickinessPolicies) { + this(id, srcIp, srcPort, protocol, algorithm, revoked, alreadyAdded, inline, arg_destinations); this.stickinessPolicies = null; if (stickinessPolicies != null && stickinessPolicies.size() > 0) { this.stickinessPolicies = new StickinessPolicyTO[MAX_STICKINESS_POLICIES]; @@ -116,6 +118,10 @@ public class LoadBalancerTO { return alreadyAdded; } + public boolean isInline() { + return inline; + } + public StickinessPolicyTO[] getStickinessPolicies() { return stickinessPolicies; } diff --git a/api/src/com/cloud/agent/api/to/NetworkACLTO.java b/api/src/com/cloud/agent/api/to/NetworkACLTO.java index 3cdf8fb476e..9b1a6296b08 100644 --- a/api/src/com/cloud/agent/api/to/NetworkACLTO.java +++ b/api/src/com/cloud/agent/api/to/NetworkACLTO.java @@ -23,9 +23,10 @@ import java.util.List; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.TrafficType; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; -public class NetworkACLTO { +public class NetworkACLTO implements InternalIdentity { long id; String vlanTag; String protocol; @@ -36,32 +37,32 @@ public class NetworkACLTO { private Integer icmpType; private Integer icmpCode; private FirewallRule.TrafficType trafficType; - + protected NetworkACLTO() { } - + public NetworkACLTO(long id,String vlanTag, String protocol, Integer portStart, Integer portEnd, boolean revoked, boolean alreadyAdded, List cidrList, Integer icmpType,Integer icmpCode,TrafficType trafficType) { this.vlanTag = vlanTag; this.protocol = protocol; - + if (portStart != null) { List range = new ArrayList(); range.add(portStart); if (portEnd != null) { range.add(portEnd); } - + portRange = new int[range.size()]; int i = 0; for (Integer port : range) { portRange[i] = port.intValue(); i ++; - } - } - + } + } + this.revoked = revoked; this.alreadyAdded = alreadyAdded; this.cidrList = cidrList; @@ -71,11 +72,11 @@ public class NetworkACLTO { } public NetworkACLTO(FirewallRule rule, String vlanTag, FirewallRule.TrafficType trafficType ) { - this(rule.getId(), vlanTag, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), + this(rule.getId(), vlanTag, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState() == FirewallRule.State.Revoke, rule.getState() == FirewallRule.State.Active, rule.getSourceCidrList() ,rule.getIcmpType(), rule.getIcmpCode(),trafficType); } - + public long getId() { return id; } @@ -91,15 +92,15 @@ public class NetworkACLTO { public int[] getSrcPortRange() { return portRange; } - + public Integer getIcmpType(){ return icmpType; } - + public Integer getIcmpCode(){ - return icmpCode; + return icmpCode; } - + public String getStringPortRange() { if (portRange == null || portRange.length < 2) return "0:0"; @@ -110,11 +111,11 @@ public class NetworkACLTO { public boolean revoked() { return revoked; } - + public List getSourceCidrList() { return cidrList; } - + public boolean isAlreadyAdded() { return alreadyAdded; } diff --git a/api/src/com/cloud/agent/api/to/NetworkTO.java b/api/src/com/cloud/agent/api/to/NetworkTO.java index ad9d4d90ee7..3edd4c0f937 100644 --- a/api/src/com/cloud/agent/api/to/NetworkTO.java +++ b/api/src/com/cloud/agent/api/to/NetworkTO.java @@ -100,7 +100,7 @@ public class NetworkTO { /** * This constructor is usually for hosts where the other information are not important. - * + * * @param ip ip address * @param netmask netmask * @param mac mac address @@ -112,7 +112,7 @@ public class NetworkTO { /** * This is the full constructor and should be used for VM's network as it contains * the full information about what is needed. - * + * * @param ip * @param vlan * @param netmask diff --git a/api/src/com/cloud/agent/api/to/NicTO.java b/api/src/com/cloud/agent/api/to/NicTO.java index 79a43d2e625..aa2aa19cc19 100644 --- a/api/src/com/cloud/agent/api/to/NicTO.java +++ b/api/src/com/cloud/agent/api/to/NicTO.java @@ -26,45 +26,45 @@ public class NicTO extends NetworkTO { public NicTO() { super(); } - + public void setDeviceId(int deviceId) { this.deviceId = deviceId; } - + public int getDeviceId() { return deviceId; } - + public Integer getNetworkRateMbps() { return networkRateMbps; } - + public void setNetworkRateMbps(Integer networkRateMbps) { this.networkRateMbps = networkRateMbps; } - + public Integer getNetworkRateMulticastMbps() { return networkRateMulticastMbps; } - + public boolean isDefaultNic() { return defaultNic; } - + public void setDefaultNic(boolean defaultNic) { this.defaultNic = defaultNic; } - + @Override public String getUuid() { return uuid; } - + @Override public void setUuid(String uuid) { this.uuid = uuid; } - + @Override public String toString() { return new StringBuilder("[Nic:").append(type).append("-").append(ip).append("-").append(broadcastUri).append("]").toString(); diff --git a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java index 19673a6e4c7..c23dce8ea86 100644 --- a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java +++ b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java @@ -22,23 +22,23 @@ import com.cloud.utils.net.NetUtils; /** * PortForwardingRuleTO specifies one port forwarding rule. - * + * * */ public class PortForwardingRuleTO extends FirewallRuleTO { String dstIp; int[] dstPortRange; - + protected PortForwardingRuleTO() { super(); } - + public PortForwardingRuleTO(PortForwardingRule rule, String srcVlanTag, String srcIp) { super(rule, srcVlanTag, srcIp); this.dstIp = rule.getDestinationIpAddress().addr(); this.dstPortRange = new int[] { rule.getDestinationPortStart(), rule.getDestinationPortEnd() }; } - + public PortForwardingRuleTO(long id, String srcIp, int srcPortStart, int srcPortEnd, String dstIp, int dstPortStart, int dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { super(id, null, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.PortForwarding, null,0,0); this.dstIp = dstIp; @@ -56,5 +56,5 @@ public class PortForwardingRuleTO extends FirewallRuleTO { public String getStringDstPortRange() { return NetUtils.portRangeToString(dstPortRange); } - + } diff --git a/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java b/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java index fd77dd69578..64ca266a1ca 100644 --- a/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java +++ b/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java @@ -22,34 +22,39 @@ import com.cloud.network.rules.StaticNatRule; /** * StaticNatRuleTO specifies one static nat rule. - * + * * */ public class StaticNatRuleTO extends FirewallRuleTO{ String dstIp; - + protected StaticNatRuleTO() { } - + public StaticNatRuleTO(StaticNatRule rule, String srcVlanTag, String srcIp, String dstIp) { super(rule.getId(),srcVlanTag, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(),rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(), null,0,0); this.dstIp = dstIp; } - + public StaticNatRuleTO(StaticNatRule rule, String scrIp, String dstIp) { super(rule.getId(), scrIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(),rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(), null,0,0); this.dstIp = dstIp; } - - + + public StaticNatRuleTO(long id, String srcIp, Integer srcPortStart, Integer srcPortEnd, String dstIp, Integer dstPortStart, Integer dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { super(id, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.StaticNat, null,0,0); this.dstIp = dstIp; } + + public StaticNatRuleTO(long id,String srcVlanTag, String srcIp, Integer srcPortStart, Integer srcPortEnd, String dstIp, Integer dstPortStart, Integer dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { + super(id, srcVlanTag, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.StaticNat, null,0,0); + this.dstIp = dstIp; + } public String getDstIp() { return dstIp; } - + } diff --git a/api/src/com/cloud/agent/api/to/StorageFilerTO.java b/api/src/com/cloud/agent/api/to/StorageFilerTO.java index 26344daaeb6..8f58c9e1c91 100644 --- a/api/src/com/cloud/agent/api/to/StorageFilerTO.java +++ b/api/src/com/cloud/agent/api/to/StorageFilerTO.java @@ -27,7 +27,7 @@ public class StorageFilerTO { String userInfo; int port; StoragePoolType type; - + public StorageFilerTO(StoragePool pool) { this.id = pool.getId(); this.host = pool.getHostAddress(); @@ -61,14 +61,14 @@ public class StorageFilerTO { public int getPort() { return port; } - + public StoragePoolType getType() { return type; } - + protected StorageFilerTO() { } - + @Override public String toString() { return new StringBuilder("Pool[").append(id).append("|").append(host).append(":").append(port).append("|").append(path).append("]").toString(); diff --git a/api/src/com/cloud/agent/api/to/SwiftTO.java b/api/src/com/cloud/agent/api/to/SwiftTO.java index 7920ce83e27..32742c7d0e3 100644 --- a/api/src/com/cloud/agent/api/to/SwiftTO.java +++ b/api/src/com/cloud/agent/api/to/SwiftTO.java @@ -15,15 +15,15 @@ // specific language governing permissions and limitations // under the License. package com.cloud.agent.api.to; - + public class SwiftTO { Long id; String url; String account; - + String userName; String key; - + public SwiftTO() { } public SwiftTO(Long id, String url, String account, String userName, String key) { @@ -33,7 +33,7 @@ public class SwiftTO { this.userName = userName; this.key = key; } - + public Long getId() { return id; } @@ -53,6 +53,6 @@ public class SwiftTO { public String getKey() { return key; } - + } diff --git a/api/src/com/cloud/agent/api/to/TemplateTO.java b/api/src/com/cloud/agent/api/to/TemplateTO.java index e163340fbf0..d77b80551f4 100644 --- a/api/src/com/cloud/agent/api/to/TemplateTO.java +++ b/api/src/com/cloud/agent/api/to/TemplateTO.java @@ -18,21 +18,22 @@ package com.cloud.agent.api.to; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class TemplateTO { +public class TemplateTO implements InternalIdentity { private long id; private String uniqueName; private ImageFormat format; - + protected TemplateTO() { } - + public TemplateTO(VirtualMachineTemplate template) { this.id = template.getId(); this.uniqueName = template.getUniqueName(); this.format = template.getFormat(); } - + public long getId() { return id; } diff --git a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java index a93c242b7c1..8f3f0eb39d6 100644 --- a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java +++ b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java @@ -108,7 +108,7 @@ public class VirtualMachineTO { public boolean getLimitCpuUse() { return limitCpuUse; } - + public long getMinRam() { return minRam; } @@ -185,11 +185,11 @@ public class VirtualMachineTO { public void setNics(NicTO[] nics) { this.nics = nics; } - + public String getVncPassword() { return this.vncPassword; } - + public void setVncPassword(String vncPassword) { this.vncPassword = vncPassword; } @@ -201,11 +201,11 @@ public class VirtualMachineTO { public void setVncAddr(String vncAddr) { this.vncAddr = vncAddr; } - + public Map getDetails() { return params; } - + public void setDetails(Map params) { this.params = params; } @@ -217,6 +217,6 @@ public class VirtualMachineTO { public void setUuid(String uuid) { this.uuid = uuid; } - - + + } diff --git a/api/src/com/cloud/agent/api/to/VolumeTO.java b/api/src/com/cloud/agent/api/to/VolumeTO.java index ca0acb57876..ff739c58f80 100644 --- a/api/src/com/cloud/agent/api/to/VolumeTO.java +++ b/api/src/com/cloud/agent/api/to/VolumeTO.java @@ -19,8 +19,9 @@ package com.cloud.agent.api.to; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; +import org.apache.cloudstack.api.InternalIdentity; -public class VolumeTO { +public class VolumeTO implements InternalIdentity { protected VolumeTO() { } diff --git a/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java index 23f0a7e0fb9..10001b149fa 100644 --- a/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { @@ -34,9 +34,9 @@ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { private Long templateId; protected uploadTemplateToSwiftFromSecondaryStorageCommand() { - + } - + public uploadTemplateToSwiftFromSecondaryStorageCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long templateId, int wait) { this.swift = swift; @@ -77,4 +77,4 @@ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/alert/Alert.java b/api/src/com/cloud/alert/Alert.java index c9368a34522..defd15490e5 100644 --- a/api/src/com/cloud/alert/Alert.java +++ b/api/src/com/cloud/alert/Alert.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.alert; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface Alert { - long getId(); +public interface Alert extends Identity, InternalIdentity { short getType(); String getSubject(); Long getPodId(); diff --git a/api/src/com/cloud/api/commands/.gitignore b/api/src/com/cloud/api/commands/.gitignore index 63e3fa0c721..62042786c83 100644 --- a/api/src/com/cloud/api/commands/.gitignore +++ b/api/src/com/cloud/api/commands/.gitignore @@ -5,9 +5,9 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY diff --git a/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java index 99fd48f82d2..263f023b3e5 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java @@ -16,16 +16,14 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -33,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.network.Network; import com.cloud.user.UserContext; -@Implementation(description="Creates a private network", responseObject=NetworkResponse.class) +//@APICommand(description="Creates a private network", responseObject=NetworkResponse.class) public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePrivateNetworkCmd.class.getName()); @@ -42,42 +40,42 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the network") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the network") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + " range. If not specified, will be defaulted to startIP") private String endIp; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the ID or VID of the network") private String vlan; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a network") private Long domainId; @@ -100,7 +98,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -108,23 +106,23 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public String getStartIp() { return startIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + public Long getProjectId() { return projectId; } - + public long getPhysicalNetworkId() { return physicalNetworkId; } - + public String getEndIp() { return endIp; } @@ -136,8 +134,8 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { Network result = null; @@ -152,14 +150,15 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network"); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.getNetwork(getEntityId()); @@ -171,7 +170,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private network"); } } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); @@ -191,9 +190,5 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { return "creating private network"; } - - @Override - public String getEntityTable() { - return "networks"; - } + } diff --git a/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java deleted file mode 100755 index 8299ec94693..00000000000 --- a/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java +++ /dev/null @@ -1,127 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; - -@Implementation(description="Creates a Storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") -public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateStorageNetworkIpRangeCmd.class); - - private static final String s_name = "createstoragenetworkiprangeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, required=true, description="UUID of pod where the ip range belongs to") - private Long podId; - - @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address") - private String startIp; - - @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") - private String endIp; - - @Parameter(name = ApiConstants.VLAN, type = CommandType.INTEGER, description = "Optional. The vlan the ip range sits on, default to Null when it is not specificed which means you network is not on any Vlan. This is mainly for Vmware as other hypervisors can directly reterive bridge from pyhsical network traffic type table") - private Integer vlan; - - @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for storage network") - private String netmask; - - @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for storage network") - private String gateway; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getEndIp() { - return endIp; - } - - public Long getPodId() { - return podId; - } - - public String getStartIp() { - return startIp; - } - - public Integer getVlan() { - return vlan; - } - - public String getNetmask() { - return netmask; - } - - public String getGateWay() { - return gateway; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_CREATE; - } - - @Override - public String getEventDescription() { - return "Creating storage ip range from " + getStartIp() + " to " + getEndIp() + " with vlan " + getVlan(); - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - StorageNetworkIpRange result = _storageNetworkService.createIpRange(this); - StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Create storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - -} diff --git a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java index 3ae61c1118b..80269075744 100644 --- a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java +++ b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java @@ -16,25 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Destroys console proxy", responseObject=SuccessResponse.class) +//@APICommand(description="Destroys console proxy", responseObject=SuccessResponse.class) public class DestroyConsoleProxyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName()); private static final String s_name = "destroyconsoleproxyresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -80,7 +76,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd { public String getEventDescription() { return "destroying console proxy: " + getId(); } - + @Override public void execute(){ boolean result = _consoleProxyService.destroyConsoleProxy(this); diff --git a/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java b/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java index 7583cc06a05..709da6af30c 100644 --- a/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java +++ b/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java @@ -19,15 +19,15 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; import com.cloud.storage.snapshot.SnapshotSchedule; -@Implementation(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class) +//@APICommand(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class) public class ListRecurringSnapshotScheduleCmd extends BaseListCmd { private static final String s_name = "listrecurringsnapshotscheduleresponse"; @@ -61,20 +61,14 @@ public class ListRecurringSnapshotScheduleCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List snapshotSchedules = _snapshotService.findRecurringSnapshotSchedule(this); ListResponse response = new ListResponse(); List snapshotScheduleResponses = new ArrayList(); for (SnapshotSchedule snapshotSchedule : snapshotSchedules) { - SnapshotScheduleResponse snapSchedResponse = new SnapshotScheduleResponse(); - snapSchedResponse.setId(snapshotSchedule.getId()); - snapSchedResponse.setVolumeId(snapshotSchedule.getVolumeId()); - snapSchedResponse.setSnapshotPolicyId(snapshotSchedule.getPolicyId()); - snapSchedResponse.setScheduled(snapshotSchedule.getScheduledTimestamp()); - - snapSchedResponse.setObjectName("snapshot"); + SnapshotScheduleResponse snapSchedResponse = _responseGenerator.createSnapshotScheduleResponse(snapshotSchedule); snapshotScheduleResponses.add(snapSchedResponse); } diff --git a/api/src/com/cloud/api/commands/RestoreVMCmd.java b/api/src/com/cloud/api/commands/RestoreVMCmd.java deleted file mode 100755 index 31d2c229dee..00000000000 --- a/api/src/com/cloud/api/commands/RestoreVMCmd.java +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -import com.cloud.uservm.UserVm; - -@Implementation(description="Restore a VM to original template or specific snapshot", responseObject=UserVmResponse.class, since="3.0.0") -public class RestoreVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RestoreVMCmd.class); - private static final String s_name = "restorevmresponse"; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="Virtual Machine ID") - private Long vmId; - - @Override - public String getEventType() { - return EventTypes.EVENT_VM_RESTORE; - } - - @Override - public String getEventDescription() { - return "Restore a VM to orignal template or specific snapshot"; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - UserVm result; - UserContext.current().setEventDetails("Vm Id: " + getVmId()); - result = _userVmService.restoreVM(this); - if (result != null) { - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - UserVm vm = _responseGenerator.findUserVmById(getVmId()); - if (vm == null) { - return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked - } - return vm.getAccountId(); - } - - public long getVmId() { - return vmId; - } - -} diff --git a/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java b/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java deleted file mode 100755 index f0b3a53fcb1..00000000000 --- a/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java +++ /dev/null @@ -1,108 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; - -@Implementation(description="List a storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") -public class listStorageNetworkIpRangeCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(listStorageNetworkIpRangeCmd.class); - - String s_name = "liststoragenetworkiprangeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="optional parameter. Storaget network IP range uuid, if specicied, using it to search the range.") - private Long rangeId; - - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="optional parameter. Pod uuid, if specicied and range uuid is absent, using it to search the range.") - private Long podId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="optional parameter. Zone uuid, if specicied and both pod uuid and range uuid are absent, using it to search the range.") - private Long zoneId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getRangeId() { - return rangeId; - } - - public Long getPodId() { - return podId; - } - - public Long getZoneId() { - return zoneId; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List results = _storageNetworkService.listIpRange(this); - ListResponse response = new ListResponse(); - List resList = new ArrayList(results.size()); - for (StorageNetworkIpRange r : results) { - StorageNetworkIpRangeResponse resp = _responseGenerator.createStorageNetworkIpRangeResponse(r); - resList.add(resp); - } - response.setResponses(resList); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - -} diff --git a/api/src/com/cloud/api/response/AsyncJobResponse.java b/api/src/com/cloud/api/response/AsyncJobResponse.java deleted file mode 100644 index 45aee122cdb..00000000000 --- a/api/src/com/cloud/api/response/AsyncJobResponse.java +++ /dev/null @@ -1,159 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; - -import java.util.Date; - -import com.cloud.api.ApiConstants; -import com.cloud.api.ResponseObject; -import com.cloud.async.AsyncJob; -import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; -import com.google.gson.annotations.SerializedName; - -@SuppressWarnings("unused") -public class AsyncJobResponse extends BaseResponse { - - @SerializedName("accountid") @Param(description="the account that executed the async command") - private IdentityProxy accountId = new IdentityProxy("account"); - - @SerializedName(ApiConstants.USER_ID) @Param(description="the user that executed the async command") - private IdentityProxy userId = new IdentityProxy("user"); - - @SerializedName("cmd") @Param(description="the async command executed") - private String cmd; - - @SerializedName("jobstatus") @Param(description="the current job status-should be 0 for PENDING") - private Integer jobStatus; - - @SerializedName("jobprocstatus") @Param(description="the progress information of the PENDING job") - private Integer jobProcStatus; - - @SerializedName("jobresultcode") @Param(description="the result code for the job") - private Integer jobResultCode; - - @SerializedName("jobresulttype") @Param(description="the result type") - private String jobResultType; - - @SerializedName("jobresult") @Param(description="the result reason") - private ResponseObject jobResult; - - @SerializedName("jobinstancetype") @Param(description="the instance/entity object related to the job") - private String jobInstanceType; - - @SerializedName("jobinstanceid") @Param(description="the unique ID of the instance/entity object related to the job") - private IdentityProxy jobInstanceId = new IdentityProxy(); - - @SerializedName(ApiConstants.CREATED) @Param(description=" the created date of the job") - private Date created; - - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); - } - - public void setUserId(Long userId) { - this.userId.setValue(userId); - } - - public void setCmd(String cmd) { - this.cmd = cmd; - } - - @Override - public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; - } - - public void setJobProcStatus(Integer jobProcStatus) { - this.jobProcStatus = jobProcStatus; - } - - public void setJobResultCode(Integer jobResultCode) { - this.jobResultCode = jobResultCode; - } - - public void setJobResultType(String jobResultType) { - this.jobResultType = jobResultType; - } - - public void setJobResult(ResponseObject jobResult) { - this.jobResult = jobResult; - } - - public void setJobInstanceType(String jobInstanceType) { - this.jobInstanceType = jobInstanceType; - - if(jobInstanceType != null) { - if(jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Volume.toString())) { - this.jobInstanceId.setTableName("volumes"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Template.toString())) { - this.jobInstanceId.setTableName("vm_template"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Iso.toString())) { - this.jobInstanceId.setTableName("vm_template"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.VirtualMachine.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.ConsoleProxy.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.SystemVm.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.DomainRouter.toString()) ) { - this.jobInstanceId.setTableName("vm_instance"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Snapshot.toString())) { - this.jobInstanceId.setTableName("snapshots"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Host.toString())) { - this.jobInstanceId.setTableName("host"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.StoragePool.toString())) { - this.jobInstanceId.setTableName("storage_pool"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.IpAddress.toString())) { - this.jobInstanceId.setTableName("user_ip_address"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.SecurityGroup.toString())) { - this.jobInstanceId.setTableName("security_group"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PhysicalNetwork.toString())) { - this.jobInstanceId.setTableName("physical_network"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.TrafficType.toString())) { - this.jobInstanceId.setTableName("physical_network_traffic_types"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PhysicalNetworkServiceProvider.toString())) { - this.jobInstanceId.setTableName("physical_network_service_providers"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.FirewallRule.toString())) { - this.jobInstanceId.setTableName("firewall_rules"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Account.toString())) { - this.jobInstanceId.setTableName("account"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.User.toString())) { - this.jobInstanceId.setTableName("user"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.StaticRoute.toString())) { - this.jobInstanceId.setTableName("static_routes"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PrivateGateway.toString())) { - this.jobInstanceId.setTableName("vpc_gateways"); - }else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Counter.toString())) { - this.jobInstanceId.setTableName("counter"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Condition.toString())) { - this.jobInstanceId.setTableName("conditions"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.AutoScalePolicy.toString())) { - this.jobInstanceId.setTableName("autoscale_policies"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.AutoScaleVmProfile.toString())) { - this.jobInstanceId.setTableName("autoscale_vmprofiles"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.AutoScaleVmGroup.toString())) { - this.jobInstanceId.setTableName("autoscale_vmgroups"); - } else if (!jobInstanceType.equalsIgnoreCase(AsyncJob.Type.None.toString())){ - // TODO : when we hit here, we need to add instanceType -> UUID entity table mapping - assert(false); - } - } - } - - public void setJobInstanceId(Long jobInstanceId) { - this.jobInstanceId.setValue(jobInstanceId); - } - - public void setCreated(Date created) { - this.created = created; - } -} diff --git a/api/src/com/cloud/async/AsyncJob.java b/api/src/com/cloud/async/AsyncJob.java index b8551edc83e..034c853e8f9 100644 --- a/api/src/com/cloud/async/AsyncJob.java +++ b/api/src/com/cloud/async/AsyncJob.java @@ -18,9 +18,10 @@ package com.cloud.async; import java.util.Date; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface AsyncJob extends Identity { +public interface AsyncJob extends Identity, InternalIdentity { public enum Type { None, VirtualMachine, @@ -50,8 +51,6 @@ public interface AsyncJob extends Identity { AutoScaleVmGroup } - Long getId(); - long getUserId(); long getAccountId(); diff --git a/api/src/com/cloud/capacity/Capacity.java b/api/src/com/cloud/capacity/Capacity.java index 2da2a672ce3..c1c5d8fa9b2 100755 --- a/api/src/com/cloud/capacity/Capacity.java +++ b/api/src/com/cloud/capacity/Capacity.java @@ -16,7 +16,10 @@ // under the License. package com.cloud.capacity; -public interface Capacity { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Capacity extends InternalIdentity, Identity { public static final short CAPACITY_TYPE_MEMORY = 0; public static final short CAPACITY_TYPE_CPU = 1; public static final short CAPACITY_TYPE_STORAGE = 2; @@ -28,8 +31,6 @@ public interface Capacity { public static final short CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8; public static final short CAPACITY_TYPE_LOCAL_STORAGE = 9; - public long getId(); - public Long getHostOrPoolId(); public Long getDataCenterId(); @@ -42,11 +43,9 @@ public interface Capacity { public long getTotalCapacity(); - public short getCapacityType(); + public short getCapacityType(); public long getReservedCapacity(); - + public Float getUsedPercentage(); - - } diff --git a/api/src/com/cloud/capacity/CapacityState.java b/api/src/com/cloud/capacity/CapacityState.java index be17663f602..b368567c022 100755 --- a/api/src/com/cloud/capacity/CapacityState.java +++ b/api/src/com/cloud/capacity/CapacityState.java @@ -17,9 +17,9 @@ package com.cloud.capacity; public enum CapacityState { - + Enabled, - Disabled, + Disabled, Maintenance, - + } diff --git a/api/src/com/cloud/cluster/ManagementServerHost.java b/api/src/com/cloud/cluster/ManagementServerHost.java index 0273d472bea..9c88a2b2006 100644 --- a/api/src/com/cloud/cluster/ManagementServerHost.java +++ b/api/src/com/cloud/cluster/ManagementServerHost.java @@ -16,7 +16,9 @@ // under the License. package com.cloud.cluster; -public interface ManagementServerHost { +import org.apache.cloudstack.api.InternalIdentity; + +public interface ManagementServerHost extends InternalIdentity { public static enum State { Up, Starting, Down diff --git a/api/src/com/cloud/configuration/ConfigurationService.java b/api/src/com/cloud/configuration/ConfigurationService.java index 78d7a2250a9..48a060719c6 100644 --- a/api/src/com/cloud/configuration/ConfigurationService.java +++ b/api/src/com/cloud/configuration/ConfigurationService.java @@ -20,26 +20,24 @@ import java.util.List; import javax.naming.NamingException; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; import com.cloud.dc.Vlan; @@ -57,7 +55,7 @@ public interface ConfigurationService { /** * Updates a configuration entry with a new value - * + * * @param cmd * - the command wrapping name and value parameters * @return updated configuration object if successful @@ -66,7 +64,7 @@ public interface ConfigurationService { /** * Create a service offering through the API - * + * * @param cmd * the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service * offering @@ -76,7 +74,7 @@ public interface ConfigurationService { /** * Updates a service offering - * + * * @param serviceOfferingId * @param userId * @param name @@ -90,7 +88,7 @@ public interface ConfigurationService { /** * Deletes a service offering - * + * * @param userId * @param serviceOfferingId */ @@ -98,7 +96,7 @@ public interface ConfigurationService { /** * Updates a disk offering - * + * * @param cmd * - the command specifying diskOfferingId, name, description, tags * @return updated disk offering @@ -108,7 +106,7 @@ public interface ConfigurationService { /** * Deletes a disk offering - * + * * @param cmd * - the command specifying disk offering id * @return true or false @@ -118,7 +116,7 @@ public interface ConfigurationService { /** * Creates a new disk offering - * + * * @param domainId * @param name * @param description @@ -131,7 +129,7 @@ public interface ConfigurationService { /** * Creates a new pod based on the parameters specified in the command object - * + * * @param zoneId * TODO * @param name @@ -154,7 +152,7 @@ public interface ConfigurationService { /** * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. - * + * * @param UpdatePodCmd * api command */ @@ -162,7 +160,7 @@ public interface ConfigurationService { /** * Deletes a pod from the database. Will not allow you to delete pods that are being used anywhere in the system. - * + * * @param cmd * - the command containing podId * @return true or false @@ -172,7 +170,7 @@ public interface ConfigurationService { /** * Creates a new zone - * + * * @param cmd * @return the zone if successful, null otherwise * @throws @@ -182,7 +180,7 @@ public interface ConfigurationService { /** * Edits a zone in the database. Will not allow you to edit DNS values if there are VMs in the specified zone. - * + * * @param UpdateZoneCmd * @return Updated zone */ @@ -190,7 +188,7 @@ public interface ConfigurationService { /** * Deletes a zone from the database. Will not allow you to delete zones that are being used anywhere in the system. - * + * * @param userId * @param zoneId */ @@ -200,7 +198,7 @@ public interface ConfigurationService { * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on * the * virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs - * + * * @param userId * @param vlanType * - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be diff --git a/api/src/com/cloud/configuration/ResourceCount.java b/api/src/com/cloud/configuration/ResourceCount.java index d776a72d2b1..f0b1d7190d5 100644 --- a/api/src/com/cloud/configuration/ResourceCount.java +++ b/api/src/com/cloud/configuration/ResourceCount.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.configuration; -public interface ResourceCount extends Resource { +import org.apache.cloudstack.api.InternalIdentity; - public Long getId(); +public interface ResourceCount extends Resource, InternalIdentity { public long getCount(); diff --git a/api/src/com/cloud/configuration/ResourceLimit.java b/api/src/com/cloud/configuration/ResourceLimit.java index df47d09b484..801feebbe10 100644 --- a/api/src/com/cloud/configuration/ResourceLimit.java +++ b/api/src/com/cloud/configuration/ResourceLimit.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.configuration; -public interface ResourceLimit extends Resource { +import org.apache.cloudstack.api.InternalIdentity; - public Long getId(); +public interface ResourceLimit extends Resource, InternalIdentity { public Long getMax(); diff --git a/api/src/com/cloud/dao/EntityManager.java b/api/src/com/cloud/dao/EntityManager.java index 0e5b07f51e4..4e4b9c293b5 100644 --- a/api/src/com/cloud/dao/EntityManager.java +++ b/api/src/com/cloud/dao/EntityManager.java @@ -37,7 +37,16 @@ public interface EntityManager { * @return T if found; null if not. */ public T findById(Class entityType, K id); - + + /** + * Finds a unique entity by uuid string + * @param entity class + * @param entityType type of entity you're looking for. + * @param uuid the unique id + * @return T if found, null if not. + */ + public T findByUuid(Class entityType, String uuid); + /** * Finds an entity by external id which is always String * @param entity class @@ -45,8 +54,8 @@ public interface EntityManager { * @param xid external id * @return T if found, null if not. */ - public T findByXid(Class entityType, String xid); - + public T findByXId(Class entityType, String xid); + /** * Lists all entities. Use this method at your own risk. * @param entity class @@ -54,7 +63,7 @@ public interface EntityManager { * @return List */ public List list(Class entityType); - + /** * Persists the entity. * @param entity class @@ -62,13 +71,13 @@ public interface EntityManager { * @return persisted entity. Only use this after persisting. */ public T persist(T t); - + public SearchBuilder createSearchBuilder(Class entityType); - + public GenericSearchBuilder createGenericSearchBuilder(Class entityType, Class resultType); - + public List search(Class entityType, SearchCriteria sc); - + public void remove(Class entityType, K id); } diff --git a/api/src/com/cloud/dc/DataCenter.java b/api/src/com/cloud/dc/DataCenter.java index 707cd34524e..946e9ccb5bd 100644 --- a/api/src/com/cloud/dc/DataCenter.java +++ b/api/src/com/cloud/dc/DataCenter.java @@ -19,18 +19,19 @@ package com.cloud.dc; import java.util.Map; import com.cloud.org.Grouping; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * */ -public interface DataCenter extends Grouping { +public interface DataCenter extends InfrastructureEntity, Grouping, Identity, InternalIdentity { public enum NetworkType { Basic, Advanced, } - long getId(); - String getDns1(); String getDns2(); diff --git a/api/src/com/cloud/dc/Pod.java b/api/src/com/cloud/dc/Pod.java index 791c5ad2c2d..9da5b7e7836 100644 --- a/api/src/com/cloud/dc/Pod.java +++ b/api/src/com/cloud/dc/Pod.java @@ -17,16 +17,15 @@ package com.cloud.dc; import com.cloud.org.Grouping; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Represents one pod in the cloud stack. - * + * */ -public interface Pod extends Grouping { - /** - * @return unique id mapped to the pod. - */ - long getId(); +public interface Pod extends InfrastructureEntity, Grouping, Identity, InternalIdentity { String getCidrAddress(); @@ -36,8 +35,6 @@ public interface Pod extends Grouping { long getDataCenterId(); - // String getUniqueName(); - String getDescription(); String getName(); diff --git a/api/src/com/cloud/dc/StorageNetworkIpRange.java b/api/src/com/cloud/dc/StorageNetworkIpRange.java index 59aa98ae11e..2b50ca1594e 100755 --- a/api/src/com/cloud/dc/StorageNetworkIpRange.java +++ b/api/src/com/cloud/dc/StorageNetworkIpRange.java @@ -16,8 +16,11 @@ // under the License. package com.cloud.dc; -public interface StorageNetworkIpRange { - String getUuid(); +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface StorageNetworkIpRange extends InfrastructureEntity, InternalIdentity, Identity { Integer getVlan(); @@ -30,8 +33,8 @@ public interface StorageNetworkIpRange { String getNetworkUuid(); String getZoneUuid(); - + String getNetmask(); - + String getGateway(); } diff --git a/api/src/com/cloud/dc/Vlan.java b/api/src/com/cloud/dc/Vlan.java index 1e1fce15fc4..0f629ef3cbf 100644 --- a/api/src/com/cloud/dc/Vlan.java +++ b/api/src/com/cloud/dc/Vlan.java @@ -16,7 +16,11 @@ // under the License. package com.cloud.dc; -public interface Vlan { +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Vlan extends InfrastructureEntity, InternalIdentity, Identity { public enum VlanType { DirectAttached, VirtualNetwork @@ -24,8 +28,6 @@ public interface Vlan { public final static String UNTAGGED = "untagged"; - public long getId(); - public String getVlanTag(); public String getVlanGateway(); diff --git a/api/src/com/cloud/deploy/DataCenterDeployment.java b/api/src/com/cloud/deploy/DataCenterDeployment.java index 25522e06cfa..f046b66ef06 100644 --- a/api/src/com/cloud/deploy/DataCenterDeployment.java +++ b/api/src/com/cloud/deploy/DataCenterDeployment.java @@ -37,7 +37,7 @@ public class DataCenterDeployment implements DeploymentPlan { public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId, Long physicalNetworkId) { this(dataCenterId, podId, clusterId, hostId, poolId, physicalNetworkId, null); } - + public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId, Long physicalNetworkId, ReservationContext context) { _dcId = dataCenterId; _podId = podId; @@ -87,7 +87,7 @@ public class DataCenterDeployment implements DeploymentPlan { public Long getPhysicalNetworkId() { return _physicalNetworkId; } - + @Override public ReservationContext getReservationContext() { return _context; diff --git a/api/src/com/cloud/deploy/DeploymentPlanner.java b/api/src/com/cloud/deploy/DeploymentPlanner.java index e5dcff1be54..537dd314733 100644 --- a/api/src/com/cloud/deploy/DeploymentPlanner.java +++ b/api/src/com/cloud/deploy/DeploymentPlanner.java @@ -37,7 +37,7 @@ import com.cloud.vm.VirtualMachineProfile; public interface DeploymentPlanner extends Adapter { /** * plan is called to determine where a virtual machine should be running. - * + * * @param vm * virtual machine. * @param plan @@ -51,7 +51,7 @@ public interface DeploymentPlanner extends Adapter { /** * check() is called right before the virtual machine starts to make sure * the host has enough capacity. - * + * * @param vm * virtual machine in question. * @param plan @@ -69,7 +69,7 @@ public interface DeploymentPlanner extends Adapter { * canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so * planner writer must * make sure only one planer->canHandle return true in the planner list - * + * * @param vm * virtual machine. * @param plan @@ -187,7 +187,7 @@ public interface DeploymentPlanner extends Adapter { } _clusterIds.addAll(clusterList); } - + public void addHost(long hostId) { if (_hostIds == null) { _hostIds = new HashSet(); diff --git a/api/src/com/cloud/domain/Domain.java b/api/src/com/cloud/domain/Domain.java index a7b4031dce5..cfed519ada9 100644 --- a/api/src/com/cloud/domain/Domain.java +++ b/api/src/com/cloud/domain/Domain.java @@ -19,19 +19,20 @@ package com.cloud.domain; import java.util.Date; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Domain defines the Domain object. */ -public interface Domain extends OwnedBy { + +public interface Domain extends OwnedBy, Identity, InternalIdentity { public static final long ROOT_DOMAIN = 1L; enum State { Active, Inactive }; - long getId(); - Long getParent(); void setParent(Long parent); diff --git a/api/src/com/cloud/event/Event.java b/api/src/com/cloud/event/Event.java index 6a305378931..1a61636828a 100644 --- a/api/src/com/cloud/event/Event.java +++ b/api/src/com/cloud/event/Event.java @@ -18,26 +18,24 @@ package com.cloud.event; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Event extends ControlledEntity{ +public interface Event extends ControlledEntity, Identity, InternalIdentity { public enum State { Created, Scheduled, Started, Completed; } - - long getId(); String getType(); State getState(); String getDescription(); Date getCreateDate(); long getUserId(); - long getAccountId(); - long getDomainId(); int getTotalSize(); String getLevel(); long getStartId(); diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index e69e4a446a2..87eddca5a69 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -108,6 +108,7 @@ public class EventTypes { public static final String EVENT_VOLUME_EXTRACT = "VOLUME.EXTRACT"; public static final String EVENT_VOLUME_UPLOAD = "VOLUME.UPLOAD"; public static final String EVENT_VOLUME_MIGRATE = "VOLUME.MIGRATE"; + public static final String EVENT_VOLUME_RESIZE = "VOLUME.RESIZE"; // Domains public static final String EVENT_DOMAIN_CREATE = "DOMAIN.CREATE"; @@ -267,26 +268,26 @@ public class EventTypes { public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_ADD = "PHYSICAL.FIREWALL.ADD"; public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_DELETE = "PHYSICAL.FIREWALL.DELETE"; public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_CONFIGURE = "PHYSICAL.FIREWALL.CONFIGURE"; - + // VPC public static final String EVENT_VPC_CREATE = "VPC.CREATE"; public static final String EVENT_VPC_UPDATE = "VPC.UPDATE"; public static final String EVENT_VPC_DELETE = "VPC.DELETE"; public static final String EVENT_VPC_RESTART = "VPC.RESTART"; - + // VPC offerings public static final String EVENT_VPC_OFFERING_CREATE = "VPC.OFFERING.CREATE"; public static final String EVENT_VPC_OFFERING_UPDATE = "VPC.OFFERING.UPDATE"; public static final String EVENT_VPC_OFFERING_DELETE = "VPC.OFFERING.DELETE"; - + // Private gateway public static final String EVENT_PRIVATE_GATEWAY_CREATE = "PRIVATE.GATEWAY.CREATE"; public static final String EVENT_PRIVATE_GATEWAY_DELETE = "PRIVATE.GATEWAY.DELETE"; - + // Static routes public static final String EVENT_STATIC_ROUTE_CREATE = "STATIC.ROUTE.CREATE"; public static final String EVENT_STATIC_ROUTE_DELETE = "STATIC.ROUTE.DELETE"; - + // tag related events public static final String EVENT_TAGS_CREATE = "CREATE_TAGS"; public static final String EVENT_TAGS_DELETE = "DELETE_TAGS"; @@ -295,7 +296,7 @@ public class EventTypes { public static final String EVENT_EXTERNAL_NVP_CONTROLLER_ADD = "PHYSICAL.NVPCONTROLLER.ADD"; public static final String EVENT_EXTERNAL_NVP_CONTROLLER_DELETE = "PHYSICAL.NVPCONTROLLER.DELETE"; public static final String EVENT_EXTERNAL_NVP_CONTROLLER_CONFIGURE = "PHYSICAL.NVPCONTROLLER.CONFIGURE"; - + // AutoScale public static final String EVENT_COUNTER_CREATE = "COUNTER.CREATE"; public static final String EVENT_COUNTER_DELETE = "COUNTER.DELETE"; diff --git a/api/src/com/cloud/exception/AgentUnavailableException.java b/api/src/com/cloud/exception/AgentUnavailableException.java index a2d052b61f5..89193243e1d 100644 --- a/api/src/com/cloud/exception/AgentUnavailableException.java +++ b/api/src/com/cloud/exception/AgentUnavailableException.java @@ -24,17 +24,17 @@ import com.cloud.utils.SerialVersionUID; * */ public class AgentUnavailableException extends ResourceUnavailableException { - + private static final long serialVersionUID = SerialVersionUID.AgentUnavailableException; - + public AgentUnavailableException(String msg, long agentId) { this(msg, agentId, null); } - + public AgentUnavailableException(long agentId) { this("Unable to reach host.", agentId); } - + public AgentUnavailableException(String msg, long agentId, Throwable cause) { super("Host " + agentId + ": " + msg, Host.class, agentId, cause); } diff --git a/api/src/com/cloud/exception/CloudAuthenticationException.java b/api/src/com/cloud/exception/CloudAuthenticationException.java index 2bba79bab1e..0bf114c0394 100644 --- a/api/src/com/cloud/exception/CloudAuthenticationException.java +++ b/api/src/com/cloud/exception/CloudAuthenticationException.java @@ -17,9 +17,9 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; -import com.cloud.utils.exception.RuntimeCloudException; +import com.cloud.utils.exception.CloudRuntimeException; -public class CloudAuthenticationException extends RuntimeCloudException { +public class CloudAuthenticationException extends CloudRuntimeException { private static final long serialVersionUID = SerialVersionUID.CloudAuthenticationException; public CloudAuthenticationException(String message) { diff --git a/api/src/com/cloud/exception/CloudException.java b/api/src/com/cloud/exception/CloudException.java index 9ebeaad6675..732670288f1 100644 --- a/api/src/com/cloud/exception/CloudException.java +++ b/api/src/com/cloud/exception/CloudException.java @@ -16,24 +16,22 @@ // under the License. package com.cloud.exception; -import com.cloud.utils.IdentityProxy; import java.util.ArrayList; import com.cloud.utils.exception.CSExceptionErrorCode; -import com.cloud.utils.AnnotationHelper; /** * by the API response serializer. Any exceptions that are thrown by * class, which extends RuntimeException instead of Exception like this - * class does. + * class does. */ public class CloudException extends Exception { - + // This holds a list of uuids and their names. Add uuid:fieldname pairs - protected ArrayList idList = new ArrayList(); - - protected Integer csErrorCode; - + protected ArrayList idList = new ArrayList(); + + protected Integer csErrorCode; + public CloudException(String message) { super(message); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); @@ -43,34 +41,27 @@ public class CloudException extends Exception { super(message, cause); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - - public void addProxyObject(Object voObj, Long id, String idFieldName) { - // Get the VO object's table name. - String tablename = AnnotationHelper.getTableName(voObj); - if (tablename != null) { - addProxyObject(tablename, id, idFieldName); - } - return; - } - + + + public CloudException() { super(); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - - public void addProxyObject(String tableName, Long id, String idFieldName) { - idList.add(new IdentityProxy(tableName, id, idFieldName)); + + public void addProxyObject(String uuid) { + idList.add(uuid); return; } - - public ArrayList getIdProxyList() { + + public ArrayList getIdProxyList() { return idList; } - + public void setCSErrorCode(int cserrcode) { this.csErrorCode = cserrcode; } - + public int getCSErrorCode() { return this.csErrorCode; } diff --git a/api/src/com/cloud/exception/CloudExecutionException.java b/api/src/com/cloud/exception/CloudExecutionException.java deleted file mode 100755 index 74b116a0983..00000000000 --- a/api/src/com/cloud/exception/CloudExecutionException.java +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.exception; - -import java.util.HashMap; -import com.cloud.utils.exception.RuntimeCloudException; - -import com.cloud.utils.SerialVersionUID; - -/** - * - */ -public class CloudExecutionException extends RuntimeCloudException { - private final static long serialVersionUID = SerialVersionUID.CloudExecutionException; - - private final ErrorCode code; - private final HashMap details; - - public CloudExecutionException(ErrorCode code, String message, Throwable cause) { - super(message, cause); - this.code = code; - details = new HashMap(); - } - - public ErrorCode getErrorCode() { - return code; - } - - public String getErrorMessage() { - return new StringBuilder("Error Code=").append(code).append("; Error Message=").append(super.toString()).toString(); - } - - @Override - public String toString() { - StringBuilder buff = new StringBuilder(); - buff.append("Error Code=").append(code); - buff.append("; Error Message=").append(super.toString()); - if (details.size() > 0) { - buff.append("; Error Details=").append(details.toString()); - } - return buff.toString(); - } -} diff --git a/api/src/com/cloud/exception/ConcurrentOperationException.java b/api/src/com/cloud/exception/ConcurrentOperationException.java index 54826d6a5e9..cfe6ba3fa0a 100644 --- a/api/src/com/cloud/exception/ConcurrentOperationException.java +++ b/api/src/com/cloud/exception/ConcurrentOperationException.java @@ -19,9 +19,9 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class ConcurrentOperationException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.ConcurrentOperationException; - + public ConcurrentOperationException(String msg) { super(msg); } diff --git a/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java b/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java index 7afcfe64575..a777afabeb7 100644 --- a/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java +++ b/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java @@ -21,7 +21,7 @@ import com.cloud.utils.SerialVersionUID; public class ConflictingNetworkSettingsException extends CloudException { private static final long serialVersionUID = SerialVersionUID.ConflictingNetworkSettingException; - + public ConflictingNetworkSettingsException() { super(); } diff --git a/api/src/com/cloud/exception/ConnectionException.java b/api/src/com/cloud/exception/ConnectionException.java index 966e39b3fd2..b3f0726fd34 100644 --- a/api/src/com/cloud/exception/ConnectionException.java +++ b/api/src/com/cloud/exception/ConnectionException.java @@ -25,26 +25,26 @@ import com.cloud.utils.SerialVersionUID; * processing. Upon receiving this exception, the AgentManager will * immediately place the agent under alert. When the function to enable * to disable the agent, the agent is disabled. - * should be disconnected and reconnected to "refresh" all resource + * should be disconnected and reconnected to "refresh" all resource * information. This is useful when the Listener needed to perform setup * on the agent and decided it is best to flush connection and reconnect. * situation where it keeps throwing ConnectionException. */ public class ConnectionException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.ConnectionException; boolean _error; public ConnectionException(boolean setupError, String msg) { this(setupError, msg, null); } - + public ConnectionException(boolean setupError, String msg, Throwable cause) { super(msg, cause); _error = setupError; - + } - + public boolean isSetupError() { return _error; } diff --git a/api/src/com/cloud/exception/DiscoveredWithErrorException.java b/api/src/com/cloud/exception/DiscoveredWithErrorException.java index f59066f83c1..ee59baf45da 100644 --- a/api/src/com/cloud/exception/DiscoveredWithErrorException.java +++ b/api/src/com/cloud/exception/DiscoveredWithErrorException.java @@ -19,13 +19,13 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class DiscoveredWithErrorException extends DiscoveryException { - + private static final long serialVersionUID = SerialVersionUID.DiscoveredWithErrorException; public DiscoveredWithErrorException(String msg) { this(msg, null); } - + public DiscoveredWithErrorException(String msg, Throwable cause) { super(msg, cause); } diff --git a/api/src/com/cloud/exception/DiscoveryException.java b/api/src/com/cloud/exception/DiscoveryException.java index 10a7c5b338f..62ae2724ea5 100644 --- a/api/src/com/cloud/exception/DiscoveryException.java +++ b/api/src/com/cloud/exception/DiscoveryException.java @@ -19,13 +19,13 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class DiscoveryException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.DiscoveryException; public DiscoveryException(String msg) { this(msg, null); } - + public DiscoveryException(String msg, Throwable cause) { super(msg, cause); } diff --git a/api/src/com/cloud/exception/ErrorCode.java b/api/src/com/cloud/exception/ErrorCode.java deleted file mode 100755 index 15d9b7e8a1e..00000000000 --- a/api/src/com/cloud/exception/ErrorCode.java +++ /dev/null @@ -1,52 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.exception; - -import java.util.HashSet; - -/** - */ -public class ErrorCode { - String code; - private static HashSet s_codes = new HashSet(); - - public ErrorCode(String code) { - this.code = code; - assert !s_codes.contains(this) : "There is already an error code registered for this code: " + code; - s_codes.add(this); - } - - public String getCode() { - return code; - } - - @Override - public int hashCode() { - return code.hashCode(); - } - - @Override - public boolean equals(Object that) { - if (!(that instanceof ErrorCode)) { - return false; - } - - return this.code.equals(((ErrorCode)that).code); - } - - public final static ErrorCode UnableToReachResource = new ErrorCode("resource.unavailable"); -} diff --git a/api/src/com/cloud/exception/HAStateException.java b/api/src/com/cloud/exception/HAStateException.java index aaa5e756aa1..cb2517446ba 100644 --- a/api/src/com/cloud/exception/HAStateException.java +++ b/api/src/com/cloud/exception/HAStateException.java @@ -23,9 +23,9 @@ import com.cloud.utils.SerialVersionUID; * done with it. Hence this special state. */ public class HAStateException extends ManagementServerException { - + private static final long serialVersionUID = SerialVersionUID.HAStateException; - + public HAStateException(String msg) { super(msg); } diff --git a/api/src/com/cloud/exception/InsufficientCapacityException.java b/api/src/com/cloud/exception/InsufficientCapacityException.java index 8a0557f8c06..51a4e593858 100755 --- a/api/src/com/cloud/exception/InsufficientCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientCapacityException.java @@ -49,7 +49,7 @@ public abstract class InsufficientCapacityException extends CloudException { /** * @return the id of the object that it is insufficient in. Note that this method is * marked such that if the id is not set, then it will throw NullPointerException. - * This is intended as you should check to see if the Scope is present before + * This is intended as you should check to see if the Scope is present before * accessing this method. */ public long getId() { diff --git a/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java b/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java index 09a077bfc24..71ec16d88f3 100644 --- a/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java @@ -20,11 +20,11 @@ import com.cloud.utils.SerialVersionUID; public class InsufficientNetworkCapacityException extends InsufficientCapacityException { private static final long serialVersionUID = SerialVersionUID.InsufficientAddressCapacityException; - + protected InsufficientNetworkCapacityException() { super(); } - + public InsufficientNetworkCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientServerCapacityException.java b/api/src/com/cloud/exception/InsufficientServerCapacityException.java index 4a30595c12b..af34e579943 100755 --- a/api/src/com/cloud/exception/InsufficientServerCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientServerCapacityException.java @@ -24,13 +24,13 @@ import com.cloud.utils.SerialVersionUID; * trying to start. */ public class InsufficientServerCapacityException extends InsufficientCapacityException { - + private static final long serialVersionUID = SerialVersionUID.InsufficientServerCapacityException; - + public InsufficientServerCapacityException(String msg, Long clusterId) { this(msg, Cluster.class, clusterId); } - + public InsufficientServerCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientStorageCapacityException.java b/api/src/com/cloud/exception/InsufficientStorageCapacityException.java index f8ec10610ce..c70bfc38c8c 100755 --- a/api/src/com/cloud/exception/InsufficientStorageCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientStorageCapacityException.java @@ -24,13 +24,13 @@ import com.cloud.utils.SerialVersionUID; * storage space to create the VM. */ public class InsufficientStorageCapacityException extends InsufficientCapacityException { - + private static final long serialVersionUID = SerialVersionUID.InsufficientStorageCapacityException; - + public InsufficientStorageCapacityException(String msg, long id) { this(msg, StoragePool.class, id); } - + public InsufficientStorageCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java b/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java index 10d9ffc82ce..4741baaf62d 100644 --- a/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java +++ b/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java @@ -21,11 +21,11 @@ import com.cloud.utils.SerialVersionUID; public class InsufficientVirtualNetworkCapcityException extends InsufficientNetworkCapacityException { private static final long serialVersionUID = SerialVersionUID.InsufficientVirtualNetworkCapacityException; - + public InsufficientVirtualNetworkCapcityException(String msg, Class scope, Long id) { super(msg, scope, id); } - + public InsufficientVirtualNetworkCapcityException(String msg, long podId) { this(msg, Pod.class, podId); } diff --git a/api/src/com/cloud/exception/PermissionDeniedException.java b/api/src/com/cloud/exception/PermissionDeniedException.java index 4900afcd67a..638b762d4c4 100644 --- a/api/src/com/cloud/exception/PermissionDeniedException.java +++ b/api/src/com/cloud/exception/PermissionDeniedException.java @@ -18,7 +18,7 @@ package com.cloud.exception; import java.util.List; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.user.Account; import com.cloud.utils.SerialVersionUID; import com.cloud.utils.exception.CloudRuntimeException; diff --git a/api/src/com/cloud/exception/ResourceUnavailableException.java b/api/src/com/cloud/exception/ResourceUnavailableException.java index 484659a6a94..30daf566b03 100644 --- a/api/src/com/cloud/exception/ResourceUnavailableException.java +++ b/api/src/com/cloud/exception/ResourceUnavailableException.java @@ -23,21 +23,21 @@ public class ResourceUnavailableException extends CloudException { Class _scope; long _id; - + public ResourceUnavailableException(String msg, Class scope, long resourceId) { this(msg, scope, resourceId, null); } - + public ResourceUnavailableException(String msg, Class scope, long resourceId, Throwable cause) { super(new StringBuilder("Resource [").append(scope.getSimpleName()).append(":").append(resourceId).append("] is unreachable: ").append(msg).toString(), cause); _scope = scope; _id = resourceId; } - + public Class getScope() { return _scope; } - + public long getResourceId() { return _id; } diff --git a/api/src/com/cloud/exception/StorageUnavailableException.java b/api/src/com/cloud/exception/StorageUnavailableException.java index 7b443a91087..6db16290237 100644 --- a/api/src/com/cloud/exception/StorageUnavailableException.java +++ b/api/src/com/cloud/exception/StorageUnavailableException.java @@ -20,9 +20,9 @@ import com.cloud.storage.StoragePool; import com.cloud.utils.SerialVersionUID; /** - * If the cause is due to storage pool unavailable, calling + * If the cause is due to storage pool unavailable, calling * problem with. - * + * */ public class StorageUnavailableException extends ResourceUnavailableException { private static final long serialVersionUID = SerialVersionUID.StorageUnavailableException; @@ -33,11 +33,11 @@ public class StorageUnavailableException extends ResourceUnavailableException { public StorageUnavailableException(String msg, long poolId, Throwable cause) { this(msg, StoragePool.class, poolId, cause); } - + public StorageUnavailableException(String msg, Class scope, long resourceId) { this(msg, scope, resourceId, null); } - + public StorageUnavailableException(String msg, Class scope, long resourceId, Throwable th) { super(msg, scope, resourceId, th); } diff --git a/api/src/com/cloud/host/Host.java b/api/src/com/cloud/host/Host.java index 1bac0d20a40..bd26f81c8c2 100755 --- a/api/src/com/cloud/host/Host.java +++ b/api/src/com/cloud/host/Host.java @@ -21,12 +21,14 @@ import java.util.Date; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.resource.ResourceState; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Host represents one particular host server. */ -public interface Host extends StateObject { +public interface Host extends StateObject, Identity, InternalIdentity { public enum Type { Storage(false), Routing(false), @@ -61,11 +63,6 @@ public interface Host extends StateObject { } } - /** - * @return id of the host. - */ - long getId(); - /** * @return name of the machine. */ @@ -198,6 +195,6 @@ public interface Host extends StateObject { String getHypervisorVersion(); boolean isInMaintenanceStates(); - - ResourceState getResourceState(); + + ResourceState getResourceState(); } diff --git a/api/src/com/cloud/host/HostEnvironment.java b/api/src/com/cloud/host/HostEnvironment.java index 31849748486..89077b5fed1 100644 --- a/api/src/com/cloud/host/HostEnvironment.java +++ b/api/src/com/cloud/host/HostEnvironment.java @@ -22,29 +22,29 @@ package com.cloud.host; * the environment. */ public class HostEnvironment { - + public String managementIpAddress; public String managementNetmask; public String managementGateway; public String managementVlan; - + public String[] neighborHosts; - + public String storageIpAddress; public String storageNetwork; public String storageGateway; public String storageVlan; public String secondaryStroageIpAddress; - + public String storage2IpAddress; public String storage2Network; public String storage2Gateway; public String storage2Vlan; public String secondaryStorageIpAddress2; - + public String[] neighborStorages; public String[] neighborStorages2; - + public String publicIpAddress; public String publicNetmask; public String publicGateway; diff --git a/api/src/com/cloud/host/HostStats.java b/api/src/com/cloud/host/HostStats.java index e8fa19ef3d1..803b1484b2b 100755 --- a/api/src/com/cloud/host/HostStats.java +++ b/api/src/com/cloud/host/HostStats.java @@ -17,7 +17,7 @@ package com.cloud.host; public interface HostStats { - + // host related stats public double getCpuUtilization(); public double getNetworkWriteKBs(); @@ -27,7 +27,7 @@ public interface HostStats { public String getEntityType(); public double getUsedMemory(); public HostStats getHostStats(); - + // public double getAverageLoad(); - // public double getXapiMemoryUsageKBs(); + // public double getXapiMemoryUsageKBs(); } diff --git a/api/src/com/cloud/host/Status.java b/api/src/com/cloud/host/Status.java index aed35cbb040..97b151dc723 100755 --- a/api/src/com/cloud/host/Status.java +++ b/api/src/com/cloud/host/Status.java @@ -32,25 +32,25 @@ public enum Status { Removed(true, false, true), Error(true, false, true), Rebalancing(true, false, true); - + private final boolean updateManagementServer; private final boolean checkManagementServer; private final boolean lostConnection; - + private Status(boolean updateConnection, boolean checkManagementServer, boolean lostConnection) { this.updateManagementServer = updateConnection; this.checkManagementServer = checkManagementServer; this.lostConnection = lostConnection; } - + public boolean updateManagementServer() { return updateManagementServer; } - + public boolean checkManagementServer() { return checkManagementServer; } - + public boolean lostConnection() { return lostConnection; } @@ -82,16 +82,16 @@ public enum Status { public String getDescription() { return comment; } - + public boolean isUserRequest() { return isUserRequest; } } - + public static StateMachine2 getStateMachine() { return s_fsm; } - + public Status getNextStatus(Event e) throws NoTransitionException { return s_fsm.getNextState(this, e); } @@ -100,7 +100,7 @@ public enum Status { List from = s_fsm.getFromStates(this, e); return from.toArray(new Status[from.size()]); } - + public Set getPossibleEvents() { return s_fsm.getPossibleEvents(this); } diff --git a/api/src/com/cloud/hypervisor/Hypervisor.java b/api/src/com/cloud/hypervisor/Hypervisor.java index 25dd8b1458d..2e0012dca6f 100644 --- a/api/src/com/cloud/hypervisor/Hypervisor.java +++ b/api/src/com/cloud/hypervisor/Hypervisor.java @@ -23,7 +23,7 @@ public class Hypervisor { XenServer, KVM, VMware, - Hyperv, + Hyperv, VirtualBox, Parralels, BareMetal, diff --git a/api/src/com/cloud/hypervisor/HypervisorCapabilities.java b/api/src/com/cloud/hypervisor/HypervisorCapabilities.java index f91da354c96..efb8a6a208b 100644 --- a/api/src/com/cloud/hypervisor/HypervisorCapabilities.java +++ b/api/src/com/cloud/hypervisor/HypervisorCapabilities.java @@ -17,16 +17,14 @@ package com.cloud.hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * HypervisorCapability represents one particular hypervisor version's capabilities. */ -public interface HypervisorCapabilities { - /** - * @return id of the host. - */ - long getId(); +public interface HypervisorCapabilities extends Identity, InternalIdentity{ /** * @return type of hypervisor diff --git a/api/src/com/cloud/hypervisor/HypervisorGuru.java b/api/src/com/cloud/hypervisor/HypervisorGuru.java index d3608dcc347..b4a0b06a7af 100644 --- a/api/src/com/cloud/hypervisor/HypervisorGuru.java +++ b/api/src/com/cloud/hypervisor/HypervisorGuru.java @@ -27,28 +27,28 @@ import com.cloud.vm.VirtualMachineProfile; public interface HypervisorGuru extends Adapter { HypervisorType getHypervisorType(); - + /** * Convert from a virtual machine to the - * virtual machine that the hypervisor expects. - * @param vm + * virtual machine that the hypervisor expects. + * @param vm * @return */ VirtualMachineTO implement(VirtualMachineProfile vm); - + /** * Give hypervisor guru opportunity to decide if certain command needs to be delegated to other host, mainly to secondary storage VM host * @param hostId original hypervisor host * @param cmd command that is going to be sent, hypervisor guru usually needs to register various context objects into the command object - * + * * @return delegated host id if the command will be delegated */ long getCommandHostDelegation(long hostId, Command cmd); - + /** * @return true if VM can be migrated independently with CloudStack, and therefore CloudStack needs to track and reflect host change * into CloudStack database, false if CloudStack enforces VM sync logic - * + * */ boolean trackVmHostChange(); diff --git a/api/src/com/cloud/network/IpAddress.java b/api/src/com/cloud/network/IpAddress.java index f67a1fa3c46..0ac7f500e2c 100644 --- a/api/src/com/cloud/network/IpAddress.java +++ b/api/src/com/cloud/network/IpAddress.java @@ -18,28 +18,30 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * * - Allocated = null * - AccountId = null * - DomainId = null - * + * * - State = Allocated * - AccountId = account owner. * - DomainId = domain of the account owner. * - Allocated = time it was allocated. */ -public interface IpAddress extends ControlledEntity { +public interface IpAddress extends ControlledEntity, Identity, InternalIdentity { enum State { Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet. Allocated, // The IP address is in used. Releasing, // The IP address is being released for other network elements and is not ready for allocation. Free // The IP address is ready to be allocated. } - + enum Purpose { StaticNat, Lb @@ -67,11 +69,6 @@ public interface IpAddress extends ControlledEntity { public Long getPhysicalNetworkId(); - /** - * @return database id. - */ - long getId(); - void setState(IpAddress.State state); Long getAllocatedToAccountId(); @@ -89,5 +86,4 @@ public interface IpAddress extends ControlledEntity { * @param vpcId */ void setVpcId(Long vpcId); - } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 188ef92e57b..c91f6a9b80d 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -16,12 +16,14 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.utils.fsm.FiniteState; import com.cloud.utils.fsm.StateMachine; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; import java.net.URI; import java.util.ArrayList; @@ -31,7 +33,7 @@ import java.util.Set; /** * owned by an account. */ -public interface Network extends ControlledEntity { +public interface Network extends ControlledEntity, InternalIdentity, Identity { public enum GuestType { Shared, @@ -45,10 +47,10 @@ public interface Network extends ControlledEntity { public static final Service Dhcp = new Service("Dhcp"); public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification); public static final Service Gateway = new Service("Gateway"); - public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, + public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, Capability.MultipleIps, Capability.TrafficStatistics); public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedLBIsolation, - Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, + Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb); public static final Service UserData = new Service("UserData"); public static final Service SourceNat = new Service("SourceNat", Capability.SupportedSourceNatTypes, Capability.RedundantRouter); @@ -168,9 +170,9 @@ public interface Network extends ControlledEntity { public static final Capability AllowDnsSuffixModification = new Capability("AllowDnsSuffixModification"); public static final Capability RedundantRouter = new Capability("RedundantRouter"); public static final Capability ElasticIp = new Capability("ElasticIp"); - public static final Capability AssociatePublicIP = new Capability("AssociatePublicIP"); public static final Capability ElasticLb = new Capability("ElasticLb"); public static final Capability AutoScaleCounters = new Capability("AutoScaleCounters"); + public static final Capability InlineMode = new Capability("InlineMode"); private String name; @@ -251,11 +253,6 @@ public interface Network extends ControlledEntity { } } - /** - * @return id of the network profile. Null means the network profile is not from the database. - */ - long getId(); - String getName(); Mode getMode(); @@ -300,5 +297,5 @@ public interface Network extends ControlledEntity { * @return */ Long getVpcId(); - + } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index cd25d9f677e..b5c463de375 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -21,9 +21,11 @@ import java.net.URI; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.api.InternalIdentity; public class NetworkProfile implements Network { private long id; + private String uuid; private long dataCenterId; private long ownerId; private long domainId; @@ -51,6 +53,7 @@ public class NetworkProfile implements Network { public NetworkProfile(Network network) { this.id = network.getId(); + this.uuid = network.getUuid(); this.broadcastUri = network.getBroadcastUri(); this.dataCenterId = network.getDataCenterId(); this.ownerId = network.getAccountId(); @@ -105,6 +108,12 @@ public class NetworkProfile implements Network { return id; } + + @Override + public String getUuid() { + return uuid; + } + @Override public long getDataCenterId() { return dataCenterId; diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index b93be6fcb3d..786afb1e107 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -18,10 +18,10 @@ package com.cloud.network; import java.util.List; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -42,8 +42,7 @@ public interface NetworkService { List getIsolatedNetworksOwnedByAccountInZone(long zoneId, Account owner); - - IpAddress allocateIP(Account ipOwner, long zoneId, Long networkId) throws ResourceAllocationException, + IpAddress allocateIP(Account ipOwner, boolean isSystem, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException; boolean releaseIpAddress(long ipAddressId) throws InsufficientAddressCapacityException; @@ -62,6 +61,8 @@ public interface NetworkService { Network getNetwork(long networkId); + Network getNetwork(String networkUuid); + IpAddress getIp(long id); @@ -72,10 +73,10 @@ public interface NetworkService { PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags, String name); - Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, + Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name); - PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, + PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state); boolean deletePhysicalNetwork(Long id); @@ -102,7 +103,7 @@ public interface NetworkService { long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType); - PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, + PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan); PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id); @@ -126,10 +127,10 @@ public interface NetworkService { * @param networkId * @param entityId * @return - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException - * @throws ResourceAllocationException - * @throws InsufficientAddressCapacityException + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ResourceAllocationException + * @throws InsufficientAddressCapacityException */ IpAddress associateIPToNetwork(long ipId, long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException; @@ -146,12 +147,12 @@ public interface NetworkService { * @param networkOwnerId * @param vpcId TODO * @return - * @throws InsufficientCapacityException - * @throws ConcurrentOperationException - * @throws ResourceAllocationException + * @throws InsufficientCapacityException + * @throws ConcurrentOperationException + * @throws ResourceAllocationException */ Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, - String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId) + String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; } diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java index b96eaa2ff6c..b15661910b4 100755 --- a/api/src/com/cloud/network/Networks.java +++ b/api/src/com/cloud/network/Networks.java @@ -23,7 +23,7 @@ import com.cloud.utils.exception.CloudRuntimeException; /** * Network includes all of the enums used within networking. - * + * */ public class Networks { diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java index be4b1d0d352..a495092879e 100644 --- a/api/src/com/cloud/network/PhysicalNetwork.java +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -16,12 +16,15 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.List; /** - * + * */ -public interface PhysicalNetwork { +public interface PhysicalNetwork extends Identity, InternalIdentity { public enum State { Disabled, @@ -40,8 +43,6 @@ public interface PhysicalNetwork { ZONE; } - long getId(); - BroadcastDomainRange getBroadcastDomainRange(); // TrafficType getTrafficType(); @@ -60,8 +61,6 @@ public interface PhysicalNetwork { String getSpeed(); - String getUuid(); - String getName(); } diff --git a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java index 1b913115aa4..0a433dcbc05 100644 --- a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java +++ b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java @@ -19,11 +19,12 @@ package com.cloud.network; import java.util.List; import com.cloud.network.Network.Service; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * */ -public interface PhysicalNetworkServiceProvider { +public interface PhysicalNetworkServiceProvider extends InternalIdentity { public enum State { Disabled, diff --git a/api/src/com/cloud/network/PhysicalNetworkTrafficType.java b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java index 0c0bfa1304e..62400e80a9e 100644 --- a/api/src/com/cloud/network/PhysicalNetworkTrafficType.java +++ b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java @@ -17,13 +17,13 @@ package com.cloud.network; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * */ -public interface PhysicalNetworkTrafficType { - - long getId(); +public interface PhysicalNetworkTrafficType extends InternalIdentity, Identity { long getPhysicalNetworkId(); @@ -36,6 +36,4 @@ public interface PhysicalNetworkTrafficType { String getVmwareNetworkLabel(); String getSimulatorNetworkLabel(); - - String getUuid(); } diff --git a/api/src/com/cloud/network/PublicIpAddress.java b/api/src/com/cloud/network/PublicIpAddress.java index 5d117b84243..21dae54202a 100644 --- a/api/src/com/cloud/network/PublicIpAddress.java +++ b/api/src/com/cloud/network/PublicIpAddress.java @@ -16,19 +16,20 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.dc.Vlan; +import org.apache.cloudstack.api.InternalIdentity; /** */ -public interface PublicIpAddress extends ControlledEntity, IpAddress, Vlan { - +public interface PublicIpAddress extends ControlledEntity, IpAddress, Vlan, InternalIdentity { + String getMacAddress(); - + public String getNetmask(); - + public String getGateway(); - + @Override public String getVlanTag(); -} \ No newline at end of file +} diff --git a/api/src/com/cloud/network/RemoteAccessVpn.java b/api/src/com/cloud/network/RemoteAccessVpn.java index 162e0fce133..1b463309a5f 100644 --- a/api/src/com/cloud/network/RemoteAccessVpn.java +++ b/api/src/com/cloud/network/RemoteAccessVpn.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; public interface RemoteAccessVpn extends ControlledEntity { enum State { @@ -24,7 +24,7 @@ public interface RemoteAccessVpn extends ControlledEntity { Running, Removed } - + long getServerAddressId(); String getIpRange(); String getIpsecPresharedKey(); diff --git a/api/src/com/cloud/network/Site2SiteCustomerGateway.java b/api/src/com/cloud/network/Site2SiteCustomerGateway.java index 8950c771705..3a5438575d9 100644 --- a/api/src/com/cloud/network/Site2SiteCustomerGateway.java +++ b/api/src/com/cloud/network/Site2SiteCustomerGateway.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,10 +18,11 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteCustomerGateway extends ControlledEntity { - public long getId(); +public interface Site2SiteCustomerGateway extends ControlledEntity, Identity, InternalIdentity { public String getGatewayIp(); public String getGuestCidrList(); public String getIpsecPsk(); diff --git a/api/src/com/cloud/network/Site2SiteVpnConnection.java b/api/src/com/cloud/network/Site2SiteVpnConnection.java index 6cf52a94943..810f9992d93 100644 --- a/api/src/com/cloud/network/Site2SiteVpnConnection.java +++ b/api/src/com/cloud/network/Site2SiteVpnConnection.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,9 +18,10 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteVpnConnection extends ControlledEntity { +public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdentity { enum State { Pending, Connected, @@ -28,6 +29,7 @@ public interface Site2SiteVpnConnection extends ControlledEntity { Error, } public long getId(); + public String getUuid(); public long getVpnGatewayId(); public long getCustomerGatewayId(); public State getState(); diff --git a/api/src/com/cloud/network/Site2SiteVpnGateway.java b/api/src/com/cloud/network/Site2SiteVpnGateway.java index 52ec5971c14..81379132844 100644 --- a/api/src/com/cloud/network/Site2SiteVpnGateway.java +++ b/api/src/com/cloud/network/Site2SiteVpnGateway.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -18,10 +18,11 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteVpnGateway extends ControlledEntity { - public long getId(); +public interface Site2SiteVpnGateway extends ControlledEntity, Identity, InternalIdentity { public long getAddrId(); public long getVpcId(); public Date getRemoved(); diff --git a/api/src/com/cloud/network/StorageNetworkService.java b/api/src/com/cloud/network/StorageNetworkService.java index 86a8352316a..1bda247179c 100755 --- a/api/src/com/cloud/network/StorageNetworkService.java +++ b/api/src/com/cloud/network/StorageNetworkService.java @@ -19,18 +19,18 @@ package com.cloud.network; import java.sql.SQLException; import java.util.List; -import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.*; +import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import com.cloud.dc.StorageNetworkIpRange; +import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; public interface StorageNetworkService { StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException; void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd); - List listIpRange(listStorageNetworkIpRangeCmd cmd); + List listIpRange(ListStorageNetworkIpRangeCmd cmd); StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd); } diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index 300c9932829..7b553b29a7f 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.network; -import com.cloud.api.commands.UpgradeRouterCmd; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; @@ -26,29 +26,29 @@ import com.cloud.user.Account; public interface VirtualNetworkApplianceService { /** * Starts domain router - * + * * @param cmd * the command specifying router's id * @return DomainRouter object */ - VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, + VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** * Reboots domain router - * + * * @param cmd * the command specifying router's id * @return router if successful */ - VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, + VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter upgradeRouter(UpgradeRouterCmd cmd); /** * Stops domain router - * + * * @param id * of the router * @param forced diff --git a/api/src/com/cloud/network/VirtualRouterProvider.java b/api/src/com/cloud/network/VirtualRouterProvider.java index f0837d650cf..ed6a2741ba0 100644 --- a/api/src/com/cloud/network/VirtualRouterProvider.java +++ b/api/src/com/cloud/network/VirtualRouterProvider.java @@ -16,7 +16,10 @@ // under the License. package com.cloud.network; -public interface VirtualRouterProvider { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface VirtualRouterProvider extends InternalIdentity, Identity { public enum VirtualRouterProviderType { VirtualRouter, ElasticLoadBalancerVm, @@ -25,8 +28,6 @@ public interface VirtualRouterProvider { public VirtualRouterProviderType getType(); - public long getId(); - public boolean isEnabled(); public long getNspId(); diff --git a/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java b/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java index 03eb576bc8d..6e8fd38ba66 100644 --- a/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java @@ -32,7 +32,7 @@ public interface VpcVirtualNetworkApplianceService extends VirtualNetworkApplian * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ - boolean addVpcRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) + boolean addVpcRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** @@ -43,7 +43,7 @@ public interface VpcVirtualNetworkApplianceService extends VirtualNetworkApplian * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean removeVpcRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) + boolean removeVpcRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/VpnUser.java b/api/src/com/cloud/network/VpnUser.java index 07a3ee3343e..ad84e9178d6 100644 --- a/api/src/com/cloud/network/VpnUser.java +++ b/api/src/com/cloud/network/VpnUser.java @@ -16,17 +16,17 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VpnUser extends ControlledEntity { +public interface VpnUser extends ControlledEntity, InternalIdentity, Identity { enum State { Add, Revoke, Active } - long getId(); - String getUsername(); String getPassword(); diff --git a/api/src/com/cloud/network/as/AutoScalePolicy.java b/api/src/com/cloud/network/as/AutoScalePolicy.java index cef198f0947..7f94f355921 100644 --- a/api/src/com/cloud/network/as/AutoScalePolicy.java +++ b/api/src/com/cloud/network/as/AutoScalePolicy.java @@ -17,12 +17,15 @@ package com.cloud.network.as; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface AutoScalePolicy extends ControlledEntity { +public interface AutoScalePolicy extends ControlledEntity, InternalIdentity { long getId(); + String getUuid(); + public int getDuration(); public int getQuietTime(); diff --git a/api/src/com/cloud/network/as/AutoScaleService.java b/api/src/com/cloud/network/as/AutoScaleService.java index c1ca804bd68..daa8d191366 100644 --- a/api/src/com/cloud/network/as/AutoScaleService.java +++ b/api/src/com/cloud/network/as/AutoScaleService.java @@ -1,43 +1,31 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; import java.util.List; -import com.cloud.api.commands.CreateAutoScalePolicyCmd; -import com.cloud.api.commands.CreateAutoScaleVmGroupCmd; -import com.cloud.api.commands.CreateAutoScaleVmProfileCmd; -import com.cloud.api.commands.CreateConditionCmd; -import com.cloud.api.commands.CreateCounterCmd; -import com.cloud.api.commands.ListAutoScalePoliciesCmd; -import com.cloud.api.commands.ListAutoScaleVmGroupsCmd; -import com.cloud.api.commands.ListAutoScaleVmProfilesCmd; -import com.cloud.api.commands.ListConditionsCmd; -import com.cloud.api.commands.ListCountersCmd; -import com.cloud.api.commands.UpdateAutoScalePolicyCmd; -import com.cloud.api.commands.UpdateAutoScaleVmGroupCmd; -import com.cloud.api.commands.UpdateAutoScaleVmProfileCmd; +import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd; +import org.apache.cloudstack.api.command.user.autoscale.*; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmProfileCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListAutoScalePoliciesCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmGroupCmd; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.as.AutoScalePolicy; -import com.cloud.network.as.AutoScaleVmGroup; -import com.cloud.network.as.AutoScaleVmProfile; -import com.cloud.network.as.Condition; -import com.cloud.network.as.Counter; public interface AutoScaleService { diff --git a/api/src/com/cloud/network/as/AutoScaleVmGroup.java b/api/src/com/cloud/network/as/AutoScaleVmGroup.java index 6d41ae3a7e0..faa166d2bae 100644 --- a/api/src/com/cloud/network/as/AutoScaleVmGroup.java +++ b/api/src/com/cloud/network/as/AutoScaleVmGroup.java @@ -17,10 +17,11 @@ package com.cloud.network.as; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface AutoScaleVmGroup extends ControlledEntity { +public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity { String State_New = "new"; String State_Revoke = "revoke"; diff --git a/api/src/com/cloud/network/as/AutoScaleVmProfile.java b/api/src/com/cloud/network/as/AutoScaleVmProfile.java index 77f5ce45f98..3be5a3e8124 100644 --- a/api/src/com/cloud/network/as/AutoScaleVmProfile.java +++ b/api/src/com/cloud/network/as/AutoScaleVmProfile.java @@ -1,34 +1,37 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.network.as; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.network.as; import java.util.List; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; /** * AutoScaleVmProfile */ -public interface AutoScaleVmProfile extends ControlledEntity { +public interface AutoScaleVmProfile extends ControlledEntity, InternalIdentity { public long getId(); + public String getUuid(); + public Long getZoneId(); public Long getServiceOfferingId(); diff --git a/api/src/com/cloud/network/as/Condition.java b/api/src/com/cloud/network/as/Condition.java index b990731dd23..b09dc2e91a8 100644 --- a/api/src/com/cloud/network/as/Condition.java +++ b/api/src/com/cloud/network/as/Condition.java @@ -17,9 +17,11 @@ package com.cloud.network.as; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Condition extends ControlledEntity { +public interface Condition extends ControlledEntity, Identity, InternalIdentity { static enum Operator { EQ, GT, LT, GE, LE @@ -30,8 +32,4 @@ public interface Condition extends ControlledEntity { long getThreshold(); Operator getRelationalOperator(); - - String getUuid(); - - long getId(); } diff --git a/api/src/com/cloud/network/as/Counter.java b/api/src/com/cloud/network/as/Counter.java index d9e2e0a1e1f..207ec57b592 100644 --- a/api/src/com/cloud/network/as/Counter.java +++ b/api/src/com/cloud/network/as/Counter.java @@ -17,7 +17,10 @@ package com.cloud.network.as; -public interface Counter { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Counter extends InternalIdentity, Identity { public static enum Source { netscaler, @@ -29,8 +32,4 @@ public interface Counter { String getValue(); Source getSource(); - - String getUuid(); - - long getId(); } diff --git a/api/src/com/cloud/network/element/IpDeployer.java b/api/src/com/cloud/network/element/IpDeployer.java index 8036d4b7bf2..c92d3e3cf2d 100644 --- a/api/src/com/cloud/network/element/IpDeployer.java +++ b/api/src/com/cloud/network/element/IpDeployer.java @@ -21,6 +21,7 @@ import java.util.Set; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.PublicIpAddress; import com.cloud.utils.component.Adapter; @@ -34,4 +35,6 @@ public interface IpDeployer extends Adapter{ * @throws ResourceUnavailableException */ boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException; + + Provider getProvider(); } diff --git a/api/src/com/cloud/network/element/IpDeployingRequester.java b/api/src/com/cloud/network/element/IpDeployingRequester.java new file mode 100644 index 00000000000..01a11b570c1 --- /dev/null +++ b/api/src/com/cloud/network/element/IpDeployingRequester.java @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.network.element; + +import com.cloud.network.Network; + +public interface IpDeployingRequester { + /** + * Would return the IpDeployer can deploy IP for this element + * @param network + * @return IpDeployer object, or null if there is no deployer for this element + */ + IpDeployer getIpDeployer(Network network); +} diff --git a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java index 3c5474642a4..879ea0ed663 100644 --- a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java +++ b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.lb.LoadBalancingRule; -public interface LoadBalancingServiceProvider extends NetworkElement { +public interface LoadBalancingServiceProvider extends NetworkElement, IpDeployingRequester { /** * Apply rules * @param network @@ -32,13 +32,12 @@ public interface LoadBalancingServiceProvider extends NetworkElement { */ boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException; - IpDeployer getIpDeployer(Network network); /** * Validate rules * @param network * @param rule * @return true/false. true should be return if there are no validations. false should be return if any oneof the validation fails. - * @throws + * @throws */ boolean validateLBRule(Network network, LoadBalancingRule rule); } diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index 10ea5095b58..1ddd60b27de 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -41,25 +41,25 @@ import com.cloud.vm.VirtualMachineProfile; * Represents one network element that exists in a network. */ public interface NetworkElement extends Adapter { - + Map> getCapabilities(); - + /** - * NOTE: + * NOTE: * NetworkElement -> Network.Provider is a one-to-one mapping. While adding a new NetworkElement, one must add a new Provider name to Network.Provider. */ Provider getProvider(); - + /** - * Implement the network configuration as specified. + * Implement the network configuration as specified. * @param config fully specified network configuration. * @param offering network offering that originated the network configuration. * @return true if network configuration is now usable; false if not; null if not handled by this element. * @throws InsufficientNetworkCapacityException TODO */ - boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) + boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + /** * Prepare for a nic to be added into this network. * @param network @@ -72,10 +72,10 @@ public interface NetworkElement extends Adapter { * @throws ResourceUnavailableException * @throws InsufficientNetworkCapacityException */ - boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, - DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, + boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, + DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + /** * A nic is released from this network. * @param network @@ -86,9 +86,9 @@ public interface NetworkElement extends Adapter { * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, + boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; - + /** * The network is being shutdown. * @param network @@ -98,9 +98,9 @@ public interface NetworkElement extends Adapter { * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean shutdown(Network network, ReservationContext context, boolean cleanup) + boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException; - + /** * The network is being destroyed. * @param network @@ -109,14 +109,14 @@ public interface NetworkElement extends Adapter { * @throws ConcurrentOperationException */ boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; - + /** * Check if the instances of this Element are configured to be used on the physical network referred by this provider. * @param provider * @return boolean true/false */ boolean isReady(PhysicalNetworkServiceProvider provider); - + /** * The network service provider is being shutdown. This should shutdown all instances of this element deployed for this provider. * @param context @@ -125,15 +125,15 @@ public interface NetworkElement extends Adapter { * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) + boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; - + /** - * This should return true if out of multiple services provided by this element, only some can be enabled. If all the services MUST be provided, this should return false. + * This should return true if out of multiple services provided by this element, only some can be enabled. If all the services MUST be provided, this should return false. * @return true/false */ boolean canEnableIndividualServices(); - + /** * Would return true if the service combination is supported by the provider * @param services diff --git a/api/src/com/cloud/network/element/PortForwardingServiceProvider.java b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java index d6589515d2a..e99bc2fd416 100644 --- a/api/src/com/cloud/network/element/PortForwardingServiceProvider.java +++ b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.PortForwardingRule; -public interface PortForwardingServiceProvider extends NetworkElement { +public interface PortForwardingServiceProvider extends NetworkElement, IpDeployingRequester { /** * Apply rules * @param network @@ -31,6 +31,4 @@ public interface PortForwardingServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException; - - IpDeployer getIpDeployer(Network network); } diff --git a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java index 2eb0389226f..4950ed92cab 100644 --- a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java +++ b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java @@ -28,6 +28,6 @@ public interface RemoteAccessVPNServiceProvider extends Adapter { String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - + boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java b/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java index eadf8013602..dd451324a72 100644 --- a/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java +++ b/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -22,6 +22,6 @@ import com.cloud.utils.component.Adapter; public interface Site2SiteVpnServiceProvider extends Adapter { boolean startSite2SiteVpn(Site2SiteVpnConnection conn) throws ResourceUnavailableException; - + boolean stopSite2SiteVpn(Site2SiteVpnConnection conn) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/SourceNatServiceProvider.java b/api/src/com/cloud/network/element/SourceNatServiceProvider.java index af63c6018b9..eaf43f82edd 100644 --- a/api/src/com/cloud/network/element/SourceNatServiceProvider.java +++ b/api/src/com/cloud/network/element/SourceNatServiceProvider.java @@ -16,8 +16,5 @@ // under the License. package com.cloud.network.element; -import com.cloud.network.Network; - -public interface SourceNatServiceProvider extends NetworkElement { - IpDeployer getIpDeployer(Network network); +public interface SourceNatServiceProvider extends NetworkElement, IpDeployingRequester { } diff --git a/api/src/com/cloud/network/element/StaticNatServiceProvider.java b/api/src/com/cloud/network/element/StaticNatServiceProvider.java index 20174b17251..50f5e204658 100644 --- a/api/src/com/cloud/network/element/StaticNatServiceProvider.java +++ b/api/src/com/cloud/network/element/StaticNatServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.StaticNat; -public interface StaticNatServiceProvider extends NetworkElement { +public interface StaticNatServiceProvider extends NetworkElement, IpDeployingRequester { /** * Creates static nat rule (public IP to private IP mapping) on the network element * @param config @@ -31,6 +31,4 @@ public interface StaticNatServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException; - - IpDeployer getIpDeployer(Network network); } diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index bf8cad27946..3ba2045cfd6 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -18,8 +18,8 @@ package com.cloud.network.element; import java.util.List; -import com.cloud.api.commands.ConfigureVirtualRouterElementCmd; -import com.cloud.api.commands.ListVirtualRouterElementsCmd; +import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; import com.cloud.utils.component.PluggableService; diff --git a/api/src/com/cloud/network/element/VpcProvider.java b/api/src/com/cloud/network/element/VpcProvider.java index aa5d2245a44..482fe6245a7 100644 --- a/api/src/com/cloud/network/element/VpcProvider.java +++ b/api/src/com/cloud/network/element/VpcProvider.java @@ -36,7 +36,7 @@ public interface VpcProvider extends NetworkElement{ * @param vpc fully specified vpc configuration. * @throws InsufficientNetworkCapacityException TODO */ - boolean implementVpc(Vpc vpc, DeployDestination dest, ReservationContext context) + boolean implementVpc(Vpc vpc, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** @@ -47,10 +47,10 @@ public interface VpcProvider extends NetworkElement{ * @throws ResourceUnavailableException */ boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean createPrivateGateway(PrivateGateway gateway) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean deletePrivateGateway(PrivateGateway privateGateway) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean applyStaticRoutes(Vpc vpc, List routes) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/firewall/FirewallService.java b/api/src/com/cloud/network/firewall/FirewallService.java index 07c2fb5a838..3858499b2bb 100644 --- a/api/src/com/cloud/network/firewall/FirewallService.java +++ b/api/src/com/cloud/network/firewall/FirewallService.java @@ -19,7 +19,7 @@ package com.cloud.network.firewall; import java.util.List; -import com.cloud.api.commands.ListFirewallRulesCmd; +import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; @@ -33,7 +33,7 @@ public interface FirewallService { /** * Revokes a firewall rule - * + * * @param ruleId * the id of the rule to revoke. * @return diff --git a/api/src/com/cloud/network/firewall/NetworkACLService.java b/api/src/com/cloud/network/firewall/NetworkACLService.java index 10896b6dc74..a1fb02cb71f 100644 --- a/api/src/com/cloud/network/firewall/NetworkACLService.java +++ b/api/src/com/cloud/network/firewall/NetworkACLService.java @@ -19,7 +19,7 @@ package com.cloud.network.firewall; import java.util.List; -import com.cloud.api.commands.ListNetworkACLsCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; @@ -29,7 +29,7 @@ import com.cloud.utils.Pair; public interface NetworkACLService { FirewallRule getNetworkACL(long ruleId); boolean applyNetworkACLs(long networkId, Account caller) throws ResourceUnavailableException; - + /** * @param createNetworkACLCmd * @return @@ -46,5 +46,5 @@ public interface NetworkACLService { * @return */ Pair, Integer> listNetworkACLs(ListNetworkACLsCmd cmd); - + } diff --git a/api/src/com/cloud/network/guru/NetworkGuru.java b/api/src/com/cloud/network/guru/NetworkGuru.java index 9b8c04b4fc3..4a9b871e240 100755 --- a/api/src/com/cloud/network/guru/NetworkGuru.java +++ b/api/src/com/cloud/network/guru/NetworkGuru.java @@ -35,7 +35,7 @@ import com.cloud.vm.VirtualMachineProfile; /** * - Designs a virtual network depending on the network offering. * - Implements the virtual network when a virtual machine requires the network to be started. - * + * * There can be multiple NetworkGurus in a CloudStack system. Each NetworkGuru * resources when VMs are gone. * @@ -44,28 +44,28 @@ import com.cloud.vm.VirtualMachineProfile; * This means the NetworkGuru checks the parameters such as cidr, gateway, * vlan, etc and returns a network that can work with those paremeters. * Note that at this point the network is only a virtual network. It has - * not been substantiated with resources, such as vlan, to make the network + * not been substantiated with resources, such as vlan, to make the network * functional in the physical environment. At this stage, the network is in - * Allocated state. - * - * - When the first virtual machine is about to be started and requires network + * Allocated state. + * + * - When the first virtual machine is about to be started and requires network * services, the guest network needs to have resources to make it usable * within the physical environment. At this time, the NetworkGuru is * called with the implement() method to acquire those resources. - * + * * - For every virtual machine starting in the network, the NetworkGuru is * asked via the reserve() method to make sure everything the virtual * machine needs to be functional in the network is reserved. - * + * * - For every virtual machine being stopped in the network, the NetworkGuru * is informed via the release() method to make sure resources occupied * by the virtual machine is released. - * + * * - If all virtual machines within the network have been stopped, the guest * network is garbage collected. When a guest network is garbage collected * the NetworkGuru is informed via the shutdown() method to release any * resources it allocated to that network. - * + * * - When a guest network is being deleted, the NetworkGuru is informed via * the trash() method. * @@ -74,18 +74,18 @@ public interface NetworkGuru extends Adapter { /** * Cloud stack requires the NetworkGuru to design a guest network given * the software packages Once a NetworkGuru returns the designed network, - * that NetworkGuru is forever associated with the guest network. It is + * that NetworkGuru is forever associated with the guest network. It is * very important for the NetworkGuru implementation to be very specific * about the network it is responsible for designing. Things that can * be used to make determination can be isolation methods, services * provided on the guest network and the service provider that's on the * guest network. - * + * * If a network is already fully substantiated with the necessary resources - * during this design phase, then the state should be set to Setup. If + * during this design phase, then the state should be set to Setup. If * the resources are not allocated at this point, the state should be set - * to Allocated. - * + * to Allocated. + * * @param offering network offering that contains the package of services * the end user intends to use on that network. * @param plan where is this network being deployed. @@ -99,29 +99,29 @@ public interface NetworkGuru extends Adapter { * For guest networks that are in Allocated state after the design stage, * resources are allocated when the guest network is actually being used * by a virtual machine. implement() is called to acquire those resources. - * + * * @param network network to be implemented. * @param offering network offering that the network was created with. * @param destination where the network is being deployed in. * @return a fully implemented Network. - * @throws InsufficientVirtualNetworkCapcityException if there's not + * @throws InsufficientVirtualNetworkCapcityException if there's not * enough resources to make the guest network usable in the physical - * environment. At this time, the admin generally must be involved to + * environment. At this time, the admin generally must be involved to * allocate more resources before any more guest network can be implemented. */ Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) throws InsufficientVirtualNetworkCapcityException; /** - * Once a guest network has been designed, virtual machines can be - * created. allocated() is called for the NetworkGuru to design a nic - * that will make the virtual machine work within the guest network. - * + * Once a guest network has been designed, virtual machines can be + * created. allocated() is called for the NetworkGuru to design a nic + * that will make the virtual machine work within the guest network. + * * @param network guest network that the virtual machine will be deployed in. - * @param nic nic information that the end user wants to set. The + * @param nic nic information that the end user wants to set. The * NetworkGuru should check this information with the guest * network settings to make sure everything will work. * @param vm virtual machine that is about to be deployed. - * @return NicProfile nic with all of the information + * @return NicProfile nic with all of the information * @throws InsufficientVirtualNetworkCapcityException if there's * insufficient capacity within the guest network. * @throws InsufficientAddressCapacityException if there are not addresses @@ -134,7 +134,7 @@ public interface NetworkGuru extends Adapter { * be allocated its resources in order for it to participate within the * guest network. reserve() is called for the NetworkGuru to make sure * that works. - * + * * @param nic nic that the vm is using to access the guest network. * @param network guest network the vm is in. * @param vm vm @@ -145,14 +145,14 @@ public interface NetworkGuru extends Adapter { * @throws InsufficientAddressCapacityException if there's not enough ip * addresses. * @throws ConcurrentOperationException if there are multiple operations - * happening on this guest network or vm. + * happening on this guest network or vm. */ void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException; /** * When a virtual machine is stopped, the NetworkGuru is informed via the - * release() method to release any resources. - * + * release() method to release any resources. + * * @param nic nic that the vm is using to access the guest network. * @param vm virtual machine * @param reservationId reservation id passed to it in the ReservationContext @@ -164,7 +164,7 @@ public interface NetworkGuru extends Adapter { * When a virtual machine is destroyed, the NetworkGuru is informed via * the deallocate() method to make sure any resources that are allocated * are released. - * + * * @param network guest network that the vm was running in. * @param nic nic that the vm was using to access the guest network. * @param vm virtual machine being destroyed. @@ -181,19 +181,19 @@ public interface NetworkGuru extends Adapter { void updateNicProfile(NicProfile profile, Network network); /** - * When no virtual machines are running in the network, the network is + * When no virtual machines are running in the network, the network is * shutdown and all physical resources are released. The NetworkGuru is * informed via the shutdown method(). - * + * * @param network guest network being shut down * @param offering network offering the guest network was created with. */ void shutdown(NetworkProfile network, NetworkOffering offering); /** - * When a guest network is destroyed, the NetworkGuru is informed via the + * When a guest network is destroyed, the NetworkGuru is informed via the * trash() method to recover any resources. - * + * * @param network guest network being destroyed. * @param offering network offering the guest network was created with. * @param owner owner of the network. diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java index 186ea566f97..b68b9cbddd4 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java @@ -26,6 +26,7 @@ import com.cloud.network.as.Counter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; public class LoadBalancingRule implements FirewallRule, LoadBalancer { private LoadBalancer lb; @@ -230,7 +231,7 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer { return null; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java index 0cf2ef94ace..4081f6efc2c 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java @@ -18,12 +18,9 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLBStickinessPolicyCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.ListLBStickinessPoliciesCmd; -import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; -import com.cloud.api.commands.ListLoadBalancerRulesCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.*; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.UpdateLoadBalancerRuleCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; @@ -36,7 +33,7 @@ import com.cloud.utils.Pair; public interface LoadBalancingRulesService { /** * Create a load balancer rule from the given ipAddress/port to the given private port - * + * * @param openFirewall * TODO * @param cmd @@ -53,7 +50,7 @@ public interface LoadBalancingRulesService { /** * Create a stickiness policy to a load balancer from the given stickiness method name and parameters in * (name,value) pairs. - * + * * @param cmd * the command specifying the stickiness method name, params (name,value pairs), policy name and * description. @@ -63,7 +60,7 @@ public interface LoadBalancingRulesService { public StickinessPolicy createLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws NetworkRuleConflictException; public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException; - + boolean deleteLBStickinessPolicy(long stickinessPolicyId, boolean apply); /** * Assign a virtual machine, or list of virtual machines, to a load balancer. @@ -77,7 +74,7 @@ public interface LoadBalancingRulesService { /** * List instances that have either been applied to a load balancer or are eligible to be assigned to a load * balancer. - * + * * @param cmd * @return list of vm instances that have been or can be applied to a load balancer */ @@ -85,7 +82,7 @@ public interface LoadBalancingRulesService { /** * List load balancer rules based on the given criteria - * + * * @param cmd * the command that specifies the criteria to use for listing load balancers. Load balancers can be * listed @@ -96,7 +93,7 @@ public interface LoadBalancingRulesService { /** * List stickiness policies based on the given criteria - * + * * @param cmd * the command specifies the load balancing rule id. * @return list of stickiness policies that match the criteria. @@ -107,4 +104,4 @@ public interface LoadBalancingRulesService { LoadBalancer findById(long LoadBalancer); -} \ No newline at end of file +} diff --git a/api/src/com/cloud/network/rules/FirewallRule.java b/api/src/com/cloud/network/rules/FirewallRule.java index f2a83af29fe..042665cdcf9 100644 --- a/api/src/com/cloud/network/rules/FirewallRule.java +++ b/api/src/com/cloud/network/rules/FirewallRule.java @@ -18,9 +18,11 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface FirewallRule extends ControlledEntity { +public interface FirewallRule extends ControlledEntity, Identity, InternalIdentity { enum Purpose { Firewall, PortForwarding, @@ -29,39 +31,34 @@ public interface FirewallRule extends ControlledEntity { StaticNat, NetworkACL, } - + enum FirewallRuleType { - System, // The pre-defined rules created by admin, in the system wide - User; // the rules created by user, to a specific ip + System, // The pre-defined rules created by admin, in the system wide + User // the rules created by user, to a specific ip } - + enum State { Staged, // Rule been created but has never got through network rule conflict detection. Rules in this state can not be sent to network elements. Add, // Add means the rule has been created and has gone through network rule conflict detection. Active, // Rule has been sent to the network elements and reported to be active. Revoke // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database. } - + enum TrafficType { Ingress, Egress } - - /** - * @return database id. - */ - long getId(); - + /** * @return external id. */ String getXid(); - + /** * @return first port of the source port range. */ Integer getSourcePortStart(); - + /** * @return last port of the source prot range. If this is null, that means only one port is mapped. */ @@ -71,21 +68,21 @@ public interface FirewallRule extends ControlledEntity { * @return protocol to open these ports for. */ String getProtocol(); - + Purpose getPurpose(); - + State getState(); - + long getNetworkId(); - + Long getSourceIpAddressId(); Integer getIcmpCode(); Integer getIcmpType(); - + List getSourceCidrList(); - + Long getRelated(); FirewallRuleType getType(); diff --git a/api/src/com/cloud/network/rules/LbStickinessMethod.java b/api/src/com/cloud/network/rules/LbStickinessMethod.java index 5f0abe8aaf6..c71b19e3a86 100644 --- a/api/src/com/cloud/network/rules/LbStickinessMethod.java +++ b/api/src/com/cloud/network/rules/LbStickinessMethod.java @@ -24,14 +24,14 @@ import com.google.gson.annotations.SerializedName; public class LbStickinessMethod { public static class StickinessMethodType { private String _name; - + public static final StickinessMethodType LBCookieBased = new StickinessMethodType("LbCookie"); public static final StickinessMethodType AppCookieBased = new StickinessMethodType("AppCookie"); public static final StickinessMethodType SourceBased = new StickinessMethodType("SourceBased"); public StickinessMethodType(String name) { _name = name; } - + public String getName() { return _name; } @@ -40,13 +40,13 @@ public class LbStickinessMethod { public class LbStickinessMethodParam { @SerializedName("paramname") private String _paramName; - + @SerializedName("required") private Boolean _required; - + @SerializedName("isflag") private Boolean _isFlag; - + @SerializedName("description") private String _description; @@ -65,7 +65,7 @@ public class LbStickinessMethod { public void setParamName(String paramName) { this._paramName = paramName; } - + public Boolean getIsflag() { return _isFlag; } @@ -73,7 +73,7 @@ public class LbStickinessMethod { public void setIsflag(Boolean isFlag) { this._isFlag = isFlag; } - + public Boolean getRequired() { return _required; } @@ -94,10 +94,10 @@ public class LbStickinessMethod { @SerializedName("methodname") private String _methodName; - + @SerializedName("paramlist") private List _paramList; - + @SerializedName("description") private String _description; @@ -118,7 +118,7 @@ public class LbStickinessMethod { public String getMethodName() { return _methodName; } - + public List getParamList() { return _paramList; } diff --git a/api/src/com/cloud/network/rules/LoadBalancer.java b/api/src/com/cloud/network/rules/LoadBalancer.java index 9734e7e3cb6..ab6085aceb7 100644 --- a/api/src/com/cloud/network/rules/LoadBalancer.java +++ b/api/src/com/cloud/network/rules/LoadBalancer.java @@ -31,5 +31,4 @@ public interface LoadBalancer extends FirewallRule { String getAlgorithm(); - String getUuid(); } diff --git a/api/src/com/cloud/network/rules/PortForwardingRule.java b/api/src/com/cloud/network/rules/PortForwardingRule.java index 6ac6f4521f9..c353e9bc3d4 100644 --- a/api/src/com/cloud/network/rules/PortForwardingRule.java +++ b/api/src/com/cloud/network/rules/PortForwardingRule.java @@ -26,26 +26,26 @@ public interface PortForwardingRule extends FirewallRule { * @return destination ip address. */ Ip getDestinationIpAddress(); - - + + /** * updates the destination ip address. */ void setDestinationIpAddress(Ip destinationIpAddress); - + /** * @return start of destination port. */ int getDestinationPortStart(); - + /** * @return end of destination port range */ int getDestinationPortEnd(); - + /** * @return destination ip address. */ - long getVirtualMachineId(); - + long getVirtualMachineId(); + } diff --git a/api/src/com/cloud/network/rules/RulesService.java b/api/src/com/cloud/network/rules/RulesService.java index 8eadfba7712..80c96d558c4 100644 --- a/api/src/com/cloud/network/rules/RulesService.java +++ b/api/src/com/cloud/network/rules/RulesService.java @@ -18,7 +18,7 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.api.commands.ListPortForwardingRulesCmd; +import org.apache.cloudstack.api.command.user.firewall.ListPortForwardingRulesCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; @@ -31,7 +31,7 @@ public interface RulesService { /** * Creates a port forwarding rule between two ip addresses or between * an ip address and a virtual machine. - * + * * @param rule * rule to be created. * @param vmId @@ -46,7 +46,7 @@ public interface RulesService { /** * Revokes a port forwarding rule - * + * * @param ruleId * the id of the rule to revoke. * @param caller @@ -56,7 +56,7 @@ public interface RulesService { /** * List port forwarding rules assigned to an ip address - * + * * @param cmd * the command object holding the criteria for listing port forwarding rules (the ipAddress) * @return list of port forwarding rules on the given address, empty list if no rules exist diff --git a/api/src/com/cloud/network/rules/StaticNat.java b/api/src/com/cloud/network/rules/StaticNat.java index bf29ab4bf9c..390a0dbaedc 100644 --- a/api/src/com/cloud/network/rules/StaticNat.java +++ b/api/src/com/cloud/network/rules/StaticNat.java @@ -18,13 +18,13 @@ package com.cloud.network.rules; public interface StaticNat{ - + long getAccountId(); - + long getDomainId(); - + long getNetworkId(); - + long getSourceIpAddressId(); String getDestIpAddress(); diff --git a/api/src/com/cloud/network/rules/StaticNatRule.java b/api/src/com/cloud/network/rules/StaticNatRule.java index 601cd6afb9e..839430a6b8c 100644 --- a/api/src/com/cloud/network/rules/StaticNatRule.java +++ b/api/src/com/cloud/network/rules/StaticNatRule.java @@ -16,31 +16,7 @@ // under the License. package com.cloud.network.rules; -import com.cloud.acl.ControlledEntity; - -public interface StaticNatRule extends ControlledEntity, FirewallRule { - - long getId(); - - String getXid(); - - String getProtocol(); - - Integer getSourcePortStart(); - - Integer getSourcePortEnd(); - - Purpose getPurpose(); - - State getState(); - - long getAccountId(); - - long getDomainId(); - - long getNetworkId(); - - Long getSourceIpAddressId(); +public interface StaticNatRule extends FirewallRule { String getDestIpAddress(); -} +} \ No newline at end of file diff --git a/api/src/com/cloud/network/rules/StickinessPolicy.java b/api/src/com/cloud/network/rules/StickinessPolicy.java index 49c2e60c493..e23ff828f74 100644 --- a/api/src/com/cloud/network/rules/StickinessPolicy.java +++ b/api/src/com/cloud/network/rules/StickinessPolicy.java @@ -19,12 +19,12 @@ package com.cloud.network.rules; import java.util.List; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** */ -public interface StickinessPolicy { - - public long getId(); +public interface StickinessPolicy extends InternalIdentity, Identity { public long getLoadBalancerId(); @@ -38,5 +38,4 @@ public interface StickinessPolicy { public List> getParams(); /* get params in Map format */ - public String getUuid(); } diff --git a/api/src/com/cloud/network/security/SecurityGroup.java b/api/src/com/cloud/network/security/SecurityGroup.java index 68467407f3d..3ac0e7cea62 100644 --- a/api/src/com/cloud/network/security/SecurityGroup.java +++ b/api/src/com/cloud/network/security/SecurityGroup.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.network.security; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityGroup extends ControlledEntity { - long getId(); +//FIXME: Annotation @doc("") +public interface SecurityGroup extends ControlledEntity, InternalIdentity, Identity { String getName(); diff --git a/api/src/com/cloud/network/security/SecurityGroupRules.java b/api/src/com/cloud/network/security/SecurityGroupRules.java index 37287f0c76b..0b575e10d56 100644 --- a/api/src/com/cloud/network/security/SecurityGroupRules.java +++ b/api/src/com/cloud/network/security/SecurityGroupRules.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.network.security; import com.cloud.network.security.SecurityRule.SecurityRuleType; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityGroupRules { - long getId(); +public interface SecurityGroupRules extends InternalIdentity { String getName(); @@ -39,6 +39,6 @@ public interface SecurityGroupRules { Long getAllowedNetworkId(); String getAllowedSourceIpCidr(); - + SecurityRuleType getRuleType(); } diff --git a/api/src/com/cloud/network/security/SecurityGroupService.java b/api/src/com/cloud/network/security/SecurityGroupService.java index 4a4b1712aba..741f179db50 100644 --- a/api/src/com/cloud/network/security/SecurityGroupService.java +++ b/api/src/com/cloud/network/security/SecurityGroupService.java @@ -18,13 +18,8 @@ package com.cloud.network.security; import java.util.List; -import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd; -import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; -import com.cloud.api.commands.CreateSecurityGroupCmd; -import com.cloud.api.commands.DeleteSecurityGroupCmd; -import com.cloud.api.commands.ListSecurityGroupsCmd; -import com.cloud.api.commands.RevokeSecurityGroupEgressCmd; -import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; +import org.apache.cloudstack.api.command.user.securitygroup.*; + import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceInUseException; @@ -38,18 +33,12 @@ public interface SecurityGroupService { public SecurityGroup createSecurityGroup(CreateSecurityGroupCmd command) throws PermissionDeniedException, InvalidParameterValueException; boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd); boolean revokeSecurityGroupEgress(RevokeSecurityGroupEgressCmd cmd); - + boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException; - /** - * Search for security groups and associated ingress rules for the given account, domain, group name, and/or keyword. - * The search terms are specified in the search criteria. - * @return the list of security groups and associated ingress rules - */ - public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException; public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd); - + public List authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd); } diff --git a/api/src/com/cloud/network/security/SecurityRule.java b/api/src/com/cloud/network/security/SecurityRule.java index 401283aba4b..bd4192d614c 100644 --- a/api/src/com/cloud/network/security/SecurityRule.java +++ b/api/src/com/cloud/network/security/SecurityRule.java @@ -17,34 +17,35 @@ package com.cloud.network.security; import com.cloud.async.AsyncInstanceCreateStatus; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityRule { +public interface SecurityRule extends Identity, InternalIdentity { public static class SecurityRuleType { public static final SecurityRuleType IngressRule = new SecurityRuleType("ingress"); public static final SecurityRuleType EgressRule = new SecurityRuleType("egress"); - + public SecurityRuleType(String type) { this._type = type; } - + public String getType(){ return _type; } private String _type; } - long getId(); long getSecurityGroupId(); int getStartPort(); int getEndPort(); - + String getType(); - + SecurityRuleType getRuleType(); - + String getProtocol(); AsyncInstanceCreateStatus getCreateStatus(); @@ -52,7 +53,4 @@ public interface SecurityRule { Long getAllowedNetworkId(); String getAllowedSourceIpCidr(); - - String getUuid(); - } diff --git a/api/src/com/cloud/network/vpc/PrivateGateway.java b/api/src/com/cloud/network/vpc/PrivateGateway.java index 82672a6ef12..2f346852e30 100644 --- a/api/src/com/cloud/network/vpc/PrivateGateway.java +++ b/api/src/com/cloud/network/vpc/PrivateGateway.java @@ -16,6 +16,6 @@ // under the License. package com.cloud.network.vpc; -public interface PrivateGateway extends VpcGateway{ +public interface PrivateGateway extends VpcGateway { long getPhysicalNetworkId(); } diff --git a/api/src/com/cloud/network/vpc/PrivateIp.java b/api/src/com/cloud/network/vpc/PrivateIp.java index 992a87ca475..857fc226f30 100644 --- a/api/src/com/cloud/network/vpc/PrivateIp.java +++ b/api/src/com/cloud/network/vpc/PrivateIp.java @@ -42,7 +42,7 @@ public interface PrivateIp { * @return */ String getMacAddress(); - + long getNetworkId(); } diff --git a/api/src/com/cloud/network/vpc/StaticRoute.java b/api/src/com/cloud/network/vpc/StaticRoute.java index 56b34cbaa86..ccdbec899b8 100644 --- a/api/src/com/cloud/network/vpc/StaticRoute.java +++ b/api/src/com/cloud/network/vpc/StaticRoute.java @@ -16,9 +16,11 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface StaticRoute extends ControlledEntity{ +public interface StaticRoute extends ControlledEntity, Identity, InternalIdentity { enum State { Staged, // route been created but has never got through network rule conflict detection. Routes in this state can not be sent to VPC virtual router. Add, // Add means the route has been created and has gone through network rule conflict detection. @@ -45,11 +47,4 @@ public interface StaticRoute extends ControlledEntity{ * @return */ Long getVpcId(); - - /** - * @return - */ - long getId(); - - } diff --git a/api/src/com/cloud/network/vpc/StaticRouteProfile.java b/api/src/com/cloud/network/vpc/StaticRouteProfile.java index 73d0a84f8b7..656355590f3 100644 --- a/api/src/com/cloud/network/vpc/StaticRouteProfile.java +++ b/api/src/com/cloud/network/vpc/StaticRouteProfile.java @@ -16,8 +16,11 @@ // under the License. package com.cloud.network.vpc; -public class StaticRouteProfile implements StaticRoute{ +import org.apache.cloudstack.api.InternalIdentity; + +public class StaticRouteProfile implements StaticRoute { private long id; + private String uuid; private String targetCidr; private long accountId; private long domainId; @@ -28,10 +31,11 @@ public class StaticRouteProfile implements StaticRoute{ String gateway; String netmask; String ipAddress; - + public StaticRouteProfile(StaticRoute staticRoute, VpcGateway gateway) { this.id = staticRoute.getId(); + this.uuid = staticRoute.getUuid(); this.targetCidr = staticRoute.getCidr(); this.accountId = staticRoute.getAccountId(); this.domainId = staticRoute.getDomainId(); @@ -79,10 +83,16 @@ public class StaticRouteProfile implements StaticRoute{ return id; } + + @Override + public String getUuid() { + return uuid; + } + public String getVlanTag() { return vlanTag; } - + public String getIp4Address() { return ipAddress; } @@ -94,5 +104,5 @@ public class StaticRouteProfile implements StaticRoute{ public String getNetmask() { return netmask; } - + } diff --git a/api/src/com/cloud/network/vpc/Vpc.java b/api/src/com/cloud/network/vpc/Vpc.java index c9f52ff999f..9365e56dd82 100644 --- a/api/src/com/cloud/network/vpc/Vpc.java +++ b/api/src/com/cloud/network/vpc/Vpc.java @@ -16,23 +16,21 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Vpc extends ControlledEntity{ +public interface Vpc extends ControlledEntity, Identity, InternalIdentity { public enum State { Enabled, Inactive } - + public static final String _supportedProviders = Network.Provider.VPCVirtualRouter.getName(); boolean readyToUse(); - long getId(); - - String getUuid(); - String getName(); long getZoneId(); @@ -42,11 +40,11 @@ public interface Vpc extends ControlledEntity{ State getState(); long getVpcOfferingId(); - + String getDisplayText(); String getNetworkDomain(); boolean isRestartRequired(); - + } diff --git a/api/src/com/cloud/network/vpc/VpcGateway.java b/api/src/com/cloud/network/vpc/VpcGateway.java index c972c35c3fb..17566160ec3 100644 --- a/api/src/com/cloud/network/vpc/VpcGateway.java +++ b/api/src/com/cloud/network/vpc/VpcGateway.java @@ -16,23 +16,22 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VpcGateway extends Identity, ControlledEntity { +public interface VpcGateway extends Identity, ControlledEntity, InternalIdentity { public enum Type { Private, Public, Vpn } - + public enum State { Creating, Ready, Deleting } - - long getId(); /** * @return diff --git a/api/src/com/cloud/network/vpc/VpcOffering.java b/api/src/com/cloud/network/vpc/VpcOffering.java index 10c1d2aca96..1acfcd21418 100644 --- a/api/src/com/cloud/network/vpc/VpcOffering.java +++ b/api/src/com/cloud/network/vpc/VpcOffering.java @@ -16,18 +16,17 @@ // under the License. package com.cloud.network.vpc; -public interface VpcOffering { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface VpcOffering extends InternalIdentity, Identity { public enum State { Disabled, Enabled } - + public static final String defaultVPCOfferingName = "Default VPC offering"; - long getId(); - - String getUuid(); - String getName(); String getUniqueName(); @@ -35,7 +34,7 @@ public interface VpcOffering { String getDisplayText(); State getState(); - + boolean isDefault(); /** diff --git a/api/src/com/cloud/network/vpc/VpcService.java b/api/src/com/cloud/network/vpc/VpcService.java index c13e37f1b55..68e062c7d79 100644 --- a/api/src/com/cloud/network/vpc/VpcService.java +++ b/api/src/com/cloud/network/vpc/VpcService.java @@ -20,8 +20,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -37,20 +37,20 @@ import com.cloud.user.User; import com.cloud.utils.Pair; public interface VpcService { - + public VpcOffering getVpcOffering(long vpcOfferingId); - + public VpcOffering createVpcOffering(String name, String displayText, List supportedServices); - + public Vpc getVpc(long vpcId); - + public Vpc getActiveVpc(long vpcId); - + public List getVpcNetworks(long vpcId); - + Map> getVpcOffSvcProvidersMap(long vpcOffId); - - List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, + + List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, Boolean isDefault, String keyword, String state, Long startIndex, Long pageSizeVal); /** @@ -85,9 +85,9 @@ public interface VpcService { /** * @param vpcId * @return - * @throws InsufficientCapacityException - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws InsufficientCapacityException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ public boolean deleteVpc(long vpcId) throws ConcurrentOperationException, ResourceUnavailableException; @@ -120,22 +120,22 @@ public interface VpcService { * @param vpc * @return */ - public List listVpcs(Long id, String vpcName, String displayText, + public List listVpcs(Long id, String vpcName, String displayText, List supportedServicesStr, String cidr, Long vpcOffId, String state, String accountName, Long domainId, - String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, + String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired, Map tags, Long projectId); /** * @param vpcId * @param destroyOnFailure TODO * @return - * @throws InsufficientCapacityException - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws InsufficientCapacityException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ - boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException, + boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + /** * @param vpcId * @return @@ -147,10 +147,10 @@ public interface VpcService { /** * @param id * @return - * @throws InsufficientCapacityException + * @throws InsufficientCapacityException */ boolean restartVpc(long id) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + PrivateGateway getVpcPrivateGateway(long id); /** @@ -162,28 +162,28 @@ public interface VpcService { * @param netmask * @param gatewayOwnerId * @return - * @throws InsufficientCapacityException - * @throws ConcurrentOperationException - * @throws ResourceAllocationException + * @throws InsufficientCapacityException + * @throws ConcurrentOperationException + * @throws ResourceAllocationException */ - public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, - String gateway, String netmask, long gatewayOwnerId) throws ResourceAllocationException, + public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, + String gateway, String netmask, long gatewayOwnerId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; /** * @param gatewayId * @param destroyOnFailure TODO * @return - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ public PrivateGateway applyVpcPrivateGateway(long gatewayId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException; - + /** * @param id * @return - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ boolean deleteVpcPrivateGateway(long gatewayId) throws ConcurrentOperationException, ResourceUnavailableException; @@ -202,14 +202,14 @@ public interface VpcService { /** * @param vpcId * @return - * @throws ResourceUnavailableException + * @throws ResourceUnavailableException */ public boolean applyStaticRoutes(long vpcId) throws ResourceUnavailableException; /** * @param routeId * @return TODO - * @throws ResourceUnavailableException + * @throws ResourceUnavailableException */ public boolean revokeStaticRoute(long routeId) throws ResourceUnavailableException; @@ -231,7 +231,7 @@ public interface VpcService { * @return */ VpcGateway getVpcGateway(long id); - + /** * @param ipId * @param vpcId @@ -243,7 +243,7 @@ public interface VpcService { */ IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException; - - public Network updateVpcGuestNetwork(long networkId, String name, String displayText, Account callerAccount, + + public Network updateVpcGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long ntwkOffId, Boolean changeCidr); } diff --git a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java index 4d820a7a258..81599a0c3c9 100644 --- a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java +++ b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java @@ -18,8 +18,8 @@ package com.cloud.network.vpn; import java.util.List; -import com.cloud.api.commands.ListRemoteAccessVpnsCmd; -import com.cloud.api.commands.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.RemoteAccessVpn; @@ -29,7 +29,7 @@ import com.cloud.utils.Pair; public interface RemoteAccessVpnService { - RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId) + RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId) throws NetworkRuleConflictException; void destroyRemoteAccessVpn(long vpnServerAddressId, Account caller) throws ResourceUnavailableException; RemoteAccessVpn startRemoteAccessVpn(long vpnServerAddressId, boolean openFirewall) throws ResourceUnavailableException; @@ -38,12 +38,12 @@ public interface RemoteAccessVpnService { boolean removeVpnUser(long vpnOwnerId, String userName, Account caller); List listVpnUsers(long vpnOwnerId, String userName); boolean applyVpnUsers(long vpnOwnerId, String userName); - + Pair, Integer> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd); Pair, Integer> searchForVpnUsers(ListVpnUsersCmd cmd); - + List listRemoteAccessVpns(long networkId); - + RemoteAccessVpn getRemoteAccessVpn(long vpnId); } diff --git a/api/src/com/cloud/network/vpn/Site2SiteVpnService.java b/api/src/com/cloud/network/vpn/Site2SiteVpnService.java index 69eab1a13f6..7ac567774d8 100644 --- a/api/src/com/cloud/network/vpn/Site2SiteVpnService.java +++ b/api/src/com/cloud/network/vpn/Site2SiteVpnService.java @@ -18,17 +18,17 @@ package com.cloud.network.vpn; import java.util.List; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.*; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ResetVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteCustomerGateway; diff --git a/api/src/com/cloud/offering/DiskOffering.java b/api/src/com/cloud/offering/DiskOffering.java index a937c6d789d..9a48f4bb655 100644 --- a/api/src/com/cloud/offering/DiskOffering.java +++ b/api/src/com/cloud/offering/DiskOffering.java @@ -16,15 +16,18 @@ // under the License. package com.cloud.offering; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; /** * Represents a disk offering that specifies what the end user needs in * the disk offering. - * + * */ -public interface DiskOffering { - long getId(); +public interface DiskOffering extends InfrastructureEntity, Identity, InternalIdentity { String getUniqueName(); diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index 29828ab6172..f2c4de520a1 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -18,12 +18,15 @@ package com.cloud.offering; import com.cloud.network.Network.GuestType; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Describes network offering - * + * */ -public interface NetworkOffering { +public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, Identity { public enum Availability { Required, @@ -40,7 +43,7 @@ public interface NetworkOffering { public final static String SystemManagementNetwork = "System-Management-Network"; public final static String SystemStorageNetwork = "System-Storage-Network"; public final static String SystemPrivateGatewayNetworkOffering = "System-Private-Gateway-Network-Offering"; - + public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService"; public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService"; public final static String OvsIsolatedNetworkOfferingWithSourceNatService = "OvsIsolatedNetworkOfferingWithSourceNatService"; @@ -50,9 +53,6 @@ public interface NetworkOffering { public final static String DefaultIsolatedNetworkOfferingForVpcNetworks = "DefaultIsolatedNetworkOfferingForVpcNetworks"; public final static String DefaultIsolatedNetworkOfferingForVpcNetworksNoLB = "DefaultIsolatedNetworkOfferingForVpcNetworksNoLB"; - - long getId(); - /** * @return name for the network offering. */ @@ -105,10 +105,9 @@ public interface NetworkOffering { boolean getElasticIp(); - boolean getAssociatePublicIP(); - boolean getElasticLb(); boolean getSpecifyIpRanges(); + boolean isInline(); } diff --git a/api/src/com/cloud/offering/OfferingManager.java b/api/src/com/cloud/offering/OfferingManager.java index 3cc68dbcc6f..576679d04c9 100644 --- a/api/src/com/cloud/offering/OfferingManager.java +++ b/api/src/com/cloud/offering/OfferingManager.java @@ -18,30 +18,30 @@ package com.cloud.offering; /** * An administrator can create, delete, enable, and disable offerings. - * + * * There are three types of offerings: * - Disk Offering - package of disk performance and size specification. * - Network Offering - package of services available on a network. - * + * */ public interface OfferingManager { /** * Creates a service offering. - * + * * @return ServiceOffering */ ServiceOffering createServiceOffering(); /** * Creates a disk offering. - * + * * @return DiskOffering */ DiskOffering createDiskOffering(); /** * Creates a network offering. - * + * * @return NetworkOffering */ NetworkOffering createNetworkOffering(); diff --git a/api/src/com/cloud/offering/ServiceOffering.java b/api/src/com/cloud/offering/ServiceOffering.java index 1a1acb2ea5a..b13346cfb83 100755 --- a/api/src/com/cloud/offering/ServiceOffering.java +++ b/api/src/com/cloud/offering/ServiceOffering.java @@ -16,12 +16,16 @@ // under the License. package com.cloud.offering; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; /** * offered. */ -public interface ServiceOffering { +public interface ServiceOffering extends InfrastructureEntity, InternalIdentity, Identity { public static final String consoleProxyDefaultOffUniqueName = "Cloud.com-ConsoleProxy"; public static final String ssvmDefaultOffUniqueName = "Cloud.com-SecondaryStorage"; public static final String routerDefaultOffUniqueName = "Cloud.Com-SoftwareRouter"; @@ -32,8 +36,6 @@ public interface ServiceOffering { shared } - long getId(); - String getDisplayText(); Date getCreated(); diff --git a/api/src/com/cloud/org/Cluster.java b/api/src/com/cloud/org/Cluster.java index 7fe64af59a5..cb72a70b817 100644 --- a/api/src/com/cloud/org/Cluster.java +++ b/api/src/com/cloud/org/Cluster.java @@ -18,15 +18,15 @@ package com.cloud.org; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Managed.ManagedState; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Cluster extends Grouping { +public interface Cluster extends Grouping, InternalIdentity, Identity { public static enum ClusterType { CloudManaged, ExternalManaged; }; - long getId(); - String getName(); long getDataCenterId(); diff --git a/api/src/com/cloud/projects/Project.java b/api/src/com/cloud/projects/Project.java index f67506e4997..78d52574f28 100644 --- a/api/src/com/cloud/projects/Project.java +++ b/api/src/com/cloud/projects/Project.java @@ -18,10 +18,11 @@ package com.cloud.projects; import java.util.Date; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.domain.PartOf; +import org.apache.cloudstack.api.InternalIdentity; -public interface Project extends PartOf, Identity { +public interface Project extends PartOf, Identity, InternalIdentity { public enum State { Active, Disabled, Suspended } diff --git a/api/src/com/cloud/projects/ProjectInvitation.java b/api/src/com/cloud/projects/ProjectInvitation.java index 6dca006645b..ee282229034 100644 --- a/api/src/com/cloud/projects/ProjectInvitation.java +++ b/api/src/com/cloud/projects/ProjectInvitation.java @@ -18,15 +18,15 @@ package com.cloud.projects; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface ProjectInvitation extends ControlledEntity { +public interface ProjectInvitation extends ControlledEntity, Identity, InternalIdentity { public enum State { Pending, Completed, Expired, Declined } - long getId(); - long getProjectId(); Long getForAccountId(); diff --git a/api/src/com/cloud/projects/ProjectService.java b/api/src/com/cloud/projects/ProjectService.java index ea143b7e868..01975188dd9 100644 --- a/api/src/com/cloud/projects/ProjectService.java +++ b/api/src/com/cloud/projects/ProjectService.java @@ -16,20 +16,16 @@ // under the License. package com.cloud.projects; -import java.util.List; -import java.util.Map; - import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.ProjectAccount.Role; import com.cloud.user.Account; -import com.cloud.utils.Pair; public interface ProjectService { /** * Creates a new project - * + * * @param name * - project name * @param displayText @@ -45,7 +41,7 @@ public interface ProjectService { /** * Deletes a project - * + * * @param id * - project id * @return true if the project was deleted successfully, false otherwise @@ -54,16 +50,13 @@ public interface ProjectService { /** * Gets a project by id - * + * * @param id * - project id * @return project object */ Project getProject(long id); - Pair, Integer> listProjects(Long id, String name, String displayText, String state, String accountName, - Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, boolean isRecursive, Map tags); - ProjectAccount assignAccountToProject(Project project, long accountId, Role accountRole); Account getProjectOwner(long projectId); @@ -80,10 +73,7 @@ public interface ProjectService { boolean deleteAccountFromProject(long projectId, String accountName); - Pair, Integer> listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal); - Pair, Integer> listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, - boolean listAll); boolean updateInvitation(long projectId, String accountName, String token, boolean accept); @@ -94,6 +84,6 @@ public interface ProjectService { Project enableProject(long projectId); boolean deleteProjectInvitation(long invitationId); - + Project findByProjectAccountIdIncludingRemoved(long projectAccountId); } diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index 4cdb31a72ab..b9db8e734d9 100755 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -18,19 +18,14 @@ package com.cloud.resource; import java.util.List; -import com.cloud.api.commands.AddClusterCmd; -import com.cloud.api.commands.AddHostCmd; -import com.cloud.api.commands.AddS3Cmd; -import com.cloud.api.commands.AddSecondaryStorageCmd; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.CancelMaintenanceCmd; -import com.cloud.api.commands.DeleteClusterCmd; -import com.cloud.api.commands.ListS3sCmd; -import com.cloud.api.commands.ListSwiftsCmd; -import com.cloud.api.commands.PrepareForMaintenanceCmd; -import com.cloud.api.commands.ReconnectHostCmd; -import com.cloud.api.commands.UpdateHostCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; +import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd; +import org.apache.cloudstack.api.command.admin.host.*; +import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceInUseException; @@ -40,15 +35,16 @@ import com.cloud.org.Cluster; import com.cloud.storage.S3; import com.cloud.storage.Swift; import com.cloud.utils.fsm.NoTransitionException; +import org.apache.cloudstack.api.command.admin.host.ReconnectHostCmd; public interface ResourceService { /** * Updates a host - * + * * @param cmd * - the command specifying hostId * @return hostObject - * @throws NoTransitionException + * @throws NoTransitionException */ Host updateHost(UpdateHostCmd cmd) throws NoTransitionException; @@ -59,7 +55,7 @@ public interface ResourceService { /** * We will automatically create a cloud.com cluster to attach to the external cluster and return a hyper host to perform * host related operation within the cluster - * + * * @param cmd * @return * @throws IllegalArgumentException @@ -79,12 +75,12 @@ public interface ResourceService { /** * Deletes a host - * + * * @param hostId * TODO * @param isForced * TODO - * + * * @param true if deleted, false otherwise */ boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage); diff --git a/api/src/com/cloud/serializer/Param.java b/api/src/com/cloud/serializer/Param.java index 005188216c6..02deb6f1c1f 100644 --- a/api/src/com/cloud/serializer/Param.java +++ b/api/src/com/cloud/serializer/Param.java @@ -31,6 +31,6 @@ public @interface Param { Class responseObject() default Object.class; boolean includeInApiDoc() default true; - + String since() default ""; } diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 7532cae2a64..fb8af1a5b4b 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -23,53 +23,47 @@ import java.util.Map; import java.util.Set; import com.cloud.alert.Alert; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.CreateSSHKeyPairCmd; -import com.cloud.api.commands.DeleteSSHKeyPairCmd; -import com.cloud.api.commands.DestroySystemVmCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.commands.GetVMPasswordCmd; -import com.cloud.api.commands.ListAlertsCmd; -import com.cloud.api.commands.ListAsyncJobsCmd; -import com.cloud.api.commands.ListCapabilitiesCmd; -import com.cloud.api.commands.ListCapacityCmd; -import com.cloud.api.commands.ListCfgsByCmd; -import com.cloud.api.commands.ListClustersCmd; -import com.cloud.api.commands.ListDiskOfferingsCmd; -import com.cloud.api.commands.ListEventsCmd; -import com.cloud.api.commands.ListGuestOsCategoriesCmd; -import com.cloud.api.commands.ListGuestOsCmd; -import com.cloud.api.commands.ListHostsCmd; -import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListPodsByCmd; -import com.cloud.api.commands.ListPublicIpAddressesCmd; -import com.cloud.api.commands.ListRoutersCmd; -import com.cloud.api.commands.ListSSHKeyPairsCmd; -import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListStoragePoolsCmd; -import com.cloud.api.commands.ListSystemVMsCmd; -import com.cloud.api.commands.ListTemplatesCmd; -import com.cloud.api.commands.ListVMGroupsCmd; -import com.cloud.api.commands.ListVlanIpRangesCmd; -import com.cloud.api.commands.ListZonesByCmd; -import com.cloud.api.commands.RebootSystemVmCmd; -import com.cloud.api.commands.RegisterSSHKeyPairCmd; -import com.cloud.api.commands.StopSystemVmCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; -import com.cloud.api.commands.UpdateIsoCmd; -import com.cloud.api.commands.UpdateTemplateCmd; -import com.cloud.api.commands.UpdateVMGroupCmd; -import com.cloud.api.commands.UpgradeSystemVMCmd; -import com.cloud.api.commands.UploadCustomCertificateCmd; -import com.cloud.async.AsyncJob; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; +import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; +import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.*; +import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; +import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; +import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; +import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; +import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; +import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; +import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; +import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; +import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; +import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; +import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; + import com.cloud.capacity.Capacity; import com.cloud.configuration.Configuration; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; import com.cloud.dc.Vlan; import com.cloud.domain.Domain; -import com.cloud.event.Event; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InternalErrorException; import com.cloud.exception.PermissionDeniedException; @@ -78,7 +72,6 @@ import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.network.IpAddress; -import com.cloud.network.router.VirtualRouter; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.org.Cluster; @@ -94,7 +87,7 @@ import com.cloud.vm.VirtualMachine.Type; /** * Hopefully this is temporary. - * + * */ public interface ManagementService { static final String Name = "management-server"; @@ -104,21 +97,21 @@ public interface ManagementService { * for the * account that invokes the API. By specifying available=true all zones which the account can access. By specifying * available=false the zones where the account has virtual machine instances will be returned. - * + * * @return a list of DataCenters */ List listDataCenters(ListZonesByCmd cmd); /** * returns the a map of the names/values in the configuraton table - * + * * @return map of configuration name/values */ Pair, Integer> searchForConfigurations(ListCfgsByCmd c); /** * Searches for Service Offerings by the specified search criteria Can search by: "name" - * + * * @param cmd * @return List of ServiceOfferings */ @@ -126,12 +119,12 @@ public interface ManagementService { /** * Searches for Clusters by the specified search criteria - * + * * @param c * @return */ Pair, Integer> searchForClusters(ListClustersCmd c); - + /** * Searches for Clusters by the specified zone Id. * @param zoneId @@ -141,24 +134,16 @@ public interface ManagementService { /** * Searches for Pods by the specified search criteria Can search by: pod name and/or zone name - * + * * @param cmd * @return List of Pods */ Pair, Integer> searchForPods(ListPodsByCmd cmd); - /** - * Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", - * "podId" - * - * @param cmd - * @return List of Hosts - */ - List searchForServers(ListHostsCmd cmd); /** * Creates a new template - * + * * @param cmd * @return updated template */ @@ -166,30 +151,12 @@ public interface ManagementService { VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd); - /** - * Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level", - * "startDate", - * "endDate" - * - * @param c - * @return List of Events. - */ - List searchForEvents(ListEventsCmd c); - /** - * Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state", - * "dataCenterId", - * "podId", "hostId" - * - * @param cmd - * @return List of DomainRouters. - */ - Pair, Integer> searchForRouters(ListRoutersCmd cmd); /** * Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId", * "address" - * + * * @param cmd * the command that wraps the search criteria * @return List of IPAddresses @@ -198,14 +165,14 @@ public interface ManagementService { /** * Obtains a list of all guest OS. - * + * * @return list of GuestOS */ Pair, Integer> listGuestOSByCriteria(ListGuestOsCmd cmd); /** * Obtains a list of all guest OS categories. - * + * * @return list of GuestOSCategories */ Pair, Integer> listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd); @@ -217,12 +184,12 @@ public interface ManagementService { VirtualMachine rebootSystemVM(RebootSystemVmCmd cmd); VirtualMachine destroySystemVM(DestroySystemVmCmd cmd); - + VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd); /** * update an existing domain - * + * * @param cmd * - the command containing domainId and new domainName * @return Domain object if the command succeeded @@ -231,7 +198,7 @@ public interface ManagementService { /** * Searches for alerts - * + * * @param c * @return List of Alerts */ @@ -239,7 +206,7 @@ public interface ManagementService { /** * list all the capacity rows in capacity operations table - * + * * @param cmd * @return List of capacities */ @@ -247,7 +214,7 @@ public interface ManagementService { /** * List ISOs that match the specified criteria. - * + * * @param cmd * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, * and zoneId @@ -258,7 +225,7 @@ public interface ManagementService { /** * List templates that match the specified criteria. - * + * * @param cmd * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, * and zoneId @@ -269,25 +236,17 @@ public interface ManagementService { /** * Search for disk offerings based on search criteria - * + * * @param cmd * the command containing the criteria to use for searching for disk offerings * @return a list of disk offerings that match the given criteria */ List searchForDiskOfferings(ListDiskOfferingsCmd cmd); - /** - * List storage pools that match the given criteria - * - * @param cmd - * the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id) - * @return a list of storage pools that match the given criteria - */ - Pair, Integer> searchForStoragePools(ListStoragePoolsCmd cmd); /** * List system VMs by the given search criteria - * + * * @param cmd * the command that wraps the search criteria (host, name, state, type, zone, pod, and/or id) * @return the list of system vms that match the given criteria @@ -296,7 +255,7 @@ public interface ManagementService { /** * Returns back a SHA1 signed response - * + * * @param userId * -- id for the user * @return -- ArrayList of @@ -307,13 +266,12 @@ public interface ManagementService { InstanceGroup updateVmGroup(UpdateVMGroupCmd cmd); - Pair, Integer> searchForVmGroups(ListVMGroupsCmd cmd); Map listCapabilities(ListCapabilitiesCmd cmd); /** * Extracts the volume to a particular location. - * + * * @param cmd * the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume * exists), @@ -321,23 +279,23 @@ public interface ManagementService { * @throws URISyntaxException * @throws InternalErrorException * @throws PermissionDeniedException - * + * */ Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException; /** * return an array of available hypervisors - * + * * @param zoneId * TODO - * + * * @return an array of available hypervisors in the cloud */ List getHypervisors(Long zoneId); /** * This method uploads a custom cert to the db, and patches every cpvm with it on the current ms - * + * * @param cmd * -- upload certificate cmd * @return -- returns a string on success @@ -350,24 +308,15 @@ public interface ManagementService { /** * Searches for vlan by the specified search criteria Can search by: "id", "vlan", "name", "zoneID" - * + * * @param cmd * @return List of Vlans */ Pair, Integer> searchForVlans(ListVlanIpRangesCmd cmd); - /** - * Search for async jobs by account and/or startDate - * - * @param cmd - * the command specifying the account and start date parameters - * @return the list of async jobs that match the criteria - */ - Pair, Integer> searchForAsyncJobs(ListAsyncJobsCmd cmd); - /** * Generates a random password that will be used (initially) by newly created and started virtual machines - * + * * @return a random password */ String generateRandomPassword(); @@ -378,7 +327,7 @@ public interface ManagementService { /** * Search registered key pairs for the logged in user. - * + * * @param cmd * The api command class. * @return The list of key pairs found. @@ -387,7 +336,7 @@ public interface ManagementService { /** * Registers a key pair for a given public key. - * + * * @param cmd * The api command class. * @return A VO with the key pair name and a finger print for the public key. @@ -396,7 +345,7 @@ public interface ManagementService { /** * Creates a new - * + * * @param cmd * The api command class. * @return A VO containing the key pair name, finger print for the public key and the private key material of the @@ -406,7 +355,7 @@ public interface ManagementService { /** * Deletes a key pair by name. - * + * * @param cmd * The api command class. * @return True on success. False otherwise. @@ -415,7 +364,7 @@ public interface ManagementService { /** * Finds and returns an encrypted password for a VM. - * + * * @param cmd * The api command class. * @return The encrypted password. @@ -428,7 +377,7 @@ public interface ManagementService { * List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current * host and * also a list of hosts that seem to have enough CPU and RAM capacity to host this VM. - * + * * @param Long * vmId * Id of The VM to migrate @@ -445,7 +394,7 @@ public interface ManagementService { /** * list all the top consumed resources across different capacity types - * + * * @param cmd * @return List of capacities */ diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index 117e721b893..5ec9f0171cc 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.server; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface ResourceTag extends ControlledEntity, Identity, InternalIdentity { -public interface ResourceTag extends ControlledEntity{ - public enum TaggedResourceType { UserVm, Template, @@ -38,11 +40,6 @@ public interface ResourceTag extends ControlledEntity{ StaticRoute } - /** - * @return - */ - long getId(); - /** * @return */ diff --git a/api/src/com/cloud/server/TaggedResourceService.java b/api/src/com/cloud/server/TaggedResourceService.java index dce799e5ca2..92a4300db0a 100644 --- a/api/src/com/cloud/server/TaggedResourceService.java +++ b/api/src/com/cloud/server/TaggedResourceService.java @@ -19,12 +19,10 @@ package com.cloud.server; import java.util.List; import java.util.Map; -import com.cloud.api.commands.ListTagsCmd; import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.utils.Pair; public interface TaggedResourceService { - + TaggedResourceType getResourceType (String resourceTypeStr); /** @@ -43,11 +41,6 @@ public interface TaggedResourceService { */ String getUuid(String resourceId, TaggedResourceType resourceType); - /** - * @param listTagsCmd - * @return - */ - Pair, Integer> listTags(ListTagsCmd listTagsCmd); /** * @param resourceIds @@ -56,6 +49,6 @@ public interface TaggedResourceService { * @return */ boolean deleteTags(List resourceIds, TaggedResourceType resourceType, Map tags); - + List listByResourceTypeAndId(TaggedResourceType type, long resourceId); } diff --git a/api/src/com/cloud/storage/GuestOS.java b/api/src/com/cloud/storage/GuestOS.java index b9727db6612..437cd37d1ab 100644 --- a/api/src/com/cloud/storage/GuestOS.java +++ b/api/src/com/cloud/storage/GuestOS.java @@ -16,9 +16,10 @@ // under the License. package com.cloud.storage; -public interface GuestOS { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; - long getId(); +public interface GuestOS extends InternalIdentity, Identity { String getName(); diff --git a/api/src/com/cloud/storage/GuestOsCategory.java b/api/src/com/cloud/storage/GuestOsCategory.java index 42320d9eec8..c28d7d6bf77 100644 --- a/api/src/com/cloud/storage/GuestOsCategory.java +++ b/api/src/com/cloud/storage/GuestOsCategory.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.storage; -public interface GuestOsCategory { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface GuestOsCategory extends Identity, InternalIdentity { // Used by OS preference, 'None' for no OS preference public static final String CATEGORY_NONE ="None"; - long getId(); String getName(); diff --git a/api/src/com/cloud/storage/S3.java b/api/src/com/cloud/storage/S3.java index 7a679f2adc5..708e280ca5b 100644 --- a/api/src/com/cloud/storage/S3.java +++ b/api/src/com/cloud/storage/S3.java @@ -19,14 +19,12 @@ package com.cloud.storage; import com.cloud.agent.api.to.S3TO; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; import java.util.Date; -public interface S3 { - - long getId(); - - String getUuid(); +public interface S3 extends InternalIdentity, Identity { String getAccessKey(); diff --git a/api/src/com/cloud/storage/Snapshot.java b/api/src/com/cloud/storage/Snapshot.java index a37cc94241f..99bdee6bea9 100644 --- a/api/src/com/cloud/storage/Snapshot.java +++ b/api/src/com/cloud/storage/Snapshot.java @@ -18,10 +18,12 @@ package com.cloud.storage; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Snapshot extends ControlledEntity { +public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { public enum Type { MANUAL, RECURRING, @@ -67,8 +69,6 @@ public interface Snapshot extends ControlledEntity { public static final long MANUAL_POLICY_ID = 0L; - Long getId(); - long getAccountId(); long getVolumeId(); diff --git a/api/src/com/cloud/storage/StoragePool.java b/api/src/com/cloud/storage/StoragePool.java index 497523d7e38..3334da54ec0 100644 --- a/api/src/com/cloud/storage/StoragePool.java +++ b/api/src/com/cloud/storage/StoragePool.java @@ -19,25 +19,16 @@ package com.cloud.storage; import java.util.Date; import com.cloud.storage.Storage.StoragePoolType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface StoragePool { - - /** - * @return id of the pool. - */ - long getId(); +public interface StoragePool extends Identity, InternalIdentity { /** * @return name of the pool. */ String getName(); - /*** - * - * @return unique identifier - */ - String getUuid(); - /** * @return the type of pool. */ diff --git a/api/src/com/cloud/storage/StorageService.java b/api/src/com/cloud/storage/StorageService.java index 587c138465a..a06f2138042 100644 --- a/api/src/com/cloud/storage/StorageService.java +++ b/api/src/com/cloud/storage/StorageService.java @@ -17,15 +17,13 @@ package com.cloud.storage; import java.net.UnknownHostException; -import java.util.List; -import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; -import com.cloud.api.commands.CreateStoragePoolCmd; -import com.cloud.api.commands.CreateVolumeCmd; -import com.cloud.api.commands.DeletePoolCmd; -import com.cloud.api.commands.ListVolumesCmd; -import com.cloud.api.commands.UpdateStoragePoolCmd; -import com.cloud.api.commands.UploadVolumeCmd; +import org.apache.cloudstack.api.command.admin.storage.*; +import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.PermissionDeniedException; @@ -33,12 +31,11 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -import com.cloud.utils.Pair; public interface StorageService{ /** * Create StoragePool based on uri - * + * * @param cmd * the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the * storage pool. @@ -49,12 +46,12 @@ public interface StorageService{ * @throws ResourceUnavailableException * TODO */ - StoragePool createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, + StoragePool createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException; /** * Creates the database object for a volume based on the given criteria - * + * * @param cmd * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, * name) @@ -65,7 +62,7 @@ public interface StorageService{ /** * Creates the volume based on the given criteria - * + * * @param cmd * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, * name) @@ -75,9 +72,18 @@ public interface StorageService{ /** - * Delete the storage pool + * Resizes the volume based on the given criteria * * @param cmd + * the API command wrapping the criteria + * @return the volume object + */ + Volume resizeVolume(ResizeVolumeCmd cmd); + + /** + * Delete the storage pool + * + * @param cmd * - the command specifying poolId * @return success or failure */ @@ -85,7 +91,7 @@ public interface StorageService{ /** * Enable maintenance for primary storage - * + * * @param cmd * - the command specifying primaryStorageId * @return the primary storage pool @@ -94,19 +100,19 @@ public interface StorageService{ * @throws InsufficientCapacityException * TODO */ - public StoragePool preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, + public StoragePool preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, InsufficientCapacityException; /** * Complete maintenance for primary storage - * + * * @param cmd * - the command specifying primaryStorageId * @return the primary storage pool * @throws ResourceUnavailableException * TODO */ - public StoragePool cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) + public StoragePool cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ResourceUnavailableException; public StoragePool updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException; @@ -115,13 +121,12 @@ public interface StorageService{ Volume migrateVolume(Long volumeId, Long storagePoolId) throws ConcurrentOperationException; - Pair, Integer> searchForVolumes(ListVolumesCmd cmd); /** * Uploads the volume to secondary storage - * - * @param UploadVolumeCmd cmd - * + * + * @param UploadVolumeCmd cmd + * * @return Volume object */ Volume uploadVolume(UploadVolumeCmd cmd) throws ResourceAllocationException; diff --git a/api/src/com/cloud/storage/StorageStats.java b/api/src/com/cloud/storage/StorageStats.java index fe21c44b702..c30e1de10f6 100755 --- a/api/src/com/cloud/storage/StorageStats.java +++ b/api/src/com/cloud/storage/StorageStats.java @@ -22,7 +22,7 @@ public interface StorageStats { */ public long getByteUsed(); /** - * @return bytes capacity of the storage server + * @return bytes capacity of the storage server */ public long getCapacityBytes(); } diff --git a/api/src/com/cloud/storage/Swift.java b/api/src/com/cloud/storage/Swift.java index 54a670cefe1..9cd3a34cd59 100644 --- a/api/src/com/cloud/storage/Swift.java +++ b/api/src/com/cloud/storage/Swift.java @@ -17,10 +17,13 @@ package com.cloud.storage; import com.cloud.agent.api.to.SwiftTO; +import org.apache.cloudstack.api.InternalIdentity; -public interface Swift { +public interface Swift extends InternalIdentity { public long getId(); + public String getUuid(); + public String getUrl(); public String getAccount(); diff --git a/api/src/com/cloud/storage/Upload.java b/api/src/com/cloud/storage/Upload.java index d73a9d8604c..a20faf1dc34 100755 --- a/api/src/com/cloud/storage/Upload.java +++ b/api/src/com/cloud/storage/Upload.java @@ -16,9 +16,12 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface Upload { +public interface Upload extends InternalIdentity, Identity { public static enum Status { UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR @@ -34,8 +37,6 @@ public interface Upload { long getHostId(); - long getId(); - Date getCreated(); Date getLastUpdated(); diff --git a/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java b/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java index 49fbc6da427..97baa4b29c4 100644 --- a/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java +++ b/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java @@ -16,9 +16,12 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface VMTemplateStorageResourceAssoc { +public interface VMTemplateStorageResourceAssoc extends InternalIdentity { public static enum Status { UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS } @@ -35,8 +38,6 @@ public interface VMTemplateStorageResourceAssoc { void setDownloadState(Status downloadState); - long getId(); - Date getCreated(); Date getLastUpdated(); diff --git a/api/src/com/cloud/storage/Volume.java b/api/src/com/cloud/storage/Volume.java index 6e8e48e48d8..38ba2d413e0 100755 --- a/api/src/com/cloud/storage/Volume.java +++ b/api/src/com/cloud/storage/Volume.java @@ -18,12 +18,14 @@ package com.cloud.storage; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.template.BasedOn; import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Volume extends ControlledEntity, BasedOn, StateObject { +public interface Volume extends ControlledEntity, Identity, InternalIdentity, BasedOn, StateObject { enum Type { UNKNOWN, ROOT, SWAP, DATADISK, ISO }; @@ -34,9 +36,10 @@ public interface Volume extends ControlledEntity, BasedOn, StateObject listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd); + List listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd); - boolean updateTemplateOrIsoPermissions(UpdateTemplateOrIsoPermissionsCmd cmd); + boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd); } diff --git a/api/src/com/cloud/template/VirtualMachineTemplate.java b/api/src/com/cloud/template/VirtualMachineTemplate.java index 27f5871b750..274b7b63843 100755 --- a/api/src/com/cloud/template/VirtualMachineTemplate.java +++ b/api/src/com/cloud/template/VirtualMachineTemplate.java @@ -19,12 +19,14 @@ package com.cloud.template; import java.util.Date; import java.util.Map; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VirtualMachineTemplate extends ControlledEntity { +public interface VirtualMachineTemplate extends ControlledEntity, Identity, InternalIdentity { public static enum BootloaderType { PyGrub, HVM, External, CD @@ -40,11 +42,6 @@ public interface VirtualMachineTemplate extends ControlledEntity { all // all templates (only usable by admins) } - /** - * @return id. - */ - long getId(); - boolean isFeatured(); /** diff --git a/api/src/com/cloud/user/Account.java b/api/src/com/cloud/user/Account.java index 18f585be75b..a5b3e87156d 100755 --- a/api/src/com/cloud/user/Account.java +++ b/api/src/com/cloud/user/Account.java @@ -18,9 +18,11 @@ package com.cloud.user; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Account extends ControlledEntity { +public interface Account extends ControlledEntity, InternalIdentity, Identity { public enum Type { Normal, Admin, @@ -35,6 +37,7 @@ public interface Account extends ControlledEntity { locked } + public static final short ACCOUNT_TYPE_NORMAL = 0; public static final short ACCOUNT_TYPE_ADMIN = 1; public static final short ACCOUNT_TYPE_DOMAIN_ADMIN = 2; @@ -48,8 +51,6 @@ public interface Account extends ControlledEntity { public static final long ACCOUNT_ID_SYSTEM = 1; - public long getId(); - public String getAccountName(); public short getType(); @@ -59,6 +60,7 @@ public interface Account extends ControlledEntity { public Date getRemoved(); public String getNetworkDomain(); - + public Long getDefaultZoneId(); + } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 90e35519578..9f5f4d225e0 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -19,14 +19,15 @@ package com.cloud.user; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; + import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; @@ -37,7 +38,7 @@ public interface AccountService { /** * Creates a new user and account, stores the password as is so encrypted passwords are recommended. - * + * * @param userName * TODO * @param password @@ -58,7 +59,7 @@ public interface AccountService { * TODO * @param networkDomain * TODO - * + * * @return the user if created successfully, null otherwise */ UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, @@ -66,17 +67,17 @@ public interface AccountService { /** * Deletes a user by userId - * + * * @param accountId * - id of the account do delete - * + * * @return true if delete was successful, false otherwise */ boolean deleteUserAccount(long accountId); /** * Disables a user by userId - * + * * @param userId * - the userId * @return UserAccount object @@ -85,7 +86,7 @@ public interface AccountService { /** * Enables a user - * + * * @param userId * - the userId * @return UserAccount object @@ -95,7 +96,7 @@ public interface AccountService { /** * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses * allocated/etc. - * + * * @param userId * @return UserAccount object */ @@ -103,7 +104,7 @@ public interface AccountService { /** * Update a user by userId - * + * * @param userId * @return UserAccount object */ @@ -111,7 +112,7 @@ public interface AccountService { /** * Disables an account by accountName and domainId - * + * * @param accountName * TODO * @param domainId @@ -125,7 +126,7 @@ public interface AccountService { /** * Enables an account by accountId - * + * * @param accountName * - the enableAccount command defining the accountId to be deleted. * @param domainId @@ -139,7 +140,7 @@ public interface AccountService { * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP * addresses * allocated/etc. - * + * * @param accountName * - the LockAccount command defining the accountId to be locked. * @param domainId @@ -151,7 +152,7 @@ public interface AccountService { /** * Updates an account name - * + * * @param cmd * - the parameter containing accountId * @return updated account object @@ -191,13 +192,10 @@ public interface AccountService { public String[] createApiKeyAndSecretKey(RegisterCmd cmd); - Pair, Integer> searchForAccounts(ListAccountsCmd cmd); - - Pair, Integer> searchForUsers(ListUsersCmd cmd) - throws PermissionDeniedException; - UserAccount getUserByApiKey(String apiKey); - + + RoleType getRoleType(Account account); + void checkAccess(Account account, Domain domain) throws PermissionDeniedException; void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 83f362264b0..cd20060b710 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -18,8 +18,8 @@ package com.cloud.user; import java.util.List; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import com.cloud.domain.Domain; import com.cloud.exception.PermissionDeniedException; import com.cloud.utils.Pair; @@ -30,9 +30,11 @@ public interface DomainService { Domain getDomain(long id); + Domain getDomain(String uuid); + /** * Return whether a domain is a child domain of a given domain. - * + * * @param parentId * @param childId */ diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java index 98dfc11319a..bec65d5b7e8 100644 --- a/api/src/com/cloud/user/ResourceLimitService.java +++ b/api/src/com/cloud/user/ResourceLimitService.java @@ -28,7 +28,7 @@ public interface ResourceLimitService { /** * Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one. - * + * * @param accountId * TODO * @param domainId @@ -37,14 +37,14 @@ public interface ResourceLimitService { * TODO * @param max * TODO - * + * * @return the updated/created resource limit */ ResourceLimit updateResourceLimit(Long accountId, Long domainId, Integer resourceType, Long max); /** * Updates an existing resource count details for the account/domain - * + * * @param accountId * TODO * @param domainId @@ -57,7 +57,7 @@ public interface ResourceLimitService { /** * Search for resource limits for the given id and/or account and/or type and/or domain. - * + * * @param id * TODO * @param accountId @@ -73,17 +73,27 @@ public interface ResourceLimitService { /** * Finds the resource limit for a specified account and type. If the account has an infinite limit, will check * the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit. - * + * * @param account * @param type * @return resource limit */ public long findCorrectResourceLimitForAccount(Account account, ResourceType type); + /** + * This call should be used when we have already queried resource limit for an account. This is to handle + * some corner cases where queried limit may be null. + * @param accountType + * @param limit + * @param type + * @return + */ + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type); + /** * Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check * up the domain hierarchy - * + * * @param account * @param type * @return resource limit @@ -92,7 +102,7 @@ public interface ResourceLimitService { /** * Increments the resource count - * + * * @param accountId * @param type * @param delta @@ -101,7 +111,7 @@ public interface ResourceLimitService { /** * Decrements the resource count - * + * * @param accountId * @param type * @param delta @@ -110,7 +120,7 @@ public interface ResourceLimitService { /** * Checks if a limit has been exceeded for an account - * + * * @param account * @param type * @param count @@ -122,7 +132,7 @@ public interface ResourceLimitService { /** * Gets the count of resources for a resource type and account - * + * * @param account * @param type * @return count of resources diff --git a/api/src/com/cloud/user/SSHKeyPair.java b/api/src/com/cloud/user/SSHKeyPair.java index 494f74f5a7a..aa20c17eb07 100644 --- a/api/src/com/cloud/user/SSHKeyPair.java +++ b/api/src/com/cloud/user/SSHKeyPair.java @@ -16,14 +16,10 @@ // under the License. package com.cloud.user; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SSHKeyPair extends ControlledEntity { - - /** - * @return The id of the key pair. - */ - public long getId(); +public interface SSHKeyPair extends ControlledEntity, InternalIdentity { /** * @return The given name of the key pair. diff --git a/api/src/com/cloud/user/User.java b/api/src/com/cloud/user/User.java index c625c168d0d..36a7c6543b0 100644 --- a/api/src/com/cloud/user/User.java +++ b/api/src/com/cloud/user/User.java @@ -16,13 +16,17 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface User extends OwnedBy { +public interface User extends OwnedBy, InternalIdentity { public static final long UID_SYSTEM = 1; public long getId(); + public String getUuid(); + public Date getCreated(); public Date getRemoved(); diff --git a/api/src/com/cloud/user/UserAccount.java b/api/src/com/cloud/user/UserAccount.java index 2a6bd4f33e3..c09b5c0fac5 100644 --- a/api/src/com/cloud/user/UserAccount.java +++ b/api/src/com/cloud/user/UserAccount.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface UserAccount { - Long getId(); +public interface UserAccount extends InternalIdentity { + long getId(); String getUsername(); diff --git a/api/src/com/cloud/user/UserContext.java b/api/src/com/cloud/user/UserContext.java index b140728e596..539e11812af 100644 --- a/api/src/com/cloud/user/UserContext.java +++ b/api/src/com/cloud/user/UserContext.java @@ -50,6 +50,10 @@ public class UserContext { return userId; } + public User getCallerUser() { + return _accountMgr.getActiveUser(userId); + } + public void setCallerUserId(long userId) { this.userId = userId; } diff --git a/api/src/com/cloud/uservm/UserVm.java b/api/src/com/cloud/uservm/UserVm.java index 866d849748d..a587666bc8b 100755 --- a/api/src/com/cloud/uservm/UserVm.java +++ b/api/src/com/cloud/uservm/UserVm.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.uservm; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.vm.VirtualMachine; /** diff --git a/api/src/com/cloud/vm/InstanceGroup.java b/api/src/com/cloud/vm/InstanceGroup.java index 98fac593d9b..6560b4afe81 100644 --- a/api/src/com/cloud/vm/InstanceGroup.java +++ b/api/src/com/cloud/vm/InstanceGroup.java @@ -18,10 +18,11 @@ package com.cloud.vm; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface InstanceGroup extends ControlledEntity { - long getId(); +public interface InstanceGroup extends ControlledEntity, Identity, InternalIdentity { String getName(); diff --git a/api/src/com/cloud/vm/Nic.java b/api/src/com/cloud/vm/Nic.java index 3beff0a5ada..84c0034b430 100644 --- a/api/src/com/cloud/vm/Nic.java +++ b/api/src/com/cloud/vm/Nic.java @@ -25,17 +25,19 @@ import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.Mode; import com.cloud.utils.fsm.FiniteState; import com.cloud.utils.fsm.StateMachine; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Nic represents one nic on the VM. */ -public interface Nic { +public interface Nic extends Identity, InternalIdentity { enum Event { ReservationRequested, ReleaseRequested, CancelRequested, OperationCompleted, OperationFailed, } public enum State implements FiniteState { - Allocated("Resource is allocated but not reserved"), Reserving("Resource is being reserved right now"), + Allocated("Resource is allocated but not reserved"), Reserving("Resource is being reserved right now"), Reserved("Resource has been reserved."), Releasing("Resource is being released"), Deallocating( "Resource is being deallocated"); @@ -86,11 +88,6 @@ public interface Nic { PlaceHolder, Create, Start, Managed; } - /** - * @return id in the CloudStack database - */ - long getId(); - /** * @return reservation id returned by the allocation source. This can be the String version of the database id if * the diff --git a/api/src/com/cloud/vm/NicProfile.java b/api/src/com/cloud/vm/NicProfile.java index c5ffbeaa502..32e3f212e99 100644 --- a/api/src/com/cloud/vm/NicProfile.java +++ b/api/src/com/cloud/vm/NicProfile.java @@ -24,8 +24,9 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.vm.Nic.ReservationStrategy; +import org.apache.cloudstack.api.InternalIdentity; -public class NicProfile { +public class NicProfile implements InternalIdentity { long id; long networkId; BroadcastDomainType broadcastType; @@ -207,7 +208,7 @@ public class NicProfile { return strategy; } - public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, + public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, boolean isSecurityGroupEnabled, String name) { this.id = nic.getId(); this.networkId = network.getId(); diff --git a/api/src/com/cloud/vm/RunningOn.java b/api/src/com/cloud/vm/RunningOn.java index a04e28edc3d..cb642939f3d 100644 --- a/api/src/com/cloud/vm/RunningOn.java +++ b/api/src/com/cloud/vm/RunningOn.java @@ -17,7 +17,7 @@ package com.cloud.vm; /** - * + * */ public interface RunningOn { diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index 98d02dbebdd..b1ebe10596d 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -21,22 +21,21 @@ import java.util.Map; import javax.naming.InsufficientResourcesException; -import com.cloud.api.commands.AssignVMCmd; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.CreateVMGroupCmd; -import com.cloud.api.commands.DeleteVMGroupCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DestroyVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.ListVMsCmd; -import com.cloud.api.commands.RebootVMCmd; -import com.cloud.api.commands.RecoverVMCmd; -import com.cloud.api.commands.ResetVMPasswordCmd; -import com.cloud.api.commands.RestoreVMCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpdateVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; + import com.cloud.dc.DataCenter; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -53,13 +52,12 @@ import com.cloud.storage.Volume; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -import com.cloud.utils.Pair; import com.cloud.utils.exception.ExecutionException; public interface UserVmService { /** * Destroys one virtual machine - * + * * @param userId * the id of the user performing the action * @param vmId @@ -71,7 +69,7 @@ public interface UserVmService { /** * Destroys one virtual machine - * + * * @param userId * the id of the user performing the action * @param vmId @@ -83,7 +81,7 @@ public interface UserVmService { /** * Resets the password of a virtual machine. - * + * * @param cmd * - the command specifying vmId, password * @return the VM if reset worked successfully, null otherwise @@ -92,7 +90,7 @@ public interface UserVmService { /** * Attaches the specified volume to the specified VM - * + * * @param cmd * - the command specifying volumeId and vmId * @return the Volume object if attach worked successfully. @@ -101,7 +99,7 @@ public interface UserVmService { /** * Detaches the specified volume from the VM it is currently attached to. - * + * * @param cmd * - the command specifying volumeId * @return the Volume object if detach worked successfully. @@ -119,7 +117,7 @@ public interface UserVmService { /** * Create a template database record in preparation for creating a private template. - * + * * @param cmd * the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. * for the @@ -133,7 +131,7 @@ public interface UserVmService { /** * Creates a private template from a snapshot of a VM - * + * * @param cmd * - the command specifying snapshotId, name, description * @return a template if successfully created, null otherwise @@ -142,7 +140,7 @@ public interface UserVmService { /** * Creates a Basic Zone User VM in the database and returns the VM to the caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -189,7 +187,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -205,7 +203,7 @@ public interface UserVmService { /** * Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the * caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -254,7 +252,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -271,7 +269,7 @@ public interface UserVmService { /** * Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the * caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -318,7 +316,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -333,7 +331,7 @@ public interface UserVmService { /** * Starts the virtual machine created from createVirtualMachine. - * + * * @param cmd * Command to deploy. * @return UserVm object if successful. @@ -348,7 +346,7 @@ public interface UserVmService { /** * Creates a vm group. - * + * * @param name * - name of the group * @param accountId @@ -360,7 +358,7 @@ public interface UserVmService { /** * upgrade the service offering of the virtual machine - * + * * @param cmd * - the command specifying vmId and new serviceOfferingId * @return the vm @@ -371,15 +369,6 @@ public interface UserVmService { void deletePrivateTemplateRecord(Long templateId); - /** - * Obtains a list of virtual machines by the specified search criteria. Can search by: "userId", "name", "state", - * "dataCenterId", "podId", "hostId" - * - * @param cmd - * the API command that wraps the search criteria - * @return List of UserVMs. - */ - Pair, Integer> searchForUserVMs(ListVMsCmd cmd); HypervisorType getHypervisorTypeOfUserVM(long vmid); @@ -392,7 +381,7 @@ public interface UserVmService { * Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds. * Only Root * Admin can migrate a VM. - * + * * @param destinationStorage * TODO * @param Long @@ -400,7 +389,7 @@ public interface UserVmService { * vmId of The VM to migrate * @param Host * destinationHost to migrate the VM - * + * * @return VirtualMachine migrated VM * @throws ManagementServerException * in case we get error finding the VM or host or access errors or other internal errors. diff --git a/api/src/com/cloud/vm/VirtualMachine.java b/api/src/com/cloud/vm/VirtualMachine.java index 1fa16c32fa0..cd305795478 100755 --- a/api/src/com/cloud/vm/VirtualMachine.java +++ b/api/src/com/cloud/vm/VirtualMachine.java @@ -19,17 +19,18 @@ package com.cloud.vm; import java.util.Date; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.InternalIdentity; /** * VirtualMachine describes the properties held by a virtual machine - * + * */ -public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, StateObject { +public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, InternalIdentity, StateObject { public enum State { Starting(true, "VM is being started. At this state, you should find host id filled which means it's being started on that host."), @@ -206,11 +207,6 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S */ public String getInstanceName(); - /** - * @return the id of this virtual machine. null means the id has not been set. - */ - public long getId(); - /** * @return the host name of the virtual machine. If the user did not * specify the host name when creating the virtual machine then it is @@ -245,7 +241,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S /** * returns the guest OS ID - * + * * @return guestOSId */ public long getGuestOSId(); @@ -290,6 +286,6 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S HypervisorType getHypervisorType(); public Map getDetails(); - + boolean canPlugNics(); } diff --git a/api/src/com/cloud/vm/VirtualMachineProfile.java b/api/src/com/cloud/vm/VirtualMachineProfile.java index 57277db32f3..0fab4436807 100644 --- a/api/src/com/cloud/vm/VirtualMachineProfile.java +++ b/api/src/com/cloud/vm/VirtualMachineProfile.java @@ -30,7 +30,7 @@ import com.cloud.user.Account; * VirtualMachineProfile describes one virtual machine. This object * on what the virtual machine profile should look like before it is * actually started on the hypervisor. - * + * * @param * a VirtualMachine */ diff --git a/api/src/org/apache/cloudstack/acl/APIChecker.java b/api/src/org/apache/cloudstack/acl/APIChecker.java new file mode 100644 index 00000000000..0d0dfd1be4e --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/APIChecker.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +import com.cloud.exception.PermissionDeniedException; +import com.cloud.user.User; +import com.cloud.utils.component.Adapter; + +// APIChecker checks the ownership and access control to API requests +public interface APIChecker extends Adapter { + // Interface for checking access for a role using apiname + // If true, apiChecker has checked the operation + // If false, apiChecker is unable to handle the operation or not implemented + // On exception, checkAccess failed don't allow + boolean checkAccess(User user, String apiCommandName) throws PermissionDeniedException; +} diff --git a/api/src/com/cloud/acl/ControlledEntity.java b/api/src/org/apache/cloudstack/acl/ControlledEntity.java similarity index 96% rename from api/src/com/cloud/acl/ControlledEntity.java rename to api/src/org/apache/cloudstack/acl/ControlledEntity.java index 190dd41eea4..3e0412623e2 100644 --- a/api/src/com/cloud/acl/ControlledEntity.java +++ b/api/src/org/apache/cloudstack/acl/ControlledEntity.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.acl; +package org.apache.cloudstack.acl; import com.cloud.domain.PartOf; import com.cloud.user.OwnedBy; @@ -22,7 +22,7 @@ import com.cloud.user.OwnedBy; /** * ControlledEntity defines an object for which the access from an * access must inherit this interface. - * + * */ public interface ControlledEntity extends OwnedBy, PartOf { public enum ACLType { diff --git a/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java b/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java new file mode 100644 index 00000000000..451c0c89ede --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java @@ -0,0 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +public interface InfrastructureEntity { +} diff --git a/api/src/org/apache/cloudstack/acl/Role.java b/api/src/org/apache/cloudstack/acl/Role.java new file mode 100644 index 00000000000..d039a6f95ff --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/Role.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +//metadata - consists of default dynamic roles in CS + any custom roles added by user +public interface Role { + + public static final short ROOT_ADMIN = 0; + public static final short DOMAIN_ADMIN = 1; + public static final short DOMAIN_USER = 2; + public static final short OWNER = 3; + public static final short PARENT_DOMAIN_ADMIN = 4; + public static final short PARENT_DOMAIN_USER = 5; + public static final short CHILD_DOMAIN_ADMIN = 6; + public static final short CHILD_DOMAIN_USER = 7; + + public long getId(); + public short getRoleType(); + } diff --git a/api/src/org/apache/cloudstack/acl/RoleType.java b/api/src/org/apache/cloudstack/acl/RoleType.java new file mode 100644 index 00000000000..0d1c4460c1e --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/RoleType.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +// Enum for default roles in CloudStack +public enum RoleType { + + Admin(1), + ResourceAdmin(2), + DomainAdmin(4), + User(8), + Unknown(0); + + private int mask; + + private RoleType(int mask) { + this.mask = mask; + } + + public int getValue() { + return mask; + } +} diff --git a/api/src/com/cloud/acl/SecurityChecker.java b/api/src/org/apache/cloudstack/acl/SecurityChecker.java similarity index 98% rename from api/src/com/cloud/acl/SecurityChecker.java rename to api/src/org/apache/cloudstack/acl/SecurityChecker.java index 3f76da97809..3a721fe7fcb 100644 --- a/api/src/com/cloud/acl/SecurityChecker.java +++ b/api/src/org/apache/cloudstack/acl/SecurityChecker.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.acl; +package org.apache.cloudstack.acl; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -39,7 +39,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the account owns the object. - * + * * @param caller * account to check against. * @param object @@ -52,7 +52,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the user belongs to an account that owns the object. - * + * * @param user * user to check against. * @param object @@ -65,7 +65,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the account can access the object. - * + * * @param caller * account to check against. * @param entity @@ -80,7 +80,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the user belongs to an account that can access the object. - * + * * @param user * user to check against. * @param entity diff --git a/api/src/com/cloud/api/IdentityMapper.java b/api/src/org/apache/cloudstack/api/ACL.java similarity index 87% rename from api/src/com/cloud/api/IdentityMapper.java rename to api/src/org/apache/cloudstack/api/ACL.java index 4515b805d05..3623d1ac523 100644 --- a/api/src/com/cloud/api/IdentityMapper.java +++ b/api/src/org/apache/cloudstack/api/ACL.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; @@ -24,6 +24,8 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) -public @interface IdentityMapper { - String entityTableName(); +public @interface ACL { + + boolean checkKeyAccess() default false; + boolean checkValueAccess() default false; } diff --git a/api/src/com/cloud/api/Implementation.java b/api/src/org/apache/cloudstack/api/APICommand.java similarity index 92% rename from api/src/com/cloud/api/Implementation.java rename to api/src/org/apache/cloudstack/api/APICommand.java index 6f0b965c3ec..4d024c15a5d 100644 --- a/api/src/com/cloud/api/Implementation.java +++ b/api/src/org/apache/cloudstack/api/APICommand.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.TYPE; @@ -22,13 +22,13 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.cloud.api.response.BaseResponse; - @Retention(RetentionPolicy.RUNTIME) @Target({ TYPE }) -public @interface Implementation { +public @interface APICommand { Class responseObject(); + String name() default ""; + String description() default ""; String usage() default ""; diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java old mode 100755 new mode 100644 similarity index 98% rename from api/src/com/cloud/api/ApiConstants.java rename to api/src/org/apache/cloudstack/api/ApiConstants.java index 588cdc6c140..58a78318fae --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import org.omg.CORBA.PUBLIC_MEMBER; @@ -91,6 +91,7 @@ public class ApiConstants { public static final String INTERVAL_TYPE = "intervaltype"; public static final String IP_ADDRESS = "ipaddress"; public static final String IP_ADDRESS_ID = "ipaddressid"; + public static final String IS_ASYNC = "isasync"; public static final String IP_AVAILABLE = "ipavailable"; public static final String IP_LIMIT = "iplimit"; public static final String IP_TOTAL = "iptotal"; @@ -106,6 +107,7 @@ public class ApiConstants { public static final String JOB_STATUS = "jobstatus"; public static final String LASTNAME = "lastname"; public static final String LEVEL = "level"; + public static final String LENGTH = "length"; public static final String LIMIT_CPU_USE = "limitcpuuse"; public static final String LOCK = "lock"; public static final String LUN = "lun"; @@ -126,6 +128,7 @@ public class ApiConstants { public static final String OP = "op"; public static final String OS_CATEGORY_ID = "oscategoryid"; public static final String OS_TYPE_ID = "ostypeid"; + public static final String PARAMS = "params"; public static final String PARENT_DOMAIN_ID = "parentdomainid"; public static final String PASSWORD = "password"; public static final String NEW_PASSWORD = "new_password"; @@ -155,10 +158,12 @@ public class ApiConstants { public static final String RECEIVED_BYTES = "receivedbytes"; public static final String REQUIRES_HVM = "requireshvm"; public static final String RESOURCE_TYPE = "resourcetype"; + public static final String RESPONSE = "response"; public static final String QUERY_FILTER = "queryfilter"; public static final String SCHEDULE = "schedule"; public static final String SCOPE = "scope"; public static final String SECRET_KEY = "usersecretkey"; + public static final String SINCE = "since"; public static final String KEY = "key"; public static final String SEARCH_BASE = "searchbase"; public static final String SECURITY_GROUP_IDS = "securitygroupids"; @@ -324,6 +329,7 @@ public class ApiConstants { public static final String SOURCE_NAT_SUPPORTED = "sourcenatsupported"; public static final String RESOURCE_STATE = "resourcestate"; public static final String PROJECT_INVITE_REQUIRED = "projectinviterequired"; + public static final String REQUIRED = "required"; public static final String RESTART_REQUIRED = "restartrequired"; public static final String ALLOW_USER_CREATE_PROJECTS = "allowusercreateprojects"; public static final String CONSERVE_MODE = "conservemode"; @@ -381,10 +387,11 @@ public class ApiConstants { public static final String ESP_LIFETIME = "esplifetime"; public static final String DPD = "dpd"; public static final String FOR_VPC = "forvpc"; + public static final String SHRINK_OK = "shrinkok"; public static final String NICIRA_NVP_DEVICE_ID = "nvpdeviceid"; public static final String NICIRA_NVP_TRANSPORT_ZONE_UUID = "transportzoneuuid"; public static final String NICIRA_NVP_DEVICE_NAME = "niciradevicename"; - public static final String NICIRA_NVP_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; + public static final String NICIRA_NVP_GATEWAYSERVICE_UUID = "l3gatewayserviceuuid"; public static final String S3_ACCESS_KEY = "accesskey"; public static final String S3_SECRET_KEY = "secretkey"; public static final String S3_END_POINT = "endpoint"; @@ -395,7 +402,6 @@ public class ApiConstants { public static final String S3_SOCKET_TIMEOUT = "sockettimeout"; public static final String INCL_ZONES = "includezones"; public static final String EXCL_ZONES = "excludezones"; - public static final String SOURCE = "source"; public static final String COUNTER_ID = "counterid"; public static final String AGGR_OPERATOR = "aggroperator"; @@ -429,7 +435,7 @@ public class ApiConstants { public enum VMDetails { all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min; } - + public enum LDAPParams { hostname, port, usessl, queryfilter, searchbase, dn, passwd, truststore, truststorepass; diff --git a/api/src/com/cloud/api/BaseAsyncCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCmd.java similarity index 95% rename from api/src/com/cloud/api/BaseAsyncCmd.java rename to api/src/org/apache/cloudstack/api/BaseAsyncCmd.java index cf6d0bdbb93..fd67ed89675 100644 --- a/api/src/com/cloud/api/BaseAsyncCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCmd.java @@ -14,9 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; -import com.cloud.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; import com.cloud.async.AsyncJob; import com.cloud.user.User; import com.cloud.user.UserContext; @@ -25,7 +25,7 @@ import com.cloud.user.UserContext; * queryAsyncJobResult API command. */ public abstract class BaseAsyncCmd extends BaseCmd { - + public static final String ipAddressSyncObject = "ipaddress"; public static final String networkSyncObject = "network"; public static final String vpcSyncObject = "vpc"; @@ -40,7 +40,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { * For proper tracking of async commands through the system, events must be generated when the command is * scheduled, started, and completed. Commands should specify the type of event so that when the scheduled, * started, and completed events are saved to the events table, they have the proper type information. - * + * * @return a string representing the type of event, e.g. VM.START, VOLUME.CREATE. */ public abstract String getEventType(); @@ -49,7 +49,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { * For proper tracking of async commands through the system, events must be generated when the command is * scheduled, started, and completed. Commands should specify a description for these events so that when * the scheduled, started, and completed events are saved to the events table, they have a meaningful description. - * + * * @return a string representing a description of the event */ public abstract String getEventDescription(); @@ -57,7 +57,8 @@ public abstract class BaseAsyncCmd extends BaseCmd { public ResponseObject getResponse(long jobId) { AsyncJobResponse response = new AsyncJobResponse(); - response.setJobId(jobId); + AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); + response.setJobId(job.getUuid()); response.setResponseName(getCommandName()); return response; } @@ -77,7 +78,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { /** * Async commands that want to be tracked as part of the listXXX commands need to * provide implementations of the two following methods, getInstanceId() and getInstanceType() - * + * * getObjectId() should return the id of the object the async command is executing on * getObjectType() should return a type from the AsyncJob.Type enumeration */ diff --git a/api/src/com/cloud/api/BaseAsyncCreateCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java similarity index 75% rename from api/src/com/cloud/api/BaseAsyncCreateCmd.java rename to api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java index 586c9c9e023..1f2d3f17beb 100644 --- a/api/src/com/cloud/api/BaseAsyncCreateCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java @@ -14,15 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; -import com.cloud.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; + +import com.cloud.async.AsyncJob; import com.cloud.exception.ResourceAllocationException; public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd { @Parameter(name = "id", type = CommandType.LONG) private Long id; + private String uuid; + public abstract void create() throws ResourceAllocationException; public Long getEntityId() { @@ -33,13 +37,19 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd { this.id = id; } - public abstract String getEntityTable(); + public String getEntityUuid() { + return uuid; + } - public String getResponse(long jobId, long objectId, String objectEntityTable) { + public void setEntityUuid(String uuid) { + this.uuid = uuid; + } + + public String getResponse(long jobId, String objectUuid) { CreateCmdResponse response = new CreateCmdResponse(); - response.setJobId(jobId); - response.setId(objectId); - response.setIdEntityTable(objectEntityTable); + AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); + response.setJobId(job.getUuid()); + response.setId(objectUuid); response.setResponseName(getCommandName()); return _responseGenerator.toSerializedString(response, getResponseType()); } diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java old mode 100755 new mode 100644 similarity index 96% rename from api/src/com/cloud/api/BaseCmd.java rename to api/src/org/apache/cloudstack/api/BaseCmd.java index 12a2176fb2e..3399784d2a2 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -15,17 +15,17 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import org.apache.cloudstack.query.QueryService; import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationService; @@ -63,7 +63,6 @@ import com.cloud.user.Account; import com.cloud.user.AccountService; import com.cloud.user.DomainService; import com.cloud.user.ResourceLimitService; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.vm.BareMetalVmService; @@ -79,7 +78,7 @@ public abstract class BaseCmd { public static final String RESPONSE_TYPE_JSON = "json"; public enum CommandType { - BOOLEAN, DATE, FLOAT, INTEGER, SHORT, LIST, LONG, OBJECT, MAP, STRING, TZDATE + BOOLEAN, DATE, FLOAT, INTEGER, SHORT, LIST, LONG, OBJECT, MAP, STRING, TZDATE, UUID } // FIXME: Extract these out into a separate file @@ -141,7 +140,9 @@ public abstract class BaseCmd { public static NetworkACLService _networkACLService; public static Site2SiteVpnService _s2sVpnService; - static void setComponents(ResponseGenerator generator) { + public static QueryService _queryService; + + public static void setComponents(ResponseGenerator generator) { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); _mgr = (ManagementService) ComponentLocator.getComponent(ManagementService.Name); _accountService = locator.getManager(AccountService.class); @@ -172,6 +173,7 @@ public abstract class BaseCmd { _vpcService = locator.getManager(VpcService.class); _networkACLService = locator.getManager(NetworkACLService.class); _s2sVpnService = locator.getManager(Site2SiteVpnService.class); + _queryService = locator.getManager(QueryService.class); } public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; @@ -192,7 +194,7 @@ public abstract class BaseCmd { /** * For commands the API framework needs to know the owner of the object being acted upon. This method is * used to determine that information. - * + * * @return the id of the account that owns the object being acted upon */ public abstract long getEntityOwnerId(); @@ -304,14 +306,14 @@ public abstract class BaseCmd { StringBuffer sb = new StringBuffer(); if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // JSON response - sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},"); + sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloudstack-version\":\"" + _mgr.getVersion() + "\"},"); sb.append("\"errorcode\" : \"" + apiException.getErrorCode() + "\", \"description\" : \"" + apiException.getDescription() + "\" } }"); } else { sb.append(""); sb.append("<" + getCommandName() + ">"); sb.append("" + apiException.getErrorCode() + ""); sb.append("" + escapeXml(apiException.getDescription()) + ""); - sb.append(""); + sb.append(""); } return sb.toString(); } @@ -322,10 +324,10 @@ public abstract class BaseCmd { // set up the return value with the name of the response if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { - prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},"); + prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloudstack-version\":\"" + _mgr.getVersion() + "\"},"); } else { prefixSb.append(""); - prefixSb.append("<" + getCommandName() + " cloud-stack-version=\"" + _mgr.getVersion() + "\">"); + prefixSb.append("<" + getCommandName() + " cloudstack-version=\"" + _mgr.getVersion() + "\">"); } int i = 0; @@ -508,8 +510,9 @@ public abstract class BaseCmd { throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active"); } } else { - List idList = new ArrayList(); - idList.add(new IdentityProxy("domain", domainId, "domainId")); + // idList is not used anywhere, so removed it now + //List idList = new ArrayList(); + //idList.add(new IdentityProxy("domain", domainId, "domainId")); throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id"); } } diff --git a/api/src/com/cloud/api/BaseListAccountResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java similarity index 97% rename from api/src/com/cloud/api/BaseListAccountResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java index 37010054526..038da63ec4c 100644 --- a/api/src/com/cloud/api/BaseListAccountResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public abstract class BaseListAccountResourcesCmd extends BaseListDomainResourcesCmd { diff --git a/api/src/com/cloud/api/BaseListCmd.java b/api/src/org/apache/cloudstack/api/BaseListCmd.java old mode 100755 new mode 100644 similarity index 98% rename from api/src/com/cloud/api/BaseListCmd.java rename to api/src/org/apache/cloudstack/api/BaseListCmd.java index d5ece6b14b3..58e83f70929 --- a/api/src/com/cloud/api/BaseListCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; @@ -62,7 +62,7 @@ public abstract class BaseListCmd extends BaseCmd { return pageSize; } - static void configure() { + public static void configure() { if (_configService.getDefaultPageSize().longValue() != PAGESIZE_UNLIMITED) { MAX_PAGESIZE = _configService.getDefaultPageSize(); } diff --git a/api/src/com/cloud/api/BaseListDomainResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java similarity index 72% rename from api/src/com/cloud/api/BaseListDomainResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java index 9571e1263c1..6e50a159f20 100644 --- a/api/src/com/cloud/api/BaseListDomainResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; + +import org.apache.cloudstack.api.response.DomainResponse; public abstract class BaseListDomainResourcesCmd extends BaseListCmd { @Parameter(name = ApiConstants.LIST_ALL, type = CommandType.BOOLEAN, description = "If set to false, " + - "list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") + "list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "list only resources" + - " belonging to the domain specified") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list only resources belonging to the domain specified") private Long domainId; @Parameter(name = ApiConstants.IS_RECURSIVE, type = CommandType.BOOLEAN, description = "defaults to false," + - " but if true, lists all resources from the parent specified by the domainId till leaves.") + " but if true, lists all resources from the parent specified by the domainId till leaves.") private Boolean recursive; public boolean listAll() { diff --git a/api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java similarity index 80% rename from api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java index 78e70019c9b..836527fc7c7 100644 --- a/api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java @@ -14,12 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; + +import org.apache.cloudstack.api.response.ProjectResponse; public abstract class BaseListProjectAndAccountResourcesCmd extends BaseListAccountResourcesCmd { - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list objects by project") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="list objects by project") private Long projectId; public Long getProjectId() { diff --git a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java similarity index 98% rename from api/src/com/cloud/api/BaseListTaggedResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java index 9b188d8ed25..88176a536ea 100644 --- a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.util.Collection; import java.util.HashMap; @@ -26,7 +26,7 @@ import com.cloud.exception.InvalidParameterValueException; public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccountResourcesCmd{ @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List resources by tags (key/value pairs)") private Map tags; - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { diff --git a/api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java index cacb41f405d..cde2d948686 100644 --- a/api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java @@ -14,33 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="List template visibility and all accounts that have permissions to view this template.", responseObject=TemplatePermissionsResponse.class) -public class ListTemplateOrIsoPermissionsCmd extends BaseCmd { - public Logger s_logger = getLogger(); +public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { + public Logger s_logger = getLogger(); protected String s_name = "listtemplatepermissionsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the template ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplatePermissionsResponse.class, + required=true, description="the template ID") private Long id; ///////////////////////////////////////////////////// @@ -68,23 +62,23 @@ public class ListTemplateOrIsoPermissionsCmd extends BaseCmd { public String getCommandName() { return s_name; } - + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return true; + return true; } - + public String getMediaType() { - return "templateOrIso"; + return "templateOrIso"; } - + protected Logger getLogger() { - return Logger.getLogger(UpdateTemplateOrIsoPermissionsCmd.class.getName()); + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); } - + @Override public void execute(){ List accountNames = _templateService.listTemplatePermissions(this); - + Account account = UserContext.current().getCaller(); boolean isAdmin = (isAdmin(account.getType())); diff --git a/api/src/com/cloud/api/response/BaseResponse.java b/api/src/org/apache/cloudstack/api/BaseResponse.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/response/BaseResponse.java rename to api/src/org/apache/cloudstack/api/BaseResponse.java index e343a104887..01f1be3253b --- a/api/src/com/cloud/api/response/BaseResponse.java +++ b/api/src/org/apache/cloudstack/api/BaseResponse.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.ResponseObject; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ResponseObject; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public abstract class BaseResponse implements ResponseObject { private transient String responseName; private transient String objectName; - + @Override public String getResponseName() { return responseName; @@ -35,7 +34,7 @@ public abstract class BaseResponse implements ResponseObject { public void setResponseName(String responseName) { this.responseName = responseName; } - + @Override public String getObjectName() { return objectName; @@ -45,31 +44,35 @@ public abstract class BaseResponse implements ResponseObject { public void setObjectName(String objectName) { this.objectName = objectName; } - - public Long getObjectId() { - return null; + + @Override + public String getObjectId() { + return null; } - - // For use by list commands with pending async jobs - @SerializedName(ApiConstants.JOB_ID) @Param(description="the ID of the latest async job acting on this object") - protected IdentityProxy jobId = new IdentityProxy("async_job"); - + + @SerializedName(ApiConstants.JOB_ID) @Param(description="the UUID of the latest async job acting on this object") + protected String jobId; + @SerializedName(ApiConstants.JOB_STATUS) @Param(description="the current status of the latest async job acting on this object") private Integer jobStatus; - - public Long getJobId() { - return jobId.getValue(); + + @Override + public String getJobId() { + return jobId; } - - public void setJobId(Long jobId) { - this.jobId.setValue(jobId); + + @Override + public void setJobId(String jobId) { + this.jobId = jobId; } - + + @Override public Integer getJobStatus() { - return jobStatus; + return jobStatus; } - + + @Override public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; + this.jobStatus = jobStatus; } } diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java rename to api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java index 89c4ee93f5e..dd6ae007ab9 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java @@ -14,17 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; -public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { +public abstract class BaseUpdateTemplateOrIsoCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateIsoCmd.class.getName()); ///////////////////////////////////////////////////// @@ -37,23 +38,23 @@ public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the image", length=4096) private String displayText; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the image file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the image file") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the image file") private String templateName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS type that best represents the OS of this image.") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="the ID of the OS type that best represents the OS of this image.") private Long osTypeId; - + @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, description="the format for the image") private String format; - + @Parameter(name=ApiConstants.PASSWORD_ENABLED, type=CommandType.BOOLEAN, description="true if the image supports the password reset feature; default is false") private Boolean passwordEnabled; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the template, integer") private Integer sortKey; @@ -80,16 +81,16 @@ public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { public Long getOsTypeId() { return osTypeId; } - + public Boolean isPasswordEnabled() { return passwordEnabled; } - + public String getFormat() { return format; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } } diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java old mode 100755 new mode 100644 similarity index 81% rename from api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java index 38a2e394145..aacc6efa2e0 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; import java.util.List; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; -public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { +public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Logger s_logger = getLogger(); protected String s_name = getResponseName(); @@ -39,8 +36,8 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNTS, type = CommandType.LIST, collectionType = CommandType.STRING, description = "a comma delimited list of accounts. If specified, \"op\" parameter has to be passed in.") private List accountNames; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the template ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, + required = true, description = "the template ID") private Long id; @Parameter(name = ApiConstants.IS_FEATURED, type = CommandType.BOOLEAN, description = "true for featured template/iso, false otherwise") @@ -48,15 +45,15 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true for public template/iso, false for private templates/isos") private Boolean isPublic; - + @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the template/iso is extractable, false other wise. Can be set only by root admin") private Boolean isExtractable; @Parameter(name = ApiConstants.OP, type = CommandType.STRING, description = "permission operator (add, remove, reset)") private String operation; - - @IdentityMapper(entityTableName="projects") - @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") + + @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ProjectResponse.class, + description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") private List projectIds; // /////////////////////////////////////////////////// @@ -65,10 +62,10 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public List getAccountNames() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); } - - return accountNames; + + return accountNames; } public Long getId() { @@ -82,18 +79,18 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public Boolean isExtractable() { return isExtractable; } - + public String getOperation() { return operation; } - + public List getProjectIds() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); } return projectIds; } @@ -112,7 +109,7 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { } protected Logger getLogger() { - return Logger.getLogger(UpdateTemplateOrIsoPermissionsCmd.class.getName()); + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); } @Override diff --git a/api/src/org/apache/cloudstack/api/EntityReference.java b/api/src/org/apache/cloudstack/api/EntityReference.java new file mode 100644 index 00000000000..1de84cee5da --- /dev/null +++ b/api/src/org/apache/cloudstack/api/EntityReference.java @@ -0,0 +1,28 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/* There is a one on one mapping between the EntityReference and the EntityResponse + * to the OTW layer. Value is the actual entity class it refers to. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface EntityReference { + Class[] value() default {}; +} diff --git a/api/src/com/cloud/api/Identity.java b/api/src/org/apache/cloudstack/api/Identity.java similarity index 96% rename from api/src/com/cloud/api/Identity.java rename to api/src/org/apache/cloudstack/api/Identity.java index 09ce7a8ac04..22d23b70017 100644 --- a/api/src/com/cloud/api/Identity.java +++ b/api/src/org/apache/cloudstack/api/Identity.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface Identity { String getUuid(); diff --git a/api/src/com/cloud/api/IdentityService.java b/api/src/org/apache/cloudstack/api/IdentityService.java similarity index 91% rename from api/src/com/cloud/api/IdentityService.java rename to api/src/org/apache/cloudstack/api/IdentityService.java index 1c53a1dfcd4..a2ccec2dae7 100644 --- a/api/src/com/cloud/api/IdentityService.java +++ b/api/src/org/apache/cloudstack/api/IdentityService.java @@ -14,12 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface IdentityService { - Long getIdentityId(IdentityMapper mapper, String identityString); - Long getIdentityId(String tableName, String identityString); - String getIdentityUuid(String tableName, String identityString); } diff --git a/api/src/org/apache/cloudstack/api/InternalIdentity.java b/api/src/org/apache/cloudstack/api/InternalIdentity.java new file mode 100644 index 00000000000..1dfeb8c9091 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/InternalIdentity.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api; + +// This interface is a contract that getId() will give the internal +// ID of an entity which extends this interface +// Any class having an internal ID in db table/schema should extend this +// For example, all ControlledEntity, OwnedBy would have an internal ID + +public interface InternalIdentity { + long getId(); +} diff --git a/api/src/com/cloud/api/Parameter.java b/api/src/org/apache/cloudstack/api/Parameter.java similarity index 88% rename from api/src/com/cloud/api/Parameter.java rename to api/src/org/apache/cloudstack/api/Parameter.java index 2da3c400f07..6f64737ab83 100644 --- a/api/src/com/cloud/api/Parameter.java +++ b/api/src/org/apache/cloudstack/api/Parameter.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; @@ -22,7 +22,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.BaseCmd.CommandType; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) @@ -37,6 +37,8 @@ public @interface Parameter { CommandType collectionType() default CommandType.OBJECT; + Class[] entityType() default Object.class; + boolean expose() default true; boolean includeInApiDoc() default true; @@ -44,4 +46,6 @@ public @interface Parameter { int length() default 255; String since() default ""; + + String retrieveMethod() default "getById"; } diff --git a/api/src/com/cloud/api/PlugService.java b/api/src/org/apache/cloudstack/api/PlugService.java similarity index 97% rename from api/src/com/cloud/api/PlugService.java rename to api/src/org/apache/cloudstack/api/PlugService.java index 7df86f9394f..00032e3abdd 100644 --- a/api/src/com/cloud/api/PlugService.java +++ b/api/src/org/apache/cloudstack/api/PlugService.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java old mode 100755 new mode 100644 similarity index 67% rename from api/src/com/cloud/api/ResponseGenerator.java rename to api/src/org/apache/cloudstack/api/ResponseGenerator.java index ec6c00ba8d4..63df4dc5532 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -14,83 +14,86 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.text.DecimalFormat; import java.util.EnumSet; import java.util.List; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.AutoScalePolicyResponse; -import com.cloud.api.response.AutoScaleVmGroupResponse; -import com.cloud.api.response.AutoScaleVmProfileResponse; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ConditionResponse; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.CounterResponse; -import com.cloud.api.response.CreateCmdResponse; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ExtractResponse; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.NetworkACLResponse; -import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.api.response.NetworkResponse; -import com.cloud.api.response.PhysicalNetworkResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.api.response.PrivateGatewayResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.api.response.S3Response; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.ServiceOfferingResponse; -import com.cloud.api.response.ServiceResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; -import com.cloud.api.response.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StaticRouteResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.SwiftResponse; -import com.cloud.api.response.SystemVmInstanceResponse; -import com.cloud.api.response.SystemVmResponse; -import com.cloud.api.response.TemplatePermissionsResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.TrafficTypeResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; -import com.cloud.api.response.VlanIpRangeResponse; -import com.cloud.api.response.VolumeResponse; -import com.cloud.api.response.VpcOfferingResponse; -import com.cloud.api.response.VpcResponse; -import com.cloud.api.response.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ServiceResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SwiftResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +import org.apache.cloudstack.api.response.S3Response; + import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.configuration.Configuration; @@ -128,7 +131,6 @@ import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.security.SecurityGroup; -import com.cloud.network.security.SecurityGroupRules; import com.cloud.network.security.SecurityRule; import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRoute; @@ -142,12 +144,14 @@ import com.cloud.projects.Project; import com.cloud.projects.ProjectAccount; import com.cloud.projects.ProjectInvitation; import com.cloud.server.ResourceTag; +import com.cloud.storage.GuestOS; import com.cloud.storage.S3; import com.cloud.storage.Snapshot; import com.cloud.storage.StoragePool; import com.cloud.storage.Swift; import com.cloud.storage.Volume; import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.User; @@ -237,7 +241,7 @@ public interface ResponseGenerator { List createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly); - ListResponse createSecurityGroupResponses(List networkGroups); + //ListResponse createSecurityGroupResponses(List networkGroups); SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List SecurityRules); @@ -251,6 +255,8 @@ public interface ResponseGenerator { EventResponse createEventResponse(Event event); + //List createEventResponse(EventJoinVO... events); + TemplateResponse createIsoResponse(VirtualMachineTemplate result); List createCapacityResponse(List result, DecimalFormat format); @@ -265,6 +271,8 @@ public interface ResponseGenerator { UserResponse createUserResponse(User user); + //List createUserResponse(UserAccountJoinVO... users); + AccountResponse createUserAccountResponse(UserAccount user); Long getSecurityGroupId(String groupName, long accountId); @@ -273,6 +281,7 @@ public interface ResponseGenerator { ProjectResponse createProjectResponse(Project project); + List createIsoResponses(VirtualMachineTemplate iso, long zoneId, boolean readyOnly); List createTemplateResponses(long templateId, Long vmId); @@ -304,13 +313,6 @@ public interface ResponseGenerator { LDAPConfigResponse createLDAPConfigResponse(String hostname, Integer port, Boolean useSSL, String queryFilter, String baseSearch, String dn); StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result); - - /** - * @param tableName TODO - * @param token - * @return - */ - Long getIdentiyId(String tableName, String token); /** * @param resourceTag @@ -319,8 +321,9 @@ public interface ResponseGenerator { */ ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly); + Site2SiteVpnGatewayResponse createSite2SiteVpnGatewayResponse(Site2SiteVpnGateway result); - + /** * @param offering @@ -357,7 +360,7 @@ public interface ResponseGenerator { Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result); CounterResponse createCounterResponse(Counter ctr); - + ConditionResponse createConditionResponse(Condition cndn); AutoScalePolicyResponse createAutoScalePolicyResponse(AutoScalePolicy policy); @@ -366,4 +369,7 @@ public interface ResponseGenerator { AutoScaleVmGroupResponse createAutoScaleVmGroupResponse(AutoScaleVmGroup vmGroup); + GuestOSResponse createGuestOSResponse(GuestOS os); + + SnapshotScheduleResponse createSnapshotScheduleResponse(SnapshotSchedule sched); } diff --git a/api/src/com/cloud/api/ResponseObject.java b/api/src/org/apache/cloudstack/api/ResponseObject.java similarity index 88% rename from api/src/com/cloud/api/ResponseObject.java rename to api/src/org/apache/cloudstack/api/ResponseObject.java index 2d08fb975b5..c8bd45727c9 100644 --- a/api/src/com/cloud/api/ResponseObject.java +++ b/api/src/org/apache/cloudstack/api/ResponseObject.java @@ -14,64 +14,65 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface ResponseObject { /** * Get the name of the API response - * + * * @return the name of the API response */ String getResponseName(); /** * Set the name of the API response - * + * * @param name */ void setResponseName(String name); /** * Get the name of the API object - * + * * @return the name of the API object */ String getObjectName(); /** - * + * * @param name */ void setObjectName(String name); /** - * Returns the object Id + * Returns the object UUid */ - Long getObjectId(); + String getObjectId(); /** * Returns the job id - * + * * @return */ - Long getJobId(); + String getJobId(); + /** * Sets the job id - * + * * @param jobId */ - void setJobId(Long jobId); + void setJobId(String jobId); /** * Returns the job status - * + * * @return */ Integer getJobStatus(); /** - * + * * @param jobStatus */ void setJobStatus(Integer jobStatus); diff --git a/api/src/com/cloud/api/ServerApiException.java b/api/src/org/apache/cloudstack/api/ServerApiException.java similarity index 88% rename from api/src/com/cloud/api/ServerApiException.java rename to api/src/org/apache/cloudstack/api/ServerApiException.java index 721cf13d353..1f57b74745d 100644 --- a/api/src/com/cloud/api/ServerApiException.java +++ b/api/src/org/apache/cloudstack/api/ServerApiException.java @@ -14,12 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; -import com.cloud.utils.IdentityProxy; -import com.cloud.utils.exception.RuntimeCloudException; +package org.apache.cloudstack.api; +import com.cloud.utils.exception.CloudRuntimeException; @SuppressWarnings("serial") -public class ServerApiException extends RuntimeCloudException { +public class ServerApiException extends CloudRuntimeException { private int _errorCode; private String _description; @@ -48,5 +47,5 @@ public class ServerApiException extends RuntimeCloudException { public void setDescription(String description) { _description = description; } - + } diff --git a/api/src/org/apache/cloudstack/api/Validate.java b/api/src/org/apache/cloudstack/api/Validate.java new file mode 100644 index 00000000000..deedda62273 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/Validate.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api; + +import static java.lang.annotation.ElementType.FIELD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ FIELD }) +public @interface Validate { + Class[] validators() default Object.class; + String description() default ""; +} diff --git a/api/src/com/cloud/api/commands/CreateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/commands/CreateAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java index 00e87761c5d..f93787b7bc5 --- a/api/src/com/cloud/api/commands/CreateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java @@ -14,26 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import java.util.Collection; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Creates an account", responseObject=UserResponse.class) +@APICommand(name = "createAccount", description="Creates an account", responseObject=UserResponse.class) public class CreateAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateAccountCmd.class.getName()); @@ -49,8 +46,8 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.SHORT, required=true, description="Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") private Short accountType; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Creates the user under the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Creates the user under the specified domain.") private Long domainId; @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, required=true, description="email") @@ -70,12 +67,13 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="Unique username.") private String userName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the account's networks") private String networkDomain; - @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") + @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -115,19 +113,19 @@ public class CreateAccountCmd extends BaseCmd { public String getUsername() { return userName; } - + public String getNetworkDomain() { return networkDomain; - } - + } + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } ///////////////////////////////////////////////////// @@ -138,12 +136,12 @@ public class CreateAccountCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); @@ -156,4 +154,4 @@ public class CreateAccountCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user account"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java old mode 100755 new mode 100644 similarity index 78% rename from api/src/com/cloud/api/commands/DeleteAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java index a7bfca78359..a1d9b6419cb --- a/api/src/com/cloud/api/commands/DeleteAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java @@ -14,39 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Deletes a account, and all users associated with this account", responseObject=SuccessResponse.class) +@APICommand(name = "deleteAccount", description="Deletes a account, and all users associated with this account", responseObject=SuccessResponse.class) public class DeleteAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAccountCmd.class.getName()); - private static final String s_name = "deleteaccountresponse"; + public static final Logger s_logger = Logger.getLogger(DeleteAccountCmd.class.getName()); + private static final String s_name = "deleteaccountresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + required=true, description="Account id") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,17 +49,16 @@ public class DeleteAccountCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - public static String getStaticName() { - return s_name; - } - + public static String getStaticName() { + return s_name; + } + @Override - public String getCommandName() { + public String getCommandName() { return s_name; } @@ -89,7 +82,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd { User user = _responseGenerator.findUserById(getId()); return (user != null ? ("deleting User " + user.getUsername() + " (id: " + user.getId() + ") and accountId = " + user.getAccountId()) : "user delete, but this user does not exist in the system"); } - + @Override public void execute(){ UserContext.current().setEventDetails("Account Id: "+getId()); @@ -101,7 +94,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user account and all corresponding users"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; diff --git a/api/src/com/cloud/api/commands/DisableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DisableAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java index 7c5e5e38331..f0a5e7078b7 100644 --- a/api/src/com/cloud/api/commands/DisableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -33,23 +30,23 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Disables an account", responseObject=AccountResponse.class) +@APICommand(name = "disableAccount", description="Disables an account", responseObject=AccountResponse.class) public class DisableAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableAccountCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DisableAccountCmd.class.getName()); private static final String s_name = "disableaccountresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Disables specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Disables specified account in this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Disables specified account in this domain.") private Long domainId; @Parameter(name=ApiConstants.LOCK, type=CommandType.BOOLEAN, required=true, description="If true, only lock the account; else disable the account") @@ -62,7 +59,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -91,7 +88,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { if (account != null) { return account.getAccountId(); } - + account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); if (account != null) { return account.getAccountId(); @@ -108,11 +105,11 @@ public class DisableAccountCmd extends BaseAsyncCmd { @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException{ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); - Account result = null; - if(lockRequested) - result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); - else - result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); + Account result = null; + if(lockRequested) + result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); + else + result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); @@ -121,7 +118,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, lockRequested == true ? "Failed to lock account" : "Failed to disable account" ); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; diff --git a/api/src/com/cloud/api/commands/EnableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/EnableAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java index 576f9354892..4aa1e4fc1b9 100644 --- a/api/src/com/cloud/api/commands/EnableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Enables an account", responseObject=AccountResponse.class) +@APICommand(name = "enableAccount", description="Enables an account", responseObject=AccountResponse.class) public class EnableAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(EnableAccountCmd.class.getName()); private static final String s_name = "enableaccountresponse"; @@ -35,15 +36,15 @@ public class EnableAccountCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Enables specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Enables specified account in this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Enables specified account in this domain.") private Long domainId; ///////////////////////////////////////////////////// @@ -53,7 +54,7 @@ public class EnableAccountCmd extends BaseCmd { public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -70,14 +71,14 @@ public class EnableAccountCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _entityMgr.findById(Account.class, getId()); if (account != null) { return account.getAccountId(); } - + account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); if (account != null) { return account.getAccountId(); diff --git a/api/src/com/cloud/api/commands/LockAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/LockAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java index 8c47dbc9d83..34e9e53b84d 100644 --- a/api/src/com/cloud/api/commands/LockAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java @@ -14,19 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Locks an account", responseObject=AccountResponse.class) +@APICommand(name = "lockAccount", description="Locks an account", responseObject=AccountResponse.class) public class LockAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LockAccountCmd.class.getName()); @@ -39,8 +40,8 @@ public class LockAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Locks the specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="Locks the specified account on this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="Locks the specified account on this domain.") private Long domainId; ///////////////////////////////////////////////////// @@ -58,12 +59,12 @@ public class LockAccountCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); diff --git a/api/src/com/cloud/api/commands/UpdateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/UpdateAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java index 8e3ef4364b3..f1340464d6b --- a/api/src/com/cloud/api/commands/UpdateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java @@ -14,49 +14,50 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import java.util.Collection; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Updates account information for the authenticated user", responseObject=AccountResponse.class) +@APICommand(name = "updateAccount", description="Updates account information for the authenticated user", responseObject=AccountResponse.class) public class UpdateAccountCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(UpdateAccountCmd.class.getName()); private static final String s_name = "updateaccountresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the current account name") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain where the account exists") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the domain where the account exists") private Long domainId; @Parameter(name=ApiConstants.NEW_NAME, type=CommandType.STRING, required=true, description="new name for the account") private String newName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the account's networks; empty string will update domainName with NULL value") private String networkDomain; - - @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") + + @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; ///////////////////////////////////////////////////// @@ -66,7 +67,7 @@ public class UpdateAccountCmd extends BaseCmd{ public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -78,19 +79,19 @@ public class UpdateAccountCmd extends BaseCmd{ public String getNewName() { return newName; } - + public String getNetworkDomain() { return networkDomain; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } ///////////////////////////////////////////////////// @@ -101,7 +102,7 @@ public class UpdateAccountCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _entityMgr.findById(Account.class, getId()); @@ -115,7 +116,7 @@ public class UpdateAccountCmd extends BaseCmd{ return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ Account result = _accountService.updateAccount(this); diff --git a/api/src/com/cloud/api/commands/CreateCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/CreateCounterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java index cc7d78cc31b..a119d0f44bf 100644 --- a/api/src/com/cloud/api/commands/CreateCounterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java @@ -15,23 +15,23 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.autoscale; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.CounterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CounterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.Counter; import com.cloud.user.Account; -@Implementation(description = "Adds metric counter", responseObject = CounterResponse.class) +@APICommand(name = "createCounter", description = "Adds metric counter", responseObject = CounterResponse.class) public class CreateCounterCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateCounterCmd.class.getName()); private static final String s_name = "counterresponse"; @@ -81,6 +81,7 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd { if (ctr != null) { this.setEntityId(ctr.getId()); + this.setEntityUuid(ctr.getUuid()); CounterResponse response = _responseGenerator.createCounterResponse(ctr); response.setResponseName(getCommandName()); this.setResponseObject(response); @@ -113,8 +114,5 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEntityTable() { - return "counter"; - } + } diff --git a/api/src/com/cloud/api/commands/DeleteCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteCounterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java index e9b92ef28ac..9304eeb7b93 100644 --- a/api/src/com/cloud/api/commands/DeleteCounterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java @@ -15,24 +15,24 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.autoscale; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceInUseException; import com.cloud.user.Account; -@Implementation(description = "Deletes a counter", responseObject = SuccessResponse.class) +@APICommand(name = "deleteCounter", description = "Deletes a counter", responseObject = SuccessResponse.class) public class DeleteCounterCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteCounterCmd.class.getName()); private static final String s_name = "deletecounterresponse"; @@ -41,8 +41,8 @@ public class DeleteCounterCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "counter") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the counter") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=CounterResponse.class, + required=true, description="the ID of the counter") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/AddClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/AddClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java index 0e10f23455c..28bf72ddba7 --- a/api/src/com/cloud/api/commands/AddClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java @@ -15,41 +15,39 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.exception.DiscoveryException; import com.cloud.exception.ResourceInUseException; import com.cloud.org.Cluster; import com.cloud.user.Account; -import com.cloud.utils.IdentityProxy; - -@Implementation(description="Adds a new cluster", responseObject=ClusterResponse.class) -public class AddClusterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); - - private static final String s_name = "addclusterresponse"; - - @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, required=true, description="the cluster name") - private String clusterName; - - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=false, description="the password for the host") - private String password; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, required=true, description="the Pod ID for the host") +@APICommand(name = "addCluster", description="Adds a new cluster", responseObject=ClusterResponse.class) +public class AddClusterCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); + + private static final String s_name = "addclusterresponse"; + + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, required=true, description="the cluster name") + private String clusterName; + + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=false, description="the password for the host") + private String password; + + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the URL") @@ -58,20 +56,19 @@ public class AddClusterCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=false, description="the username for the cluster") private String username; - @IdentityMapper(entityTableName="data_center") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID for the cluster") + private Long zoneId; - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the cluster") - private Long zoneId; - - @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator") - private String hypervisor; - - @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, required=true, description="type of the cluster: CloudManaged, ExternalManaged") - private String clusterType; - - @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") + @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator") + private String hypervisor; + + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, required=true, description="type of the cluster: CloudManaged, ExternalManaged") + private String clusterType; + + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name = ApiConstants.VSM_USERNAME, type = CommandType.STRING, required = false, description = "the username for the VSM associated with this cluster") private String vsmusername; @@ -80,7 +77,7 @@ public class AddClusterCmd extends BaseCmd { @Parameter(name = ApiConstants.VSM_IPADDRESS, type = CommandType.STRING, required = false, description = "the ipaddress of the VSM associated with this cluster") private String vsmipaddress; - + public String getVSMIpaddress() { return vsmipaddress; } @@ -92,90 +89,90 @@ public class AddClusterCmd extends BaseCmd { public String getVSMUsername() { return vsmusername; } - - public String getClusterName() { - return clusterName; - } - - public String getPassword() { - return password; - } - - public Long getPodId() { - return podId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public Long getZoneId() { - return zoneId; - } - - public String getHypervisor() { - return hypervisor; - } - - @Override - public String getCommandName() { - return s_name; - } - - public String getClusterType() { - return clusterType; - } - - public void setClusterType(String type) { - this.clusterType = type; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - public String getAllocationState() { - return allocationState; - } - - public void setAllocationState(String allocationState) { - this.allocationState = allocationState; - } - - @Override - public void execute(){ - try { - List result = _resourceService.discoverCluster(this); - ListResponse response = new ListResponse(); - List clusterResponses = new ArrayList(); - if (result != null && result.size() > 0) { - for (Cluster cluster : result) { - ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); - clusterResponses.add(clusterResponse); - } - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add cluster"); - } - - response.setResponses(clusterResponses); - response.setResponseName(getCommandName()); - - this.setResponseObject(response); - } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + + public String getClusterName() { + return clusterName; + } + + public String getPassword() { + return password; + } + + public Long getPodId() { + return podId; + } + + public String getUrl() { + return url; + } + + public String getUsername() { + return username; + } + + public Long getZoneId() { + return zoneId; + } + + public String getHypervisor() { + return hypervisor; + } + + @Override + public String getCommandName() { + return s_name; + } + + public String getClusterType() { + return clusterType; + } + + public void setClusterType(String type) { + this.clusterType = type; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + public String getAllocationState() { + return allocationState; + } + + public void setAllocationState(String allocationState) { + this.allocationState = allocationState; + } + + @Override + public void execute(){ + try { + List result = _resourceService.discoverCluster(this); + ListResponse response = new ListResponse(); + List clusterResponses = new ArrayList(); + if (result != null && result.size() > 0) { + for (Cluster cluster : result) { + ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); + clusterResponses.add(clusterResponse); + } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add cluster"); + } + + response.setResponses(clusterResponses); + response.setResponseName(getCommandName()); + + this.setResponseObject(response); + } catch (DiscoveryException ex) { + s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - for (IdentityProxy proxyObj : ex.getIdProxyList()) { - e.addProxyObject(proxyObj.getTableName(), proxyObj.getValue(), proxyObj.getidFieldName()); + for (String proxyObj : ex.getIdProxyList()) { + e.addProxyObject(proxyObj); } throw e; - } - } + } + } } diff --git a/api/src/com/cloud/api/commands/DeleteClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/DeleteClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java index 2e08b1c9100..f0b40cb6b03 --- a/api/src/com/cloud/api/commands/DeleteClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java @@ -14,21 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; - -@Implementation(description="Deletes a cluster.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteCluster", description="Deletes a cluster.", responseObject=SuccessResponse.class) public class DeleteClusterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteClusterCmd.class.getName()); @@ -38,11 +37,10 @@ public class DeleteClusterCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the cluster ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + required=true, description="the cluster ID") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +49,6 @@ public class DeleteClusterCmd extends BaseCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +57,12 @@ public class DeleteClusterCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _resourceService.deleteCluster(this); diff --git a/api/src/com/cloud/api/commands/ListClustersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/commands/ListClustersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java index e571bf52e8e..95ab0bff4f3 --- a/api/src/com/cloud/api/commands/ListClustersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java @@ -14,24 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.PodResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.org.Cluster; import com.cloud.utils.Pair; -@Implementation(description="Lists clusters.", responseObject=ClusterResponse.class) +@APICommand(name = "listClusters", description="Lists clusters.", responseObject=ClusterResponse.class) public class ListClustersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); @@ -41,19 +44,19 @@ public class ListClustersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists clusters by the cluster ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="lists clusters by the cluster ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="lists clusters by the cluster name") private String clusterName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists clusters by Pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="lists clusters by Pod ID") private Long podId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists clusters by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="lists clusters by Zone ID") private Long zoneId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="lists clusters by hypervisor type") @@ -61,13 +64,13 @@ public class ListClustersCmd extends BaseListCmd { @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="lists clusters by cluster type") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="lists clusters by allocation state") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the clusters") private Boolean showCapacities; @@ -90,19 +93,19 @@ public class ListClustersCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getHypervisorType() { - return hypervisorType; + return hypervisorType; } - + public String getClusterType() { - return clusterType; + return clusterType; } public String getAllocationState() { - return allocationState; + return allocationState; } - + public String getManagedstate() { return managedState; @@ -114,18 +117,18 @@ public class ListClustersCmd extends BaseListCmd { public Boolean getShowCapacities() { - return showCapacities; - } + return showCapacities; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _mgr.searchForClusters(this); diff --git a/api/src/com/cloud/api/commands/UpdateClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/UpdateClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java index 9a2d66865b4..03b43def3ca --- a/api/src/com/cloud/api/commands/UpdateClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java @@ -14,46 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.org.Cluster; import com.cloud.user.Account; -@Implementation(description="Updates an existing cluster", responseObject=ClusterResponse.class) +@APICommand(name = "updateCluster", description="Updates an existing cluster", responseObject=ClusterResponse.class) public class UpdateClusterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); private static final String s_name = "updateclusterresponse"; - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Cluster") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + required=true, description="the ID of the Cluster") private Long id; - + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name") private String clusterName; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="hypervisor type of the cluster") private String hypervisor; - + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="hypervisor type of the cluster") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + public String getClusterName() { return clusterName; } @@ -63,34 +62,34 @@ public class UpdateClusterCmd extends BaseCmd { } public String getHypervisor() { - return hypervisor; + return hypervisor; } - + @Override public String getCommandName() { - return s_name; + return s_name; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String type) { - this.clusterType = type; + this.clusterType = type; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; - } + this.allocationState = allocationState; + } public String getManagedstate() { return managedState; @@ -102,11 +101,11 @@ public class UpdateClusterCmd extends BaseCmd { @Override public void execute(){ - Cluster cluster = _resourceService.getCluster(getId()); + Cluster cluster = _resourceService.getCluster(getId()); if (cluster == null) { throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId()); } - + Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate()); if (result != null) { ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); diff --git a/api/src/com/cloud/api/commands/ListCfgsByCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/ListCfgsByCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java index 6e07ca9f519..16010fdb495 100644 --- a/api/src/com/cloud/api/commands/ListCfgsByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.configuration.Configuration; import com.cloud.utils.Pair; -@Implementation(description = "Lists all configurations.", responseObject = ConfigurationResponse.class) +@APICommand(name = "listConfigurations", description = "Lists all configurations.", responseObject = ConfigurationResponse.class) public class ListCfgsByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListCfgsByCmd.class.getName()); diff --git a/api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java index 9afd3eb2903..b69e9eab597 100644 --- a/api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java @@ -14,25 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.utils.Pair; -@Implementation(description="Lists all hypervisor capabilities.", responseObject=HypervisorCapabilitiesResponse.class, since="3.0.0") +@APICommand(name = "listHypervisorCapabilities", description="Lists all hypervisor capabilities.", responseObject=HypervisorCapabilitiesResponse.class, since="3.0.0") public class ListHypervisorCapabilitiesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListHypervisorCapabilitiesCmd.class.getName()); @@ -42,14 +41,13 @@ public class ListHypervisorCapabilitiesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="hypervisor_capabilities") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the hypervisor capability") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HypervisorCapabilitiesResponse.class, + description="ID of the hypervisor capability") private Long id; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/UpdateCfgCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/UpdateCfgCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java index f2d9fe92cac..79693e76f84 100644 --- a/api/src/com/cloud/api/commands/UpdateCfgCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ConfigurationResponse; import com.cloud.configuration.Configuration; import com.cloud.user.Account; -@Implementation(description="Updates a configuration.", responseObject=ConfigurationResponse.class) +@APICommand(name = "updateConfiguration", description="Updates a configuration.", responseObject=ConfigurationResponse.class) public class UpdateCfgCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateCfgCmd.class.getName()); private static final String s_name = "updateconfigurationresponse"; @@ -62,12 +62,12 @@ public class UpdateCfgCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Configuration cfg = _configService.updateConfiguration(this); diff --git a/api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java index 3173775891a..82880c1fbae 100644 --- a/api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.UUID; +package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.user.Account; - -@Implementation(description="Updates a hypervisor capabilities.", responseObject=ServiceOfferingResponse.class, since="3.0.0") +@APICommand(name = "updateHypervisorCapabilities", description="Updates a hypervisor capabilities.", responseObject=ServiceOfferingResponse.class, since="3.0.0") public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHypervisorCapabilitiesCmd.class.getName()); private static final String s_name = "updatehypervisorcapabilitiesresponse"; @@ -41,8 +37,8 @@ public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="hypervisor_capabilities") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the hypervisor capability") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HypervisorCapabilitiesResponse.class, + description="ID of the hypervisor capability") private Long id; @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="set true to enable security group for this hypervisor.") @@ -67,8 +63,6 @@ public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { return maxGuestsLimit; } - - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/CreateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/CreateDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java index 92ee7ecefe9..0e6ae32583b 100644 --- a/api/src/com/cloud/api/commands/CreateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java @@ -14,22 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a domain", responseObject=DomainResponse.class) +@APICommand(name = "createDomain", description="Creates a domain", responseObject=DomainResponse.class) public class CreateDomainCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateDomainCmd.class.getName()); @@ -42,8 +38,8 @@ public class CreateDomainCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="creates domain with this name") private String domainName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.PARENT_DOMAIN_ID, type=CommandType.LONG, description="assigns new domain a parent domain by domain ID of the parent. If no parent domain is specied, the ROOT domain is assumed.") + @Parameter(name=ApiConstants.PARENT_DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="assigns new domain a parent domain by domain ID of the parent. If no parent domain is specied, the ROOT domain is assumed.") private Long parentDomainId; @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for networks in the domain") @@ -63,7 +59,7 @@ public class CreateDomainCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; - } + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -73,12 +69,12 @@ public class CreateDomainCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Name: "+getDomainName()+((getParentDomainId()!=null)?", Parent DomainId :"+getParentDomainId():"")); diff --git a/api/src/com/cloud/api/commands/DeleteDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeleteDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index 3908256a192..7009e70ca32 100644 --- a/api/src/com/cloud/api/commands/DeleteDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a specified domain", responseObject=SuccessResponse.class) +@APICommand(name = "deleteDomain", description="Deletes a specified domain", responseObject=SuccessResponse.class) public class DeleteDomainCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteDomainCmd.class.getName()); private static final String s_name = "deletedomainresponse"; @@ -40,8 +36,8 @@ public class DeleteDomainCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of domain to delete") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="ID of domain to delete") private Long id; @Parameter(name=ApiConstants.CLEANUP, type=CommandType.BOOLEAN, description="true if all domain resources (child domains, accounts) have to be cleaned up, false otherwise") @@ -88,7 +84,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting domain: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ListDomainChildrenCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/ListDomainChildrenCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java index bb0dd7f7e83..4bc05d1c0f9 100644 --- a/api/src/com/cloud/api/commands/ListDomainChildrenCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java @@ -14,26 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.domain.Domain; import com.cloud.utils.Pair; -@Implementation(description="Lists all children domains belonging to a specified domain", responseObject=DomainResponse.class) +@APICommand(name = "listDomainChildren", description="Lists all children domains belonging to a specified domain", responseObject=DomainResponse.class) public class ListDomainChildrenCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainChildrenCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListDomainChildrenCmd.class.getName()); private static final String s_name = "listdomainchildrenresponse"; @@ -41,16 +40,16 @@ public class ListDomainChildrenCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list children domain by parent domain ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list children domain by parent domain ID.") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list children domains by name") private String domainName; - + @Parameter(name=ApiConstants.IS_RECURSIVE, type=CommandType.BOOLEAN, description="to return the entire tree, use the value \"true\". To return the first level children, use the value \"false\".") private Boolean recursive; - + @Parameter(name=ApiConstants.LIST_ALL, type=CommandType.BOOLEAN, description="If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; @@ -65,11 +64,11 @@ public class ListDomainChildrenCmd extends BaseListCmd { public String getDomainName() { return domainName; } - + public boolean listAll() { return listAll == null ? false : listAll; } - + public boolean isRecursive() { return recursive == null ? false : recursive; } @@ -82,7 +81,7 @@ public class ListDomainChildrenCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _domainService.searchForDomainChildren(this); diff --git a/api/src/com/cloud/api/commands/ListDomainsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/ListDomainsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java index 93d1570d6df..9b9e200abcd 100644 --- a/api/src/com/cloud/api/commands/ListDomainsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java @@ -14,35 +14,34 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.domain.Domain; import com.cloud.utils.Pair; -@Implementation(description="Lists domains and provides detailed information for listed domains", responseObject=DomainResponse.class) +@APICommand(name = "listDomains", description="Lists domains and provides detailed information for listed domains", responseObject=DomainResponse.class) public class ListDomainsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); + private static final String s_name = "listdomainsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List domain by domain ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="List domain by domain ID.") private Long id; @Parameter(name=ApiConstants.LEVEL, type=CommandType.INTEGER, description="List domains by domain level.") @@ -50,7 +49,7 @@ public class ListDomainsCmd extends BaseListCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List domain by domain name.") private String domainName; - + @Parameter(name=ApiConstants.LIST_ALL, type=CommandType.BOOLEAN, description="If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; @@ -69,7 +68,7 @@ public class ListDomainsCmd extends BaseListCmd { public String getDomainName() { return domainName; } - + public boolean listAll() { return listAll == null ? false : listAll; } diff --git a/api/src/com/cloud/api/commands/UpdateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java index 739ae87ca05..cc5926cace1 100644 --- a/api/src/com/cloud/api/commands/UpdateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java @@ -14,22 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates a domain with a new name", responseObject=DomainResponse.class) +@APICommand(name = "updateDomain", description="Updates a domain with a new name", responseObject=DomainResponse.class) public class UpdateDomainCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateDomainCmd.class.getName()); private static final String s_name = "updatedomainresponse"; @@ -38,13 +34,13 @@ public class UpdateDomainCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of domain to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="ID of domain to update") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates domain with this name") private String domainName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the domain's networks; empty string will update domainName with NULL value") private String networkDomain; @@ -59,7 +55,7 @@ public class UpdateDomainCmd extends BaseCmd { public String getDomainName() { return domainName; } - + public String getNetworkDomain() { return networkDomain; } @@ -72,12 +68,12 @@ public class UpdateDomainCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/AddHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/AddHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java index a4646a26904..0a0a98c1c45 --- a/api/src/com/cloud/api/commands/AddHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java @@ -14,37 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; -@Implementation(description="Adds a new host.", responseObject=HostResponse.class) +@APICommand(name = "addHost", description="Adds a new host.", responseObject=HostResponse.class) public class AddHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); private static final String s_name = "addhostresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="the cluster ID for the host") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="the cluster ID for the host") private Long clusterId; @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name for the host") @@ -53,8 +55,8 @@ public class AddHostCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the password for the host") private String password; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, required=true, type=CommandType.LONG, description="the Pod ID for the host") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the host URL") @@ -63,13 +65,13 @@ public class AddHostCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host") private String username; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the host") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID for the host") private Long zoneId; - + @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the host") private String hypervisor; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Host for allocation of new resources") private String allocationState; @@ -107,33 +109,33 @@ public class AddHostCmd extends BaseCmd { public Long getZoneId() { return zoneId; } - + public String getHypervisor() { - return hypervisor; + return hypervisor; } - + public List getHostTags() { return hostTags; } - + public String getAllocationState() { - return allocationState; - } - + return allocationState; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { @@ -151,7 +153,7 @@ public class AddHostCmd extends BaseCmd { response.setResponses(hostResponses); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); diff --git a/api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java index 04f84c148f2..579e286f884 100644 --- a/api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java @@ -14,28 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; -@Implementation(description="Adds secondary storage.", responseObject=HostResponse.class) +@APICommand(name = "addSecondaryStorage", description="Adds secondary storage.", responseObject=HostResponse.class) public class AddSecondaryStorageCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddSecondaryStorageCmd.class.getName()); private static final String s_name = "addsecondarystorageresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -43,8 +40,8 @@ public class AddSecondaryStorageCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL for the secondary storage") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the secondary storage") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID for the secondary storage") private Long zoneId; ///////////////////////////////////////////////////// @@ -65,14 +62,14 @@ public class AddSecondaryStorageCmd extends BaseCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/CancelMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java index def0c2d75cd..93dca9140f9 100644 --- a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java @@ -14,25 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Cancels host maintenance.", responseObject=HostResponse.class) +@APICommand(name = "cancelHostMaintenance", description="Cancels host maintenance.", responseObject=HostResponse.class) public class CancelMaintenanceCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CancelMaintenanceCmd.class.getName()); @@ -42,11 +41,10 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HostResponse.class, + required=true, description="the host ID") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +53,6 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,9 +61,9 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -88,17 +85,17 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "canceling maintenance for host: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ Host result = _resourceService.cancelMaintenance(this); diff --git a/api/src/com/cloud/api/commands/DeleteHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java index 60e61b99f30..5103f986e10 100644 --- a/api/src/com/cloud/api/commands/DeleteHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description = "Deletes a host.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteHost", description = "Deletes a host.", responseObject = SuccessResponse.class) public class DeleteHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteHostCmd.class.getName()); @@ -37,13 +37,13 @@ public class DeleteHostCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the host ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = HostResponse.class, + required = true, description = "the host ID") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Force delete the host. All HA enabled vms running on the host will be put to HA; HA disabled ones will be stopped") private Boolean forced; - + @Parameter(name = ApiConstants.FORCED_DESTROY_LOCAL_STORAGE, type = CommandType.BOOLEAN, description = "Force destroy local storage on this host. All VMs created on this local storage will be destroyed") private Boolean forceDestroyLocalStorage; @@ -58,7 +58,7 @@ public class DeleteHostCmd extends BaseCmd { public boolean isForced() { return (forced != null) ? forced : false; } - + public boolean isForceDestoryLocalStorage() { return (forceDestroyLocalStorage != null) ? forceDestroyLocalStorage : true; } @@ -87,4 +87,4 @@ public class DeleteHostCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete host"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListHostsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java old mode 100755 new mode 100644 similarity index 65% rename from api/src/com/cloud/api/commands/ListHostsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java index 87f13302a97..82f329f4b7e --- a/api/src/com/cloud/api/commands/ListHostsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java @@ -14,28 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.utils.Pair; -@Implementation(description="Lists hosts.", responseObject=HostResponse.class) +@APICommand(name = "listHosts", description="Lists hosts.", responseObject=HostResponse.class) public class ListHostsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListHostsCmd.class.getName()); @@ -45,19 +48,19 @@ public class ListHostsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="lists hosts existing in particular cluster") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + description="lists hosts existing in particular cluster") private Long clusterId; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the host") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + description="the id of the host") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the host") private String hostName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID for the host") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the host") @@ -66,23 +69,23 @@ public class ListHostsCmd extends BaseListCmd { @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the host type") private String type; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the host") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID for the host") private Long zoneId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") private Long virtualMachineId; - + @Parameter(name=ApiConstants.RESOURCE_STATE, type=CommandType.STRING, description="list hosts by resource state. Resource state represents current state determined by admin of host, valule can be one of [Enabled, Disabled, Unmanaged, PrepareForMaintenance, ErrorInMaintenance, Maintenance, Error]") - private String resourceState; - + private String resourceState; + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]" ) private List viewDetails; - + @Parameter(name=ApiConstants.HA_HOST, type=CommandType.BOOLEAN, description="if true, list only hosts dedicated to HA") private Boolean haHost; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -110,7 +113,7 @@ public class ListHostsCmd extends BaseListCmd { public String getType() { return type; } - + public Boolean getHaHost() { return haHost; } @@ -122,7 +125,7 @@ public class ListHostsCmd extends BaseListCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -142,9 +145,9 @@ public class ListHostsCmd extends BaseListCmd { } return dv; } - + public String getResourceState() { - return resourceState; + return resourceState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -154,39 +157,42 @@ public class ListHostsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } @Override public void execute(){ - List result = new ArrayList(); - List hostsWithCapacity = new ArrayList(); - - if(getVirtualMachineId() != null){ - Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), this.getStartIndex(), this.getPageSizeVal()); + ListResponse response = null; + if (getVirtualMachineId() == null) { + response = _queryService.searchForServers(this); + } else { + List result = new ArrayList(); + List hostsWithCapacity = new ArrayList(); + + Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), + this.getStartIndex(), this.getPageSizeVal()); result = hostsForMigration.first(); hostsWithCapacity = hostsForMigration.second(); - }else{ - result = _mgr.searchForServers(this); - } - ListResponse response = new ListResponse(); - List hostResponses = new ArrayList(); - for (Host host : result) { - HostResponse hostResponse = _responseGenerator.createHostResponse(host, getDetails()); - Boolean suitableForMigration = false; - if(hostsWithCapacity.contains(host)){ - suitableForMigration = true; + response = new ListResponse(); + List hostResponses = new ArrayList(); + for (Host host : result) { + HostResponse hostResponse = _responseGenerator.createHostResponse(host, getDetails()); + Boolean suitableForMigration = false; + if (hostsWithCapacity.contains(host)) { + suitableForMigration = true; + } + hostResponse.setSuitableForMigration(suitableForMigration); + hostResponse.setObjectName("host"); + hostResponses.add(hostResponse); } - hostResponse.setSuitableForMigration(suitableForMigration); - hostResponse.setObjectName("host"); - hostResponses.add(hostResponse); - } - response.setResponses(hostResponses); + response.setResponses(hostResponses); + } response.setResponseName(getCommandName()); this.setResponseObject(response); + } } diff --git a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java index 5a4abd0c244..385e2aef415 100644 --- a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Prepares a host for maintenance.", responseObject=HostResponse.class) +@APICommand(name = "prepareHostForMaintenance", description="Prepares a host for maintenance.", responseObject=HostResponse.class) public class PrepareForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PrepareForMaintenanceCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(PrepareForMaintenanceCmd.class.getName()); + private static final String s_name = "preparehostformaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the host ID") private Long id; ///////////////////////////////////////////////////// @@ -62,9 +61,9 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -86,17 +85,17 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "preparing host: " + getId() + " for maintenance"; } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ Host result = _resourceService.maintain(this); diff --git a/api/src/com/cloud/api/commands/ReconnectHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/ReconnectHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java index b74ac70f882..99e867bbebd --- a/api/src/com/cloud/api/commands/ReconnectHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java @@ -14,28 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; -import com.cloud.exception.AgentUnavailableException; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Reconnects a host.", responseObject=HostResponse.class) +@APICommand(name = "reconnectHost", description="Reconnects a host.", responseObject=HostResponse.class) public class ReconnectHostCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReconnectHostCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ReconnectHostCmd.class.getName()); private static final String s_name = "reconnecthostresponse"; @@ -43,8 +41,8 @@ public class ReconnectHostCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the host ID") private Long id; ///////////////////////////////////////////////////// @@ -63,9 +61,9 @@ public class ReconnectHostCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -87,15 +85,15 @@ public class ReconnectHostCmd extends BaseAsyncCmd { public String getEventDescription() { return "reconnecting host: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/UpdateHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/UpdateHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java index fae596f9015..9ab27178838 --- a/api/src/com/cloud/api/commands/UpdateHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.host.Host; import com.cloud.user.Account; -import com.cloud.utils.fsm.NoTransitionException; -@Implementation(description="Updates a host.", responseObject=HostResponse.class) +@APICommand(name = "updateHost", description="Updates a host.", responseObject=HostResponse.class) public class UpdateHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHostCmd.class.getName()); private static final String s_name = "updatehostresponse"; @@ -40,12 +39,12 @@ public class UpdateHostCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the host to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the ID of the host to update") private Long id; - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.LONG, description="the id of Os category to update the host with") + @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="the id of Os category to update the host with") private Long osCategoryId; @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Change resource state of host, valid values are [Enable, Disable]. Operation may failed if host in states not allowing Enable/Disable") @@ -53,7 +52,7 @@ public class UpdateHostCmd extends BaseCmd { @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="list of tags to be added to the host") private List hostTags; - + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="the new uri for the secondary storage: nfs://host/path") private String url; @@ -75,10 +74,10 @@ public class UpdateHostCmd extends BaseCmd { public List getHostTags() { return hostTags; - } - + } + public String getUrl() { - return url; + return url; } ///////////////////////////////////////////////////// @@ -103,13 +102,13 @@ public class UpdateHostCmd extends BaseCmd { public void execute(){ Host result; try { - result = _resourceService.updateHost(this); + result = _resourceService.updateHost(this); HostResponse hostResponse = _responseGenerator.createHostResponse(result); hostResponse.setResponseName(getCommandName()); this.setResponseObject(hostResponse); } catch (Exception e) { - s_logger.debug("Failed to update host:" + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); + s_logger.debug("Failed to update host:" + getId(), e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); } } } diff --git a/api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java index 426b51c0ed0..dd9e4559b9d 100644 --- a/api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description = "Update password of a host/pool on management server.", responseObject = SuccessResponse.class) +@APICommand(name = "updateHostPassword", description = "Update password of a host/pool on management server.", responseObject = SuccessResponse.class) public class UpdateHostPasswordCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHostPasswordCmd.class.getName()); @@ -37,18 +37,17 @@ public class UpdateHostPasswordCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - // TO DO - this is of no use currently. Probably need to remove it. - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID") private Long hostId; - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="the cluster ID") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="the cluster ID") private Long clusterId; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host/cluster") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the new password for the host/cluster") private String password; @@ -59,7 +58,7 @@ public class UpdateHostPasswordCmd extends BaseCmd { public Long getHostId() { return hostId; } - + public Long getClusterId() { return clusterId; } @@ -71,7 +70,7 @@ public class UpdateHostPasswordCmd extends BaseCmd { public String getUsername() { return username; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -92,4 +91,4 @@ public class UpdateHostPasswordCmd extends BaseCmd { _resourceService.updateHostPassword(this); this.setResponseObject(new SuccessResponse(getCommandName())); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/LDAPConfigCmd.java b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java similarity index 91% rename from api/src/com/cloud/api/commands/LDAPConfigCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java index d7ff5b5a8de..b71ba73405f 100644 --- a/api/src/com/cloud/api/commands/LDAPConfigCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java @@ -14,26 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.ldap; import javax.naming.NamingException; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.LDAPConfigResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Configure the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.0") +@APICommand(name = "ldapConfig", description="Configure the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.0") public class LDAPConfigCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LDAPConfigCmd.class.getName()); @@ -45,10 +45,10 @@ public class LDAPConfigCmd extends BaseCmd { @Parameter(name=ApiConstants.HOST_NAME, type=CommandType.STRING, required=true, description="Hostname or ip address of the ldap server eg: my.ldap.com") private String hostname; - + @Parameter(name=ApiConstants.PORT, type=CommandType.INTEGER, description="Specify the LDAP port if required, default is 389.") private Integer port=0; - + @Parameter(name=ApiConstants.USE_SSL, type=CommandType.BOOLEAN, description="Check Use SSL if the external LDAP server is configured for LDAP over SSL.") private Boolean useSSL; @@ -60,10 +60,10 @@ public class LDAPConfigCmd extends BaseCmd { @Parameter(name=ApiConstants.BIND_DN, type=CommandType.STRING, description="Specify the distinguished name of a user with the search permission on the directory.") private String bindDN; - + @Parameter(name=ApiConstants.BIND_PASSWORD, type=CommandType.STRING, description="Enter the password.") private String bindPassword; - + @Parameter(name=ApiConstants.TRUST_STORE, type=CommandType.STRING, description="Enter the path to trust certificates store.") private String trustStore; @@ -132,14 +132,14 @@ public class LDAPConfigCmd extends BaseCmd { catch (NamingException ne){ ne.printStackTrace(); } - + } @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/LDAPRemoveCmd.java b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/LDAPRemoveCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java index 43d9a0a399c..6bf5f4ff851 100644 --- a/api/src/com/cloud/api/commands/LDAPRemoveCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java @@ -14,28 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.ldap; -import javax.naming.NamingException; - +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.BaseResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.LDAPRemoveResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LDAPRemoveResponse; import com.cloud.user.Account; -@Implementation(description="Remove the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.1") +@APICommand(name = "ldapRemove", description="Remove the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.1") public class LDAPRemoveCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LDAPRemoveCmd.class.getName()); @@ -45,12 +35,12 @@ public class LDAPRemoveCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,10 +50,10 @@ public class LDAPRemoveCmd extends BaseCmd { public void execute(){ boolean result = _configService.removeLDAP(this); if (result){ - LDAPRemoveResponse lr = new LDAPRemoveResponse(); + LDAPRemoveResponse lr = new LDAPRemoveResponse(); lr.setObjectName("ldapremove"); lr.setResponseName(getCommandName()); - this.setResponseObject(lr); + this.setResponseObject(lr); } } @@ -71,7 +61,7 @@ public class LDAPRemoveCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java new file mode 100644 index 00000000000..3e1d74df405 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.network; + +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import com.cloud.server.ManagementService; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "addNetworkDevice", description="Adds a network device of one of the following types: ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer", responseObject = NetworkDeviceResponse.class) +public class AddNetworkDeviceCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddNetworkDeviceCmd.class); + private static final String s_name = "addnetworkdeviceresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") + private String type; + + @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") + private Map paramList; + + + public String getDeviceType() { + return type; + } + + public Map getParamList() { + return paramList; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + Host device = nwDeviceMgr.addNetworkDevice(this); + NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(device); + response.setObjectName("networkdevice"); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + // TODO Auto-generated method stub + return 0; + } + +} diff --git a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java index 1e4339766c0..6d4b962d4a1 100644 --- a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -35,7 +35,7 @@ import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "addNetworkServiceProvider", description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class, since="3.0.0") public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddNetworkServiceProviderCmd.class.getName()); @@ -44,30 +44,26 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID to add the provider to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID to add the provider to") private Long physicalNetworkId; - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.DEST_PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the destination Physical Network ID to bridge to") + @Parameter(name=ApiConstants.DEST_PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="the destination Physical Network ID to bridge to") private Long destinationPhysicalNetworkId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name for the physical network service provider") private String name; - + @Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider") private List enabledServices; - @Override - public String getEntityTable() { - return "physical_network_service_providers"; - } ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getPhysicalNetworkId() { return physicalNetworkId; } @@ -92,12 +88,12 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network ServiceProvider Id: "+getEntityId()); @@ -116,21 +112,22 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { PhysicalNetworkServiceProvider result = _networkService.addProviderToPhysicalNetwork(getPhysicalNetworkId(), getProviderName(), getDestinationPhysicalNetworkId(), getEnabledServices()); if (result != null) { setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_SERVICE_PROVIDER_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network ServiceProvider: " + getEntityId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index 748f96eb263..b97f85ec1ba 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.Collection; @@ -23,15 +23,12 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Service; @@ -39,7 +36,7 @@ import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; -@Implementation(description="Creates a network offering.", responseObject=NetworkOfferingResponse.class, since="3.0.0") +@APICommand(name = "createNetworkOffering", description="Creates a network offering.", responseObject=NetworkOfferingResponse.class, since="3.0.0") public class CreateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateNetworkOfferingCmd.class.getName()); private static final String _name = "createnetworkofferingresponse"; @@ -50,55 +47,55 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering. Supported type in current release is GUEST only") private String traffictype; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the network offering.", length=4096) - private String tags; - + private String tags; + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="true if network offering supports vlans") - private Boolean specifyVlan; - + private Boolean specifyVlan; + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Optional") - private String availability; - + private String availability; + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed") private Integer networkRate; - + @Parameter(name=ApiConstants.CONSERVE_MODE, type=CommandType.BOOLEAN, description="true if the network offering is IP conserve mode enabled") private Boolean conserveMode; - - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, description="the service offering ID used by virtual router provider") + + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the service offering ID used by virtual router provider") private Long serviceOfferingId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="guest type of the network offering: Shared or Isolated") private String guestIptype; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the network offering") private List supportedServices; - + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; @Parameter(name = ApiConstants.SERVICE_CAPABILITY_LIST, type = CommandType.MAP, description = "desired service capabilities as part of network offering") private Map serviceCapabilitystList; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to false if not specified") private Boolean specifyIpRanges; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } @@ -110,7 +107,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getTraffictype() { return traffictype; } - + public Boolean getSpecifyVlan() { return specifyVlan == null ? false : specifyVlan; } @@ -118,7 +115,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getAvailability() { return availability == null ? Availability.Optional.toString() : availability; } - + public Integer getNetworkRate() { return networkRate; } @@ -130,18 +127,18 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public Long getServiceOfferingId() { return serviceOfferingId; } - - public List getSupportedServices() { - return supportedServices; - } - public String getGuestIpType() { + public List getSupportedServices() { + return supportedServices; + } + + public String getGuestIpType() { return guestIptype; } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges == null ? false : specifyIpRanges; - } + + public Boolean getSpecifyIpRanges() { + return specifyIpRanges == null ? false : specifyIpRanges; + } public Boolean getConserveMode() { if (conserveMode == null) { @@ -170,7 +167,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { serviceProviderMap.put(service, providerList); } } - + return serviceProviderMap; } @@ -199,7 +196,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { if (svc.equalsIgnoreCase(service.getName())) { capabilityMap.put(capability, capabilityValue); } else { - //throw new InvalidParameterValueException("Service is not equal ") + //throw new InvalidParameterValueException("Service is not equal ") } } } @@ -214,7 +211,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java index 537b9bec56d..f56ae7dbf50 100644 --- a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -35,7 +36,7 @@ import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "createPhysicalNetwork", description="Creates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePhysicalNetworkCmd.class.getName()); @@ -44,9 +45,9 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the physical network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType= ZoneResponse.class, + required=true, description="the Zone ID for the physical network") private Long zoneId; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") @@ -55,33 +56,29 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") private String speed; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a physical network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="domain ID of the account owning a physical network") private Long domainId; - + @Parameter(name=ApiConstants.BROADCAST_DOMAIN_RANGE, type=CommandType.STRING, description="the broadcast domain range for the physical network[Pod or Zone]. In Acton release it can be Zone only in Advance zone, and Pod in Basic") private String broadcastDomainRange; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") private List tags; - + @Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]") private List isolationMethods; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the physical network") private String networkName; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public List getTags() { return tags; } - @Override - public String getEntityTable() { - return "physical_network"; - } public Long getZoneId() { return zoneId; @@ -102,25 +99,25 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public List getIsolationMethods() { return isolationMethods; } - + public String getNetworkSpeed() { return speed; } - + public String getNetworkName() { - return networkName; - } - - @Override + return networkName; + } + + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_CREATE; @@ -140,7 +137,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating Physical Network. Id: "+getEntityId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -163,11 +160,12 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { PhysicalNetwork result = _networkService.createPhysicalNetwork(getZoneId(),getVlan(),getNetworkSpeed(), getIsolationMethods(),getBroadcastDomainRange(),getDomainId(), getTags(), getNetworkName()); if (result != null) { setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java new file mode 100644 index 00000000000..ccd92e19d67 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java @@ -0,0 +1,127 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; + +@APICommand(name = "createStorageNetworkIpRange", description="Creates a Storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(CreateStorageNetworkIpRangeCmd.class); + + private static final String s_name = "createstoragenetworkiprangeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="UUID of pod where the ip range belongs to") + private Long podId; + + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address") + private String startIp; + + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") + private String endIp; + + @Parameter(name = ApiConstants.VLAN, type = CommandType.INTEGER, description = "Optional. The vlan the ip range sits on, default to Null when it is not specificed which means you network is not on any Vlan. This is mainly for Vmware as other hypervisors can directly reterive bridge from pyhsical network traffic type table") + private Integer vlan; + + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for storage network") + private String netmask; + + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for storage network") + private String gateway; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getEndIp() { + return endIp; + } + + public Long getPodId() { + return podId; + } + + public String getStartIp() { + return startIp; + } + + public Integer getVlan() { + return vlan; + } + + public String getNetmask() { + return netmask; + } + + public String getGateWay() { + return gateway; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating storage ip range from " + getStartIp() + " to " + getEndIp() + " with vlan " + getVlan(); + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + StorageNetworkIpRange result = _storageNetworkService.createIpRange(this); + StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Create storage network IP range failed", e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java new file mode 100644 index 00000000000..09451242daf --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java @@ -0,0 +1,89 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.network; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.server.ManagementService; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "deleteNetworkDevice", description="Deletes network device.", responseObject=SuccessResponse.class) +public class DeleteNetworkDeviceCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(DeleteNetworkDeviceCmd.class); + private static final String s_name = "deletenetworkdeviceresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = HostResponse.class, + required=true, description = "Id of network device to delete") + private Long id; + + public Long getId() { + return id; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + boolean result = nwDeviceMgr.deleteNetworkDevice(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network device:" + getId()); + } + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + // TODO Auto-generated method stub + return 0; + } + +} diff --git a/api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java index 9d60e34e201..c13088f6123 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes a network offering.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteNetworkOffering", description="Deletes a network offering.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteNetworkOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteNetworkOfferingCmd.class.getName()); private static final String s_name = "deletenetworkofferingresponse"; @@ -36,11 +36,10 @@ public class DeleteNetworkOfferingCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + required=true, description="the ID of the network offering") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -58,12 +57,12 @@ public class DeleteNetworkOfferingCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteNetworkOffering(this); diff --git a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java index 815657bd9dc..bc744399a33 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteNetworkServiceProvider", description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetworkServiceProviderCmd.class.getName()); @@ -41,11 +41,10 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network_service_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network service provider") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProviderResponse.class, + required=true, description="the ID of the network service provider") + private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -55,7 +54,6 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +62,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -86,7 +84,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } + } } @@ -100,7 +98,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Physical network ServiceProvider: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java index c2814386a36..5f86efa9ad8 100644 --- a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Physical Network.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deletePhysicalNetwork", description="Deletes a Physical Network.", responseObject=SuccessResponse.class, since="3.0.0") public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePhysicalNetworkCmd.class.getName()); @@ -40,11 +36,10 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Physical network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="the ID of the Physical network") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,7 +48,6 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -62,7 +56,7 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -85,12 +79,12 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Physical network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_DELETE; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java old mode 100755 new mode 100644 similarity index 50% rename from api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java index cfecd5e1f84..1873fc7d6ef --- a/api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,20 +29,20 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Deletes a storage network IP Range.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteStorageNetworkIpRange", description="Deletes a storage network IP Range.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteStorageNetworkIpRangeCmd.class); - - private static final String s_name = "deletestoragenetworkiprangeresponse"; - + public static final Logger s_logger = Logger.getLogger(DeleteStorageNetworkIpRangeCmd.class); + + private static final String s_name = "deletestoragenetworkiprangeresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the uuid of the storage network ip range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + required=true, description="the uuid of the storage network ip range") private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,38 +50,38 @@ public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { public Long getId() { return id; } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_DELETE; - } - @Override - public String getEventDescription() { - return "Deleting storage ip range " + getId(); - } + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_DELETE; + } - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - _storageNetworkService.deleteIpRange(this); + @Override + public String getEventDescription() { + return "Deleting storage ip range " + getId(); + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + _storageNetworkService.deleteIpRange(this); SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Failed to delete storage network ip range " + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } + } catch (Exception e) { + s_logger.warn("Failed to delete storage network ip range " + getId(), e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java new file mode 100644 index 00000000000..742ff1f74af --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java @@ -0,0 +1,99 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import com.cloud.server.ManagementService; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "listNetworkDevice", description="List network devices", responseObject = NetworkDeviceResponse.class) +public class ListNetworkDeviceCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListNetworkDeviceCmd.class); + private static final String s_name = "listnetworkdevice"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") + private String type; + + @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") + private Map paramList; + + public String getDeviceType() { + return type; + } + + public Map getParamList() { + return paramList; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + List devices = nwDeviceMgr.listNetworkDevice(this); + List nwdeviceResponses = new ArrayList(); + ListResponse listResponse = new ListResponse(); + for (Host d : devices) { + NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(d); + response.setObjectName("networkdevice"); + response.setResponseName(getCommandName()); + nwdeviceResponses.add(response); + } + + listResponse.setResponses(nwdeviceResponses); + listResponse.setResponseName(getCommandName()); + this.setResponseObject(listResponse); + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + +} diff --git a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java index 97bfd77f463..06a0518af20 100644 --- a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java @@ -14,26 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; import com.cloud.utils.Pair; - -@Implementation(description="Lists network serviceproviders for a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "listNetworkServiceProviders", description="Lists network serviceproviders for a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") public class ListNetworkServiceProvidersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkServiceProvidersCmd.class.getName()); private static final String _name = "listnetworkserviceprovidersresponse"; @@ -41,21 +40,21 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list providers by name") private String name; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list providers by state") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } @@ -65,14 +64,14 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { } public String getName() { - return name; - } + return name; + } - public String getState() { - return state; - } + public String getState() { + return state; + } - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override @@ -84,7 +83,7 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Pair, Integer> serviceProviders = _networkService.listNetworkServiceProviders(getPhysicalNetworkId(), diff --git a/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java index ed2968fffe9..a301ac004ea 100644 --- a/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; import com.cloud.utils.Pair; -@Implementation(description="Lists physical networks", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "listPhysicalNetworks", description="Lists physical networks", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class ListPhysicalNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListPhysicalNetworksCmd.class.getName()); @@ -43,22 +43,22 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list physical network by id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="list physical network by id") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the physical network") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID for the physical network") private Long zoneId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="search by name") private String networkName; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -66,11 +66,11 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getNetworkName() { - return networkName; + return networkName; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -79,12 +79,12 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Pair, Integer> result = _networkService.searchPhysicalNetworks(getId(),getZoneId(), diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java new file mode 100644 index 00000000000..8fcaf4958b1 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java @@ -0,0 +1,105 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; + +@APICommand(name = "listStorageNetworkIpRange", description="List a storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +public class ListStorageNetworkIpRangeCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListStorageNetworkIpRangeCmd.class); + + String s_name = "liststoragenetworkiprangeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + description="optional parameter. Storaget network IP range uuid, if specicied, using it to search the range.") + private Long rangeId; + + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="optional parameter. Pod uuid, if specicied and range uuid is absent, using it to search the range.") + private Long podId; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="optional parameter. Zone uuid, if specicied and both pod uuid and range uuid are absent, using it to search the range.") + private Long zoneId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getRangeId() { + return rangeId; + } + + public Long getPodId() { + return podId; + } + + public Long getZoneId() { + return zoneId; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + List results = _storageNetworkService.listIpRange(this); + ListResponse response = new ListResponse(); + List resList = new ArrayList(results.size()); + for (StorageNetworkIpRange r : results) { + StorageNetworkIpRangeResponse resp = _responseGenerator.createStorageNetworkIpRangeResponse(r); + resList.add(resp); + } + response.setResponses(resList); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java index ef949da8fa3..f7407a108e0 100644 --- a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java @@ -14,44 +14,44 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ServiceResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; import com.cloud.network.Network.Service; import com.cloud.user.Account; -@Implementation(description="Lists all network services provided by CloudStack or for the given Provider.", responseObject=ServiceResponse.class, since="3.0.0") +@APICommand(name = "listSupportedNetworkServices", description="Lists all network services provided by CloudStack or for the given Provider.", responseObject=ServiceResponse.class, since="3.0.0") public class ListSupportedNetworkServicesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); private static final String _name = "listsupportednetworkservicesresponse"; - + @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING, description="network service provider name") private String providerName; - + @Parameter(name=ApiConstants.SERVICE, type=CommandType.STRING, description="network service name to list providers and capabilities of") private String serviceName; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setProviderName(String providerName) { this.providerName = providerName; @@ -78,10 +78,10 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - List services; + List services; if(getServiceName() != null){ Network.Service service = null; if(serviceName != null){ @@ -96,14 +96,14 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { }else{ services = _networkService.listNetworkServices(getProviderName()); } - + ListResponse response = new ListResponse(); List servicesResponses = new ArrayList(); for (Network.Service service : services) { - //skip gateway service - if (service == Service.Gateway) { - continue; - } + //skip gateway service + if (service == Service.Gateway) { + continue; + } ServiceResponse serviceResponse = _responseGenerator.createNetworkServiceResponse(service); servicesResponses.add(serviceResponse); } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java index c30361944cb..dc2f3099206 --- a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; -@Implementation(description="Updates a network offering.", responseObject=NetworkOfferingResponse.class) +@APICommand(name = "updateNetworkOffering", description="Updates a network offering.", responseObject=NetworkOfferingResponse.class) public class UpdateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkOfferingCmd.class.getName()); private static final String _name = "updatenetworkofferingresponse"; @@ -36,21 +32,21 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the network offering") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=NetworkOfferingResponse.class, + description="the id of the network offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering." + - " Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering") + " Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering") private String availability; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the network offering, integer") private Integer sortKey; @@ -60,15 +56,15 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } @@ -80,9 +76,9 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { public String getState() { return state; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } ///////////////////////////////////////////////////// @@ -92,7 +88,7 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java index bd52f35c48b..b770ea26c12 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java @@ -14,26 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; -@Implementation(description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "updateNetworkServiceProvider", description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class, since="3.0.0") public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkServiceProviderCmd.class.getName()); @@ -44,14 +43,14 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled/Shutdown the physical network service provider") private String state; - - @IdentityMapper(entityTableName="physical_network_service_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="network service provider id") - private Long id; + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProviderResponse.class, + required=true, description="network service provider id") + private Long id; @Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider") private List enabledServices; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -59,14 +58,14 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getState() { return state; } - + private Long getId() { return id; - } - + } + public List getEnabledServices() { return enabledServices; - } + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -75,12 +74,12 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetworkServiceProvider result = _networkService.updateNetworkServiceProvider(getId(), getState(), getEnabledServices()); @@ -102,7 +101,7 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating physical network ServiceProvider: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java index a6abc039042..d9a3e044c73 100644 --- a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; -@Implementation(description="Updates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "updatePhysicalNetwork", description="Updates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdatePhysicalNetworkCmd.class.getName()); @@ -40,8 +39,8 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="physical network id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="physical network id") private Long id; @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") @@ -49,17 +48,17 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") private List tags; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled") private String state; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") private String vlan; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public List getTags() { return tags; } @@ -67,7 +66,7 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getNetworkSpeed() { return speed; } - + public String getState() { return state; } @@ -79,7 +78,7 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getVlan() { return vlan; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -88,12 +87,12 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetwork result = _networkService.updatePhysicalNetwork(getId(),getNetworkSpeed(), getTags(), getVlan(), getState()); @@ -106,12 +105,12 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating Physical network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java old mode 100755 new mode 100644 similarity index 53% rename from api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java index 7e0b05bad23..d6d0b92e4b7 --- a/api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,30 +29,30 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Update a Storage network IP range, only allowed when no IPs in this range have been allocated.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +@APICommand(name = "updateStorageNetworkIpRange", description="Update a Storage network IP range, only allowed when no IPs in this range have been allocated.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateStorageNetworkIpRangeCmd.class); - private static final String s_name = "updatestoragenetworkiprangeresponse"; - + public static final Logger s_logger = Logger.getLogger(UpdateStorageNetworkIpRangeCmd.class); + private static final String s_name = "updatestoragenetworkiprangeresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="UUID of storage network ip range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + required=true, description="UUID of storage network ip range") private Long id; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address") private String startIp; @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") private String endIp; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.INTEGER, description="Optional. the vlan the ip range sits on") private Integer vlan; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask for storage network") private String netmask; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -72,49 +67,49 @@ public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { public Integer getVlan() { return vlan; } - + public String getNetmask() { - return netmask; + return netmask; } public Long getId() { - return id; + return id; } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_UPDATE; - } - @Override - public String getEventDescription() { - return "Update storage ip range " + getId() + " [StartIp=" + getStartIp() + ", EndIp=" + getEndIp() + ", vlan=" + getVlan() + ", netmask=" + getNetmask() + ']'; - } + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_UPDATE; + } - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this); - StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Update storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + @Override + public String getEventDescription() { + return "Update storage ip range " + getId() + " [StartIp=" + getStartIp() + ", EndIp=" + getEndIp() + ", vlan=" + getVlan() + ", netmask=" + getNetmask() + ']'; + } - } + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this); + StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Update storage network IP range failed", e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } - @Override - public String getCommandName() { - return s_name; - } + } - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } } diff --git a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java index 779221ee416..08101dc4137 --- a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Creates a disk offering.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "createDiskOffering", description="Creates a disk offering.", responseObject=DiskOfferingResponse.class) public class CreateDiskOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateDiskOfferingCmd.class.getName()); @@ -53,10 +53,10 @@ public class CreateDiskOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.CUSTOMIZED, type=CommandType.BOOLEAN, description="whether disk offering is custom or not") private Boolean customized; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public offerings") - private Long domainId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public offerings") + private Long domainId; @Parameter(name=ApiConstants.STORAGE_TYPE, type=CommandType.STRING, description="the storage type of the disk offering. Values are local and shared.") private String storageType = ServiceOffering.StorageType.shared.toString(); @@ -82,11 +82,11 @@ public class CreateDiskOfferingCmd extends BaseCmd { } public Boolean isCustomized(){ - return customized; + return customized; } - + public Long getDomainId(){ - return domainId; + return domainId; } public String getStorageType() { @@ -101,12 +101,12 @@ public class CreateDiskOfferingCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ DiskOffering offering = _configService.createDiskOffering(this); @@ -116,6 +116,6 @@ public class CreateDiskOfferingCmd extends BaseCmd { this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create disk offering"); - } + } } } diff --git a/api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index 1aa43e67dc3..f93c2a88ce2 100644 --- a/api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Creates a service offering.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "createServiceOffering", description="Creates a service offering.", responseObject=ServiceOfferingResponse.class) public class CreateServiceOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); - private static final String _name = "createserviceofferingresponse"; + public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); + private static final String _name = "createserviceofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -64,10 +64,10 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for this service offering.") private String tags; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public offerings") - private Long domainId; - + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public offerings") + private Long domainId; + @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.STRING, description="the host tag for this service offering.") private String hostTag; @@ -76,10 +76,10 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"domainrouter\", \"consoleproxy\" and \"secondarystoragevm\".") private String systemVmType; - + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed. Supported only for non-System offering and system offerings having \"domainrouter\" systemvmtype") private Integer networkRate; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -109,7 +109,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { } public Boolean GetLimitCpuUse() { - return limitCpuUse; + return limitCpuUse; } public String getStorageType() { @@ -121,8 +121,8 @@ public class CreateServiceOfferingCmd extends BaseCmd { } public Long getDomainId() { - return domainId; - } + return domainId; + } public String getHostTag() { return hostTag; @@ -135,7 +135,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { public String getSystemVmType() { return systemVmType; } - + public Integer getNetworkRate() { return networkRate; } @@ -144,11 +144,11 @@ public class CreateServiceOfferingCmd extends BaseCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { - return _name; - } - + return _name; + } + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java index 12fcac7ac1a..85e034f6191 100644 --- a/api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Updates a disk offering.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteDiskOffering", description="Updates a disk offering.", responseObject=SuccessResponse.class) public class DeleteDiskOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteDiskOfferingCmd.class.getName()); private static final String s_name = "deletediskofferingresponse"; @@ -36,8 +36,8 @@ public class DeleteDiskOfferingCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="ID of the disk offering") private Long id; @@ -57,12 +57,12 @@ public class DeleteDiskOfferingCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteDiskOffering(this); diff --git a/api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java index b76ad0cc5ea..d1ea4de0504 100644 --- a/api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes a service offering.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteServiceOffering", description="Deletes a service offering.", responseObject=SuccessResponse.class) public class DeleteServiceOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteServiceOfferingCmd.class.getName()); private static final String s_name = "deleteserviceofferingresponse"; @@ -36,8 +33,8 @@ public class DeleteServiceOfferingCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the service offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering") private Long id; @@ -58,12 +55,12 @@ public class DeleteServiceOfferingCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteServiceOffering(this); diff --git a/api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java index 882f90e090b..8db731d3b31 --- a/api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java @@ -14,20 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.offering.DiskOffering; import com.cloud.user.Account; -@Implementation(description="Updates a disk offering.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "updateDiskOffering", description="Updates a disk offering.", responseObject=DiskOfferingResponse.class) public class UpdateDiskOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(UpdateDiskOfferingCmd.class.getName()); private static final String s_name = "updatediskofferingresponse"; @@ -39,13 +38,13 @@ public class UpdateDiskOfferingCmd extends BaseCmd{ @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="updates alternate display text of the disk offering with this value", length=4096) private String displayText; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="ID of the disk offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates name of the disk offering with this value") private String diskOfferingName; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the disk offering, integer") private Integer sortKey; @@ -64,26 +63,26 @@ public class UpdateDiskOfferingCmd extends BaseCmd{ public String getDiskOfferingName() { return diskOfferingName; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ DiskOffering result = _configService.updateDiskOffering(this); diff --git a/api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java index b7c2cf69fbd..38220b90673 --- a/api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Updates a service offering.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "updateServiceOffering", description="Updates a service offering.", responseObject=ServiceOfferingResponse.class) public class UpdateServiceOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateServiceOfferingCmd.class.getName()); private static final String s_name = "updateserviceofferingresponse"; @@ -36,16 +32,16 @@ public class UpdateServiceOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the service offering to be updated") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering to be updated") private Long id; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the service offering to be updated") private String displayText; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the service offering to be updated") private String serviceOfferingName; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the service offering, integer") private Integer sortKey; ///////////////////////////////////////////////////// @@ -65,19 +61,19 @@ public class UpdateServiceOfferingCmd extends BaseCmd { } public Integer getSortKey() { - return sortKey; + return sortKey; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -85,8 +81,8 @@ public class UpdateServiceOfferingCmd extends BaseCmd { @Override public void execute(){ - //Note - //Once an offering is created, we cannot update the domainId field (keeping consistent with zones logic) + //Note + //Once an offering is created, we cannot update the domainId field (keeping consistent with zones logic) ServiceOffering result = _configService.updateServiceOffering(this); if (result != null){ ServiceOfferingResponse response = _responseGenerator.createServiceOfferingResponse(result); diff --git a/api/src/com/cloud/api/commands/CreatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java old mode 100755 new mode 100644 similarity index 85% rename from api/src/com/cloud/api/commands/CreatePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java index 99a161bb211..331968b00db --- a/api/src/com/cloud/api/commands/CreatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java @@ -14,21 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PodResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.dc.Pod; import com.cloud.user.Account; -@Implementation(description="Creates a new Pod.", responseObject=PodResponse.class) +@APICommand(name = "createPod", description="Creates a new Pod.", responseObject=PodResponse.class) public class CreatePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreatePodCmd.class.getName()); @@ -39,23 +37,23 @@ public class CreatePodCmd extends BaseCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the Pod") private String podName; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID in which the Pod will be created ") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID in which the Pod will be created") private Long zoneId; @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the starting IP address for the Pod") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address for the Pod") private String endIp; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for the Pod") private String netmask; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for the Pod") private String gateway; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Pod for allocation of new resources") private String allocationState; @@ -88,9 +86,9 @@ public class CreatePodCmd extends BaseCmd { } public String getAllocationState() { - return allocationState; + return allocationState; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -99,7 +97,7 @@ public class CreatePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeletePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeletePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java index ed951242ab3..8c64a8dad33 100644 --- a/api/src/com/cloud/api/commands/DeletePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.SuccessResponse; + import com.cloud.user.Account; -@Implementation(description="Deletes a Pod.", responseObject=SuccessResponse.class) +@APICommand(name = "deletePod", description="Deletes a Pod.", responseObject=SuccessResponse.class) public class DeletePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeletePodCmd.class.getName()); @@ -37,11 +38,10 @@ public class DeletePodCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Pod") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the ID of the Pod") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -57,7 +57,7 @@ public class DeletePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/ListPodsByCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/ListPodsByCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java index 37b8e29d6f6..a64ecdde9b5 --- a/api/src/com/cloud/api/commands/ListPodsByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PodResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.dc.Pod; import com.cloud.utils.Pair; -@Implementation(description="Lists all Pods.", responseObject=PodResponse.class) +@APICommand(name = "listPods", description="Lists all Pods.", responseObject=PodResponse.class) public class ListPodsByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListPodsByCmd.class.getName()); @@ -41,23 +42,23 @@ public class ListPodsByCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list Pods by ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + description="list Pods by ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list Pods by name") private String podName; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list Pods by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="list Pods by Zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="list pods by allocation state") - private String allocationState; - + private String allocationState; + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the pods") private Boolean showCapacities; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -73,15 +74,15 @@ public class ListPodsByCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getAllocationState() { - return allocationState; - } + return allocationState; + } public Boolean getShowCapacities() { - return showCapacities; - } - + return showCapacities; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/UpdatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java old mode 100755 new mode 100644 similarity index 85% rename from api/src/com/cloud/api/commands/UpdatePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java index f575c7cf1dd..ca5e03953a3 --- a/api/src/com/cloud/api/commands/UpdatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PodResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; + import com.cloud.dc.Pod; import com.cloud.user.Account; -@Implementation(description="Updates a Pod.", responseObject=PodResponse.class) +@APICommand(name = "updatePod", description="Updates a Pod.", responseObject=PodResponse.class) public class UpdatePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdatePodCmd.class.getName()); @@ -38,8 +35,8 @@ public class UpdatePodCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Pod") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the ID of the Pod") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the Pod") @@ -47,16 +44,16 @@ public class UpdatePodCmd extends BaseCmd { @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the starting IP address for the Pod") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address for the Pod") private String endIp; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the Pod") private String netmask; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway for the Pod") private String gateway; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; @@ -89,7 +86,7 @@ public class UpdatePodCmd extends BaseCmd { } public String getAllocationState() { - return allocationState; + return allocationState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -99,12 +96,12 @@ public class UpdatePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Pod result = _configService.editPod(this); diff --git a/api/src/com/cloud/api/commands/ListAlertsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/ListAlertsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java index 1f6c7b3e413..db7a20b02a3 100644 --- a/api/src/com/cloud/api/commands/ListAlertsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; import com.cloud.alert.Alert; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AlertResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AlertResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.utils.Pair; -@Implementation(description = "Lists all alerts.", responseObject = AlertResponse.class) +@APICommand(name = "listAlerts", description = "Lists all alerts.", responseObject = AlertResponse.class) public class ListAlertsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListAlertsCmd.class.getName()); @@ -42,8 +41,8 @@ public class ListAlertsCmd extends BaseListCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="alert") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the alert") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AlertResponse.class, + description = "the ID of the alert") private Long id; @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "list by alert type") @@ -77,7 +76,7 @@ public class ListAlertsCmd extends BaseListCmd { List alertResponseList = new ArrayList(); for (Alert alert : result.first()) { AlertResponse alertResponse = new AlertResponse(); - alertResponse.setId(alert.getId()); + alertResponse.setId(alert.getUuid()); alertResponse.setAlertType(alert.getType()); alertResponse.setDescription(alert.getSubject()); alertResponse.setLastSent(alert.getLastSent()); diff --git a/api/src/com/cloud/api/commands/ListCapacityCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java old mode 100755 new mode 100644 similarity index 59% rename from api/src/com/cloud/api/commands/ListCapacityCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java index 5e3ca5e1511..ce20a3e27de --- a/api/src/com/cloud/api/commands/ListCapacityCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java @@ -14,24 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; import java.text.DecimalFormat; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.capacity.Capacity; import com.cloud.exception.InvalidParameterValueException; -@Implementation(description="Lists all the system wide capacities.", responseObject=CapacityResponse.class) +@APICommand(name = "listCapacity", description="Lists all the system wide capacities.", responseObject=CapacityResponse.class) public class ListCapacityCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListCapacityCmd.class.getName()); @@ -42,36 +44,36 @@ public class ListCapacityCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists capacity by the Zone ID") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="lists capacity by the Zone ID") private Long zoneId; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists capacity by the Pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="lists capacity by the Pod ID") private Long podId; - - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, since="3.0.0", description="lists capacity by the Cluster ID") + + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + since="3.0.0", description="lists capacity by the Cluster ID") private Long clusterId; @Parameter(name=ApiConstants.FETCH_LATEST, type=CommandType.BOOLEAN, since="3.0.0", description="recalculate capacities and fetch the latest") private Boolean fetchLatest; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.INTEGER, description="lists capacity by type" + - "* CAPACITY_TYPE_MEMORY = 0" + - "* CAPACITY_TYPE_CPU = 1" + - "* CAPACITY_TYPE_STORAGE = 2" + - "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + - "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + - "* CAPACITY_TYPE_PRIVATE_IP = 5" + - "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + - "* CAPACITY_TYPE_VLAN = 7" + - "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + - "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") + "* CAPACITY_TYPE_MEMORY = 0" + + "* CAPACITY_TYPE_CPU = 1" + + "* CAPACITY_TYPE_STORAGE = 2" + + "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + + "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + + "* CAPACITY_TYPE_PRIVATE_IP = 5" + + "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + + "* CAPACITY_TYPE_VLAN = 7" + + "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + + "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") private Integer type; - + @Parameter(name=ApiConstants.SORT_BY, type=CommandType.STRING, since="3.0.0", description="Sort the results. Available values: Usage") private String sortBy; @@ -82,23 +84,23 @@ public class ListCapacityCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getPodId() { return podId; } public Long getClusterId() { - return clusterId; - } + return clusterId; + } - public Boolean getFetchLatest() { - return fetchLatest; - } + public Boolean getFetchLatest() { + return fetchLatest; + } - public Integer getType() { + public Integer getType() { return type; } - + public String getSortBy() { if (sortBy != null) { if (sortBy.equalsIgnoreCase("usage")) { @@ -107,7 +109,7 @@ public class ListCapacityCmd extends BaseListCmd { throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage"); } } - + return null; } @@ -119,7 +121,7 @@ public class ListCapacityCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = null; @@ -128,7 +130,7 @@ public class ListCapacityCmd extends BaseListCmd { } else { result = _mgr.listCapacities(this); } - + ListResponse response = new ListResponse(); List capacityResponses = _responseGenerator.createCapacityResponse(result, s_percentFormat); response.setResponses(capacityResponses); diff --git a/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java index d6eca303910..0e559189904 100644 --- a/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.CustomCertificateResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.CustomCertificateResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(responseObject=CustomCertificateResponse.class, description="Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.") +@APICommand(name = "uploadCustomCertificate", responseObject=CustomCertificateResponse.class, description="Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.") public class UploadCustomCertificateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UploadCustomCertificateCmd.class.getName()); @@ -36,10 +32,10 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.CERTIFICATE,type=CommandType.STRING,required=true,description="The certificate to be uploaded.", length=65535) private String certificate; - + @Parameter(name=ApiConstants.ID,type=CommandType.INTEGER,required=false,description="An integer providing the location in a chain that the certificate will hold. Usually, this can be left empty. When creating a chain, the top level certificate should have an ID of 1, with each step in the chain incrementing by one. Example, CA with id = 1, Intermediate CA with id = 2, Site certificate with ID = 3") private Integer index; - + @Parameter(name=ApiConstants.NAME,type=CommandType.STRING,required=false,description="A name / alias for the certificate.") private String alias; @@ -48,25 +44,25 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.DOMAIN_SUFFIX,type=CommandType.STRING,required=true,description="DNS domain suffix that the certificate is granted for.") private String domainSuffix; - + public String getCertificate() { return certificate; } - + public String getPrivateKey() { - return privateKey; + return privateKey; } - + public String getDomainSuffix() { - return domainSuffix; + return domainSuffix; } - + public Integer getCertIndex() { - return index; + return index; } - + public String getAlias() { - return alias; + return alias; } @Override @@ -78,21 +74,21 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Uploading custom certificate to the db, and applying it to all the cpvms in the system"); } - + @Override public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "certificate"; + return "certificate"; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ String result = _mgr.uploadCertificate(this); diff --git a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java index 967994051bb..be6be26a36f 100644 --- a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java @@ -14,19 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.element.VirtualRouterElementService; import com.cloud.async.AsyncJob; @@ -37,11 +36,11 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=VirtualRouterProviderResponse.class, description="Configures a virtual router element.") +@APICommand(name = "configureVirtualRouterElement", responseObject=VirtualRouterProviderResponse.class, description="Configures a virtual router element.") public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ConfigureVirtualRouterElementCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ConfigureVirtualRouterElementCmd.class.getName()); private static final String s_name = "configurevirtualrouterelementresponse"; - + @PlugService private VirtualRouterElementService _service; @@ -49,14 +48,13 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "virtual_router_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the virtual router provider") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VirtualRouterProviderResponse.class, + required=true, description="the ID of the virtual router provider") private Long id; - @IdentityMapper(entityTableName = "physical_network_service_providers") @Parameter(name=ApiConstants.ENABLED, type=CommandType.BOOLEAN, required=true, description="Enabled/Disabled the service provider") private Boolean enabled; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -85,11 +83,11 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "boolean"; + return "boolean"; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -104,15 +102,15 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { public String getEventDescription() { return "configuring virtual router provider: " + id; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.None; + return AsyncJob.Type.None; } - + public Long getInstanceId() { return id; } - + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Virtual router element: " + id); diff --git a/api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java index 2c44663a382..f6a7b744ca3 100644 --- a/api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProviderResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.VirtualRouterProvider; @@ -35,11 +30,11 @@ import com.cloud.network.element.VirtualRouterElementService; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=VirtualRouterProviderResponse.class, description="Create a virtual router element.") +@APICommand(name = "createVirtualRouterElement", responseObject=VirtualRouterProviderResponse.class, description="Create a virtual router element.") public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVirtualRouterElementCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVirtualRouterElementCmd.class.getName()); private static final String s_name = "createvirtualrouterelementresponse"; - + @PlugService private VirtualRouterElementService _service; @@ -47,8 +42,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.NETWORK_SERVICE_PROVIDER_ID, type=CommandType.LONG, required=true, description="the network service provider ID of the virtual router element") - @IdentityMapper(entityTableName="physical_network_service_providers") + @Parameter(name=ApiConstants.NETWORK_SERVICE_PROVIDER_ID, type=CommandType.UUID, entityType = ProviderResponse.class, required=true, description="the network service provider ID of the virtual router element") private Long nspId; ///////////////////////////////////////////////////// @@ -59,15 +53,12 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { this.nspId = nspId; } - @Override - public String getEntityTable() { - return "virtual_router_providers"; - } + public Long getNspId() { return nspId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -76,12 +67,12 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Virtual router element Id: "+getEntityId()); @@ -100,16 +91,17 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { VirtualRouterProvider result = _service.addElement(getNspId(), VirtualRouterProviderType.VirtualRouter); if (result != null) { setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_SERVICE_PROVIDER_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network ServiceProvider Virtual Router: " + getEntityId(); diff --git a/api/src/com/cloud/api/commands/DestroyRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/DestroyRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java index f5286d6a6ad..1157aaa7b93 100644 --- a/api/src/com/cloud/api/commands/DestroyRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +33,7 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Destroys a router.", responseObject = DomainRouterResponse.class) +@APICommand(name = "destroyRouter", description = "Destroys a router.", responseObject = DomainRouterResponse.class) public class DestroyRouterCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroyRouterCmd.class.getName()); private static final String s_name = "destroyrouterresponse"; @@ -43,8 +42,8 @@ public class DestroyRouterCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the router") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainRouterResponse.class, + required = true, description = "the ID of the router") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListRoutersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java similarity index 58% rename from api/src/com/cloud/api/commands/ListRoutersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java index 8bf9ba818dd..198d8766b21 100644 --- a/api/src/com/cloud/api/commands/ListRoutersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.async.AsyncJob; -import com.cloud.network.router.VirtualRouter; -import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="List routers.", responseObject=DomainRouterResponse.class) +import com.cloud.async.AsyncJob; + +@APICommand(name = "listRouters", description="List routers.", responseObject=DomainRouterResponse.class) public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListRoutersCmd.class.getName()); @@ -42,36 +43,36 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID of the router") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID of the router") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the disk router") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the router") private String routerName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the router") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the Pod ID of the router") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the router") private String state; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the router") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID of the router") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType=NetworkResponse.class, + description="list by network id") private Long networkId; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="List networks by VPC") private Long vpcId; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="if true is passed for this parameter, list only VPC routers") private Boolean forVpc; @@ -86,7 +87,7 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public Long getId() { return id; } - + public String getRouterName() { return routerName; } @@ -102,15 +103,15 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public Long getZoneId() { return zoneId; } - + public Long getNetworkId() { return networkId; } - + public Long getVpcId() { return vpcId; } - + public Boolean getForVpc() { return forVpc; } @@ -123,23 +124,15 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; + return AsyncJob.Type.DomainRouter; } @Override public void execute(){ - Pair, Integer> result = _mgr.searchForRouters(this); - ListResponse response = new ListResponse(); - List routerResponses = new ArrayList(); - for (VirtualRouter router : result.first()) { - DomainRouterResponse routerResponse = _responseGenerator.createDomainRouterResponse(router); - routerResponse.setObjectName("router"); - routerResponses.add(routerResponse); - } - - response.setResponses(routerResponses, result.second()); + ListResponse response = _queryService.searchForRouters(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java index 937a01e2d80..0a93ea5ab3e 100644 --- a/api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.response.ProviderResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -37,32 +38,32 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.element.VirtualRouterElementService; -@Implementation(description="Lists all available virtual router elements.", responseObject=VirtualRouterProviderResponse.class) +@APICommand(name = "listVirtualRouterElements", description="Lists all available virtual router elements.", responseObject=VirtualRouterProviderResponse.class) public class ListVirtualRouterElementsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); private static final String _name = "listvirtualrouterelementsresponse"; @PlugService private VirtualRouterElementService _service; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "virtual_router_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list virtual router elements by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VirtualRouterProviderResponse.class, + description="list virtual router elements by id") private Long id; - - @IdentityMapper(entityTableName = "physical_network_service_providers") - @Parameter(name=ApiConstants.NSP_ID, type=CommandType.LONG, description="list virtual router elements by network service provider id") + + @Parameter(name=ApiConstants.NSP_ID, type=CommandType.UUID, entityType = ProviderResponse.class, + description="list virtual router elements by network service provider id") private Long nspId; - + @Parameter(name=ApiConstants.ENABLED, type=CommandType.BOOLEAN, description="list network offerings by enabled state") private Boolean enabled; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setId(Long id) { this.id = id; } @@ -91,7 +92,7 @@ public class ListVirtualRouterElementsCmd extends BaseListCmd { public String getCommandName() { return _name; } - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { List providers = _service.searchForVirtualRouterElement(this); diff --git a/api/src/com/cloud/api/commands/RebootRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/RebootRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java index 58577b7ffb9..9c50d2ffb0f 100644 --- a/api/src/com/cloud/api/commands/RebootRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,17 +30,17 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Starts a router.", responseObject=DomainRouterResponse.class) +@APICommand(name = "rebootRouter", description="Starts a router.", responseObject=DomainRouterResponse.class) public class RebootRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName()); private static final String s_name = "rebootrouterresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DomainRouterResponse.class, + required=true, description="the ID of the router") private Long id; ///////////////////////////////////////////////////// @@ -64,7 +59,7 @@ public class RebootRouterCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -84,16 +79,16 @@ public class RebootRouterCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting router: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; - } - - public Long getInstanceId() { - return getId(); + return AsyncJob.Type.DomainRouter; } - + public Long getInstanceId() { + return getId(); + } + + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Router Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StartRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/StartRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java index 233e34f0a05..f1f3f681829 100644 --- a/api/src/com/cloud/api/commands/StartRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,10 +30,9 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; - -@Implementation(responseObject=DomainRouterResponse.class, description="Starts a router.") +@APICommand(name = "startRouter", responseObject=DomainRouterResponse.class, description="Starts a router.") public class StartRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName()); private static final String s_name = "startrouterresponse"; @@ -46,8 +40,8 @@ public class StartRouterCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainRouterResponse.class, + required=true, description="the ID of the router") private Long id; ///////////////////////////////////////////////////// @@ -66,11 +60,11 @@ public class StartRouterCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "router"; + return "router"; } - + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -90,15 +84,15 @@ public class StartRouterCmd extends BaseAsyncCmd { public String getEventDescription() { return "starting router: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; + return AsyncJob.Type.DomainRouter; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Router Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StopRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/StopRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java index 84a8bc50d52..2d1b609aa5d 100644 --- a/api/src/com/cloud/api/commands/StopRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +33,7 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Stops a router.", responseObject = DomainRouterResponse.class) +@APICommand(name = "stopRouter", description = "Stops a router.", responseObject = DomainRouterResponse.class) public class StopRouterCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopRouterCmd.class.getName()); private static final String s_name = "stoprouterresponse"; @@ -43,8 +42,8 @@ public class StopRouterCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the router") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainRouterResponse.class, + required = true, description = "the ID of the router") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM. The caller knows the VM is stopped.") diff --git a/api/src/com/cloud/api/commands/UpgradeRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/UpgradeRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java index a5168761d8f..e2b020e09f9 100644 --- a/api/src/com/cloud/api/commands/UpgradeRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java @@ -14,35 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; -@Implementation(description="Upgrades domain router to a new service offering", responseObject=DomainRouterResponse.class) +@APICommand(name = "changeServiceForRouter", description="Upgrades domain router to a new service offering", responseObject=DomainRouterResponse.class) public class UpgradeRouterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); - private static final String s_name = "changeserviceforrouterresponse"; + public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); + private static final String s_name = "changeserviceforrouterresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DomainRouterResponse.class, + required=true, description="The ID of the router") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the service offering ID to apply to the domain router") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType = DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the domain router") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -61,11 +58,11 @@ public class UpgradeRouterCmd extends BaseCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -75,7 +72,7 @@ public class UpgradeRouterCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualRouter router = _routerService.upgradeRouter(this); diff --git a/api/src/com/cloud/api/commands/AddS3Cmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java similarity index 85% rename from api/src/com/cloud/api/commands/AddS3Cmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java index e046ccc0160..13f066a6e57 100644 --- a/api/src/com/cloud/api/commands/AddS3Cmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java @@ -16,26 +16,26 @@ * specific language governing permissions and limitations * under the License. */ -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; -import static com.cloud.api.ApiConstants.S3_ACCESS_KEY; -import static com.cloud.api.ApiConstants.S3_CONNECTION_TIMEOUT; -import static com.cloud.api.ApiConstants.S3_END_POINT; -import static com.cloud.api.ApiConstants.S3_HTTPS_FLAG; -import static com.cloud.api.ApiConstants.S3_MAX_ERROR_RETRY; -import static com.cloud.api.ApiConstants.S3_SECRET_KEY; -import static com.cloud.api.ApiConstants.S3_SOCKET_TIMEOUT; -import static com.cloud.api.ApiConstants.S3_BUCKET_NAME; -import static com.cloud.api.BaseCmd.CommandType.INTEGER; -import static com.cloud.api.BaseCmd.CommandType.STRING; -import static com.cloud.api.BaseCmd.CommandType.BOOLEAN; +import static org.apache.cloudstack.api.ApiConstants.S3_ACCESS_KEY; +import static org.apache.cloudstack.api.ApiConstants.S3_CONNECTION_TIMEOUT; +import static org.apache.cloudstack.api.ApiConstants.S3_END_POINT; +import static org.apache.cloudstack.api.ApiConstants.S3_HTTPS_FLAG; +import static org.apache.cloudstack.api.ApiConstants.S3_MAX_ERROR_RETRY; +import static org.apache.cloudstack.api.ApiConstants.S3_SECRET_KEY; +import static org.apache.cloudstack.api.ApiConstants.S3_SOCKET_TIMEOUT; +import static org.apache.cloudstack.api.ApiConstants.S3_BUCKET_NAME; +import static org.apache.cloudstack.api.BaseCmd.CommandType.INTEGER; +import static org.apache.cloudstack.api.BaseCmd.CommandType.STRING; +import static org.apache.cloudstack.api.BaseCmd.CommandType.BOOLEAN; import static com.cloud.user.Account.ACCOUNT_ID_SYSTEM; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.S3Response; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.S3Response; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InsufficientCapacityException; @@ -44,7 +44,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.storage.S3; -@Implementation(description = "Adds S3", responseObject = S3Response.class, since = "4.0.0") +@APICommand(name = "addS3", description = "Adds S3", responseObject = S3Response.class, since = "4.0.0") public final class AddS3Cmd extends BaseCmd { private static String COMMAND_NAME = "adds3response"; diff --git a/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java index c4d97aeb985..24ef48be222 100644 --- a/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -33,18 +32,18 @@ import com.cloud.storage.StoragePool; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Cancels maintenance for primary storage", responseObject=StoragePoolResponse.class) +@APICommand(name = "cancelStorageMaintenance", description="Cancels maintenance for primary storage", responseObject=StoragePoolResponse.class) public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CancelPrimaryStorageMaintenanceCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(CancelPrimaryStorageMaintenanceCmd.class.getName()); + private static final String s_name = "cancelprimarystoragemaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the primary storage ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="the primary storage ID") private Long id; @@ -65,16 +64,16 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "primarystorage"; + return "primarystorage"; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } - + @Override public Long getInstanceId() { return getId(); @@ -99,7 +98,7 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "canceling maintenance for primary storage pool: " + getId(); } - + @Override public void execute() throws ResourceUnavailableException{ StoragePool result = _storageService.cancelPrimaryStorageForMaintenance(this); diff --git a/api/src/com/cloud/api/commands/CreateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/CreateStoragePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java index 8926ea71b13..78a142ac449 100644 --- a/api/src/com/cloud/api/commands/CreateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java @@ -14,27 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.net.UnknownHostException; import java.util.Map; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.storage.StoragePool; import com.cloud.user.Account; @SuppressWarnings("rawtypes") -@Implementation(description="Creates a storage pool.", responseObject=StoragePoolResponse.class) +@APICommand(name = "createStoragePool", description="Creates a storage pool.", responseObject=StoragePoolResponse.class) public class CreateStoragePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateStoragePoolCmd.class.getName()); @@ -44,8 +43,8 @@ public class CreateStoragePoolCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, required=true, description="the cluster ID for the storage pool") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + required=true, description="the cluster ID for the storage pool") private Long clusterId; @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the storage pool") @@ -54,8 +53,8 @@ public class CreateStoragePoolCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name for the storage pool") private String storagePoolName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, required=true, description="the Pod ID for the storage pool") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + required=true, description="the Pod ID for the storage pool") private Long podId; @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the storage pool") @@ -64,8 +63,8 @@ public class CreateStoragePoolCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of the storage pool") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the storage pool") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the Zone ID for the storage pool") private Long zoneId; ///////////////////////////////////////////////////// @@ -103,12 +102,12 @@ public class CreateStoragePoolCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeletePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeletePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java index ba2f73fdb24..1510f7822f7 100644 --- a/api/src/com/cloud/api/commands/DeletePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java @@ -14,22 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolStatus; import com.cloud.user.Account; -@Implementation(description = "Deletes a storage pool.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteStoragePool", description = "Deletes a storage pool.", responseObject = SuccessResponse.class) public class DeletePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeletePoolCmd.class.getName()); private static final String s_name = "deletestoragepoolresponse"; @@ -38,10 +35,10 @@ public class DeletePoolCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "Storage pool id") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = StoragePoolResponse.class, + required = true, description = "Storage pool id") private Long id; - + @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force destroy storage pool " + "(force expunge volumes in Destroyed state as a part of pool removal)") private Boolean forced; @@ -53,7 +50,7 @@ public class DeletePoolCmd extends BaseCmd { public Long getId() { return id; } - + public boolean isForced() { return (forced != null) ? forced : false; } diff --git a/api/src/com/cloud/api/commands/ListS3sCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/ListS3sCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java index d536cfcf80a..d0f6d722179 100644 --- a/api/src/com/cloud/api/commands/ListS3sCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java @@ -16,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.util.ArrayList; import java.util.List; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.S3Response; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.S3Response; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.NetworkRuleConflictException; @@ -33,7 +33,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.storage.S3; -@Implementation(description = "Lists S3s", responseObject = S3Response.class, since = "4.0.0") +@APICommand(name = "listS3s", description = "Lists S3s", responseObject = S3Response.class, since = "4.0.0") public final class ListS3sCmd extends BaseListCmd { private static final String COMMAND_NAME = "lists3sresponse"; diff --git a/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java similarity index 64% rename from api/src/com/cloud/api/commands/ListStoragePoolsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java index 7199b0b25ec..9c5c584b7cb 100644 --- a/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java @@ -14,25 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.storage.StoragePool; import com.cloud.utils.Pair; -@Implementation(description="Lists storage pools.", responseObject=StoragePoolResponse.class) +@APICommand(name = "listStoragePools", description="Lists storage pools.", responseObject=StoragePoolResponse.class) public class ListStoragePoolsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListStoragePoolsCmd.class.getName()); @@ -42,8 +45,8 @@ public class ListStoragePoolsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="list storage pools belongig to the specific cluster") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + description="list storage pools belongig to the specific cluster") private Long clusterId; @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the IP address for the storage pool") @@ -55,16 +58,16 @@ public class ListStoragePoolsCmd extends BaseListCmd { @Parameter(name=ApiConstants.PATH, type=CommandType.STRING, description="the storage pool path") private String path; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID for the storage pool") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID for the storage pool") private Long podId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the storage pool") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID for the storage pool") private Long zoneId; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the storage pool") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + description="the ID of the storage pool") private Long id; ///////////////////////////////////////////////////// @@ -94,9 +97,9 @@ public class ListStoragePoolsCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getId() { - return id; + return id; } ///////////////////////////////////////////////////// @@ -107,23 +110,14 @@ public class ListStoragePoolsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } @Override public void execute(){ - Pair, Integer> pools = _mgr.searchForStoragePools(this); - ListResponse response = new ListResponse(); - List poolResponses = new ArrayList(); - for (StoragePool pool : pools.first()) { - StoragePoolResponse poolResponse = _responseGenerator.createStoragePoolResponse(pool); - poolResponse.setObjectName("storagepool"); - poolResponses.add(poolResponse); - } - - response.setResponses(poolResponses, pools.second()); + ListResponse response = _queryService.searchForStoragePools(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java index 31e181e56d7..6a4175516cc 100644 --- a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -34,17 +33,17 @@ import com.cloud.storage.StoragePool; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Puts storage pool into maintenance state", responseObject=StoragePoolResponse.class) +@APICommand(name = "enableStorageMaintenance", description="Puts storage pool into maintenance state", responseObject=StoragePoolResponse.class) public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PreparePrimaryStorageForMaintenanceCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(PreparePrimaryStorageForMaintenanceCmd.class.getName()); private static final String s_name = "prepareprimarystorageformaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Primary storage ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="Primary storage ID") private Long id; ///////////////////////////////////////////////////// @@ -63,16 +62,16 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "primarystorage"; + return "primarystorage"; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } - + @Override public Long getInstanceId() { return getId(); diff --git a/api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index 52b5a047dbf..806df561397 100644 --- a/api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.storage.StoragePool; import com.cloud.user.Account; -@Implementation(description="Updates a storage pool.", responseObject=StoragePoolResponse.class, since="3.0.0") +@APICommand(name = "updateStoragePool", description="Updates a storage pool.", responseObject=StoragePoolResponse.class, since="3.0.0") public class UpdateStoragePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateStoragePoolCmd.class.getName()); @@ -40,13 +36,13 @@ public class UpdateStoragePoolCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the Id of the storage pool") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="the Id of the storage pool") private Long id; @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma-separated list of tags for the storage pool") private List tags; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -68,12 +64,12 @@ public class UpdateStoragePoolCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ StoragePool result = _storageService.updateStoragePool(this); diff --git a/api/src/com/cloud/api/commands/AddSwiftCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/AddSwiftCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java index 0be4d5ffde8..23a00ca04dc 100644 --- a/api/src/com/cloud/api/commands/AddSwiftCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java @@ -14,26 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.swift; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.SwiftResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.exception.DiscoveryException; import com.cloud.storage.Swift; import com.cloud.user.Account; -@Implementation(description = "Adds Swift.", responseObject = HostResponse.class, since="3.0.0") +@APICommand(name = "addSwift", description = "Adds Swift.", responseObject = HostResponse.class, since="3.0.0") public class AddSwiftCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddSwiftCmd.class.getName()); private static final String s_name = "addswiftresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -76,14 +73,14 @@ public class AddSwiftCmd extends BaseCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/ListSwiftsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/ListSwiftsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java index 587ceee10b9..d7c151188e7 100644 --- a/api/src/com/cloud/api/commands/ListSwiftsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java @@ -14,28 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.swift; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SwiftResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.storage.Swift; import com.cloud.user.Account; -@Implementation(description = "List Swift.", responseObject = HostResponse.class, since="3.0.0") +@APICommand(name = "listSwifts", description = "List Swift.", responseObject = HostResponse.class, since="3.0.0") public class ListSwiftsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSwiftsCmd.class.getName()); private static final String s_name = "listswiftsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -54,14 +54,14 @@ public class ListSwiftsCmd extends BaseListCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ List result = _resourceService.listSwifts(this); diff --git a/api/src/com/cloud/api/commands/DestroySystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DestroySystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java index 44626e1ad46..ad0f09cba46 100644 --- a/api/src/com/cloud/api/commands/DestroySystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java @@ -14,34 +14,29 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Destroyes a system virtual machine.") +@APICommand(name = "destroySystemVm", responseObject=SystemVmResponse.class, description="Destroyes a system virtual machine.") public class DestroySystemVmCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroySystemVmCmd.class.getName()); - + private static final String s_name = "destroysystemvmresponse"; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; - + public Long getId() { return id; } @@ -50,9 +45,9 @@ public class DestroySystemVmCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "systemvm"; + return "systemvm"; } @Override @@ -75,22 +70,22 @@ public class DestroySystemVmCmd extends BaseAsyncCmd { return EventTypes.EVENT_SSVM_DESTROY; } } - + @Override public String getEventDescription() { return "destroying system vm: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.SystemVm; } - + @Override public Long getInstanceId() { return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ListSystemVMsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListSystemVMsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java index 44391971469..27e2ee40daf 100644 --- a/api/src/com/cloud/api/commands/ListSystemVMsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java @@ -14,25 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.utils.Pair; import com.cloud.vm.VirtualMachine; -@Implementation(description="List system virtual machines.", responseObject=SystemVmResponse.class) +@APICommand(name = "listSystemVms", description="List system virtual machines.", responseObject=SystemVmResponse.class) public class ListSystemVMsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSystemVMsCmd.class.getName()); @@ -42,19 +45,19 @@ public class ListSystemVMsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID of the system VM") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID of the system VM") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the system VM") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + description="the ID of the system VM") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the system VM") private String systemVmName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the system VM") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the Pod ID of the system VM") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the system VM") @@ -63,12 +66,12 @@ public class ListSystemVMsCmd extends BaseListCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"consoleproxy\" and \"secondarystoragevm\".") private String systemVmType; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the system VM") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID of the system VM") private Long zoneId; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to", since="3.0.1") + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="the storage ID where vm's volumes belong to", since="3.0.1") private Long storageId; ///////////////////////////////////////////////////// @@ -102,7 +105,7 @@ public class ListSystemVMsCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getStorageId() { return storageId; } @@ -115,11 +118,11 @@ public class ListSystemVMsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + @Override public void execute(){ Pair, Integer> systemVMs = _mgr.searchForSystemVm(this); diff --git a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/MigrateSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java index 13bb208ad6d..dd844acd17f 100644 --- a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +38,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Attempts Migration of a system virtual machine to the host specified.", responseObject=SystemVmInstanceResponse.class) +@APICommand(name = "migrateSystemVm", description="Attempts Migration of a system virtual machine to the host specified.", responseObject=SystemVmInstanceResponse.class) public class MigrateSystemVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MigrateSystemVMCmd.class.getName()); @@ -47,12 +48,12 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, required=true, description="destination Host ID to migrate VM to") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + required=true, description="destination Host ID to migrate VM to") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; @@ -77,7 +78,7 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -97,38 +98,38 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - + Host destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); } try{ - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); - //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer - VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - if (migratedVm != null) { - // return the generic system VM instance response - SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer + VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + if (migratedVm != null) { + // return the generic system VM instance response + SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/RebootSystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java index 03a95756a82..49e895b22fe 100644 --- a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Reboots a system VM.", responseObject=SystemVmResponse.class) +@APICommand(name = "rebootSystemVm", description="Reboots a system VM.", responseObject=SystemVmResponse.class) public class RebootSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootSystemVmCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(RebootSystemVmCmd.class.getName()); private static final String s_name = "rebootsystemvmresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -57,7 +56,7 @@ public class RebootSystemVmCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; @@ -88,15 +87,15 @@ public class RebootSystemVmCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting system vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StartSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/StartSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java index 9cd78f3c1fd..70ab5f38720 100644 --- a/api/src/com/cloud/api/commands/StartSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Starts a system virtual machine.") +@APICommand(name = "startSystemVm", responseObject=SystemVmResponse.class, description="Starts a system virtual machine.") public class StartSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartSystemVMCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StartSystemVMCmd.class.getName()); private static final String s_name = "startsystemvmresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -62,9 +61,9 @@ public class StartSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "systemvm"; + return "systemvm"; } @Override @@ -92,15 +91,15 @@ public class StartSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "starting system vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StopSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/StopSystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java index 91e48c8a35d..af2bd3ad64f 100644 --- a/api/src/com/cloud/api/commands/StopSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,9 +29,9 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Stops a system VM.", responseObject=SystemVmResponse.class) +@APICommand(name = "stopSystemVm", description="Stops a system VM.", responseObject=SystemVmResponse.class) public class StopSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); private static final String s_name = "stopsystemvmresponse"; @@ -44,13 +39,13 @@ public class StopSystemVmCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; @Parameter(name=ApiConstants.FORCED, type=CommandType.BOOLEAN, required=false, description="Force stop the VM. The caller knows the VM is stopped.") private Boolean forced; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -93,17 +88,17 @@ public class StopSystemVmCmd extends BaseAsyncCmd { public String getEventDescription() { return "stopping system vm: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + public boolean isForced() { return (forced != null) ? forced : false; } diff --git a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java index a36844aeb3b..290c3603f1f 100644 --- a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java @@ -14,24 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Changes the service offering for a system vm (console proxy or secondary storage). " + +@APICommand(name = "changeServiceForSystemVm", responseObject=SystemVmResponse.class, description="Changes the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.") public class UpgradeSystemVMCmd extends BaseCmd { @@ -42,13 +40,12 @@ public class UpgradeSystemVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system vm") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system vm") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, - description="the service offering ID to apply to the system vm") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the system vm") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -71,7 +68,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -81,16 +78,16 @@ public class UpgradeSystemVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } - + VirtualMachine result = _mgr.upgradeSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); diff --git a/api/src/com/cloud/api/commands/PrepareTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java similarity index 64% rename from api/src/com/cloud/api/commands/PrepareTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java index cb2cd2fa3f4..74f33915551 100644 --- a/api/src/com/cloud/api/commands/PrepareTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.template; import java.util.List; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(responseObject=TemplateResponse.class, description="load template into primary storage") +@APICommand(name = "prepareTemplate", responseObject=TemplateResponse.class, description="load template into primary storage") public class PrepareTemplateCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(PrepareTemplateCmd.class.getName()); @@ -40,23 +40,23 @@ public class PrepareTemplateCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, required=true, type=CommandType.LONG, description="zone ID of the template to be prepared in primary storage(s).") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="zone ID of the template to be prepared in primary storage(s).") private Long zoneId; - - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, required=true, type=CommandType.LONG, description="template ID of the template to be prepared in primary storage(s).") + + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="template ID of the template to be prepared in primary storage(s).") private Long templateId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getZoneId() { - return zoneId; + return zoneId; } - + public Long getTemplateId() { return templateId; } @@ -69,20 +69,20 @@ public class PrepareTemplateCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() { ListResponse response = new ListResponse(); - - VirtualMachineTemplate vmTemplate = _templateService.prepareTemplate(templateId, zoneId); - List templateResponses = _responseGenerator.createTemplateResponses(vmTemplate.getId(), zoneId, true); + + VirtualMachineTemplate vmTemplate = _templateService.prepareTemplate(templateId, zoneId); + List templateResponses = _responseGenerator.createTemplateResponses(vmTemplate.getId(), zoneId, true); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/AddTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index 7f3f07eb02f..5dca9d2d4c1 100644 --- a/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +33,7 @@ import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds traffic type to a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") +@APICommand(name = "addTrafficType", description="Adds traffic type to a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddTrafficTypeCmd.class.getName()); @@ -42,34 +42,30 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the trafficType to be added to the physical network") private String trafficType; - + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenLabel; - + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") private String kvmLabel; - + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareLabel; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="The VLAN id to be used for Management traffic by VMware host") private String vlan; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - @Override - public String getEntityTable() { - return "physical_network_traffic_types"; - } + public Long getPhysicalNetworkId() { return physicalNetworkId; @@ -90,10 +86,10 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public String getVmwareLabel() { return vmwareLabel; } - + public String getSimulatorLabel() { - //simulators will have no labels - return null; + //simulators will have no labels + return null; } public void setVlan(String vlan) { @@ -112,12 +108,12 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("TrafficType Id: "+getEntityId()); @@ -136,21 +132,22 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { PhysicalNetworkTrafficType result = _networkService.addTrafficTypeToPhysicalNetwork(getPhysicalNetworkId(), getTrafficType(), getXenLabel(), getKvmLabel(), getVmwareLabel(), getSimulatorLabel(), getVlan()); if (result != null) { setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network traffic type: " + getEntityId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.TrafficType; diff --git a/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java index 35089d37f3d..bb665fbfd58 100644 --- a/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(description="Deletes traffic type of a physical network", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteTrafficType", description="Deletes traffic type of a physical network", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteTrafficTypeCmd.class.getName()); @@ -39,19 +39,19 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network_traffic_types") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TrafficTypeResponse.class, + required=true, description="traffic type id") private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +60,12 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _networkService.deletePhysicalNetworkTrafficType(getId()); @@ -81,7 +81,7 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Traffic Type: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_DELETE; diff --git a/api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java old mode 100755 new mode 100644 similarity index 53% rename from api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java index 8b6bde43055..3cd00c02af7 --- a/api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TrafficTypeImplementorResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TrafficTypeImplementorResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -36,51 +33,51 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.user.Account; import com.cloud.utils.Pair; -@Implementation(description="Lists implementors of implementor of a network traffic type or implementors of all network traffic types", responseObject=TrafficTypeImplementorResponse.class, since="3.0.0") +@APICommand(name = "listTrafficTypeImplementors", description="Lists implementors of implementor of a network traffic type or implementors of all network traffic types", responseObject=TrafficTypeImplementorResponse.class, since="3.0.0") public class ListTrafficTypeImplementorsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); - private static final String _name = "listtraffictypeimplementorsresponse"; - + public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); + private static final String _name = "listtraffictypeimplementorsresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="Optional. The network traffic type, if specified, return its implementor. Otherwise, return all traffic types with their implementor") private String trafficType; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getTrafficType() { - return trafficType; + return trafficType; } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - List> results = _networkService.listTrafficTypeImplementor(this); - ListResponse response = new ListResponse(); - List responses= new ArrayList(); - for (Pair r : results) { - TrafficTypeImplementorResponse p = new TrafficTypeImplementorResponse(); - p.setTrafficType(r.first().toString()); - p.setImplementor(r.second()); - p.setObjectName("traffictypeimplementorresponse"); - responses.add(p); - } - - response.setResponses(responses); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + List> results = _networkService.listTrafficTypeImplementor(this); + ListResponse response = new ListResponse(); + List responses= new ArrayList(); + for (Pair r : results) { + TrafficTypeImplementorResponse p = new TrafficTypeImplementorResponse(); + p.setTrafficType(r.first().toString()); + p.setImplementor(r.second()); + p.setObjectName("traffictypeimplementorresponse"); + responses.add(p); + } + + response.setResponses(responses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - - @Override - public String getCommandName() { - return _name; - } + + @Override + public String getCommandName() { + return _name; + } } diff --git a/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/ListTrafficTypesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java index 671d406e289..2cbb13df0d3 --- a/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java @@ -14,27 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; import com.cloud.utils.Pair; - -@Implementation(description="Lists traffic types of a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "listTrafficTypes", description="Lists traffic types of a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") public class ListTrafficTypesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListTrafficTypesCmd.class.getName()); private static final String _name = "listtraffictypesresponse"; @@ -42,14 +41,14 @@ public class ListTrafficTypesCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } @@ -70,7 +69,7 @@ public class ListTrafficTypesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Pair, Integer> trafficTypes = _networkService.listTrafficTypes(getPhysicalNetworkId()); diff --git a/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java index e23967a173c..279c2b858d3 100644 --- a/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; -@Implementation(description="Updates traffic type of a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") +@APICommand(name = "updateTrafficType", description="Updates traffic type of a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateTrafficTypeCmd.class.getName()); @@ -40,25 +39,25 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network_traffic_types") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TrafficTypeResponse.class, + required=true, description="traffic type id") private Long id; - + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenLabel; - + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") private String kvmLabel; - + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareLabel; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -69,11 +68,11 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getKvmLabel() { return kvmLabel; } - + public String getVmwareLabel() { return vmwareLabel; - } - + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -82,12 +81,12 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetworkTrafficType result = _networkService.updatePhysicalNetworkTrafficType(getId(), getXenLabel(), getKvmLabel(), getVmwareLabel()); @@ -104,7 +103,7 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating Traffic Type: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_UPDATE; diff --git a/api/src/com/cloud/api/commands/CreateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java index fc10437e257..2045abf4e93 100644 --- a/api/src/com/cloud/api/commands/CreateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Creates a user for an account that already exists", responseObject=UserResponse.class) +@APICommand(name = "createUser", description="Creates a user for an account that already exists", responseObject=UserResponse.class) public class CreateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateUserCmd.class.getName()); @@ -42,8 +42,8 @@ public class CreateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Creates the user under the specified account. If no account is specified, the username will be used as the account name.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Creates the user under the specified domain. Has to be accompanied with the account parameter") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Creates the user under the specified domain. Has to be accompanied with the account parameter") private Long domainId; @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, required=true, description="email") @@ -108,7 +108,7 @@ public class CreateUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -127,7 +127,7 @@ public class CreateUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserName: "+getUserName()+", FirstName :"+getFirstName()+", LastName: "+getLastName()); @@ -140,4 +140,4 @@ public class CreateUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java index e43649591fc..a43501e7641 100644 --- a/api/src/com/cloud/api/commands/DeleteUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Creates a user for an account", responseObject=UserResponse.class) +@APICommand(name = "deleteUser", description="Creates a user for an account", responseObject=UserResponse.class) public class DeleteUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteUserCmd.class.getName()); @@ -39,8 +38,7 @@ public class DeleteUserCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Deletes a user") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, required=true, description="Deletes a user") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +57,7 @@ public class DeleteUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -69,7 +67,7 @@ public class DeleteUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); @@ -81,4 +79,4 @@ public class DeleteUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DisableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DisableUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java index 407042dfc40..f483e628928 100644 --- a/api/src/com/cloud/api/commands/DisableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; @@ -33,17 +32,17 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Disables a user account", responseObject=UserResponse.class) +@APICommand(name = "disableUser", description="Disables a user account", responseObject=UserResponse.class) public class DisableUserCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableUserCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DisableUserCmd.class.getName()); private static final String s_name = "disableuserresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Disables user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Disables user by user ID.") private Long id; ///////////////////////////////////////////////////// @@ -83,20 +82,20 @@ public class DisableUserCmd extends BaseAsyncCmd { return "disabling user: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); UserAccount user = _accountService.disableUser(getId()); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable user"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.User; diff --git a/api/src/com/cloud/api/commands/EnableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/EnableUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java index 914d59bb4ea..e444aa395d2 100644 --- a/api/src/com/cloud/api/commands/EnableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Enables a user account", responseObject=UserResponse.class) +@APICommand(name = "enableUser", description="Enables a user account", responseObject=UserResponse.class) public class EnableUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(EnableUserCmd.class.getName()); private static final String s_name = "enableuserresponse"; @@ -39,8 +35,8 @@ public class EnableUserCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Enables user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Enables user by user ID.") private Long id; @@ -60,7 +56,7 @@ public class EnableUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -70,14 +66,14 @@ public class EnableUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); UserAccount user = _accountService.enableUser(getId()); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable user"); diff --git a/api/src/com/cloud/api/commands/GetUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/GetUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java index 465e440a0f3..2ffe4ab245d 100644 --- a/api/src/com/cloud/api/commands/GetUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.UserAccount; -@Implementation(description="Find user account by API key", responseObject=UserResponse.class) +@APICommand(name = "getUser", description="Find user account by API key", responseObject=UserResponse.class) public class GetUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetUserCmd.class.getName()); @@ -43,32 +43,32 @@ public class GetUserCmd extends BaseCmd { /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getApiKey() { - return apiKey; - } + public String getApiKey() { + return apiKey; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - return 0; - } - + @Override + public long getEntityOwnerId() { + return 0; + } + @Override public void execute(){ UserAccount result = _accountService.getUserByApiKey(getApiKey()); if(result != null){ - UserResponse response = _responseGenerator.createUserResponse(result); - response.setResponseName(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); + UserResponse response = _responseGenerator.createUserResponse(result); + response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); } else { throw new InvalidParameterValueException("User with specified API key does not exist"); } diff --git a/api/src/com/cloud/api/commands/ListUsersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/ListUsersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java index 03db56d7187..3d68e2f48c9 100644 --- a/api/src/com/cloud/api/commands/ListUsersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java @@ -14,24 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.user.UserAccount; -import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserResponse; -@Implementation(description="Lists user accounts", responseObject=UserResponse.class) +@APICommand(name = "listUsers", description="Lists user accounts", responseObject=UserResponse.class) public class ListUsersCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListUsersCmd.class.getName()); @@ -44,8 +38,7 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.LONG, description="List users by account type. Valid types include admin, domain-admin, read-only-admin, or user.") private Long accountType; - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List user by ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, description="List user by ID.") private Long id; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="List users by state of the user account.") @@ -79,21 +72,14 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ - Pair, Integer> result = _accountService.searchForUsers(this); - ListResponse response = new ListResponse(); - List userResponses = new ArrayList(); - for (UserAccount user : result.first()) { - UserResponse userResponse = _responseGenerator.createUserResponse(user); - userResponses.add(userResponse); - } - response.setResponses(userResponses, result.second()); + ListResponse response = _queryService.searchForUsers(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/LockUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/LockUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java index 5d2f58cd3dd..622b4e9a023 100644 --- a/api/src/com/cloud/api/commands/LockUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java @@ -14,22 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; -@Implementation(description="Locks a user account", responseObject=UserResponse.class) +@APICommand(name = "lockUser", description="Locks a user account", responseObject=UserResponse.class) public class LockUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LockUserCmd.class.getName()); @@ -39,8 +38,8 @@ public class LockUserCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Locks user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Locks user by user ID.") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +58,7 @@ public class LockUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -69,7 +68,7 @@ public class LockUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserAccount user = _accountService.lockUser(getId()); diff --git a/api/src/com/cloud/api/commands/RegisterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/RegisterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java index dff8ec9ae32..06ffc537995 100644 --- a/api/src/com/cloud/api/commands/RegisterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.RegisterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.RegisterResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; -@Implementation(responseObject=RegisterResponse.class, description="This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user") +@APICommand(name = "registerUserKeys", responseObject=RegisterResponse.class, description="This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user") public class RegisterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterCmd.class.getName()); @@ -36,9 +36,9 @@ public class RegisterCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="User id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="User id") private Long id; ///////////////////////////////////////////////////// @@ -56,7 +56,7 @@ public class RegisterCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); diff --git a/api/src/com/cloud/api/commands/UpdateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/UpdateUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index 634b5d6cc14..170d852ff58 100644 --- a/api/src/com/cloud/api/commands/UpdateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Updates a user account", responseObject=UserResponse.class) +@APICommand(name = "updateUser", description="Updates a user account", responseObject=UserResponse.class) public class UpdateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName()); @@ -49,8 +45,8 @@ public class UpdateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.FIRSTNAME, type=CommandType.STRING, description="first name") private String firstname; - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="User id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="User uuid") private Long id; @Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, description="last name") @@ -116,7 +112,7 @@ public class UpdateUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -126,7 +122,7 @@ public class UpdateUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); @@ -139,4 +135,4 @@ public class UpdateUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java index 63eda633858..c9717480e44 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java @@ -14,17 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -32,9 +34,9 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Creates a VLAN IP range.", responseObject=VlanIpRangeResponse.class) +@APICommand(name = "createVlanIpRange", description="Creates a VLAN IP range.", responseObject=VlanIpRangeResponse.class) public class CreateVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateVlanIpRangeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVlanIpRangeCmd.class.getName()); private static final String s_name = "createvlaniprangeresponse"; @@ -44,13 +46,13 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a VLAN") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a VLAN") private Long domainId; @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the VLAN IP range") @@ -65,29 +67,29 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the VLAN IP range") private String netmask; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="optional parameter. Have to be specified for Direct Untagged vlan only.") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="optional parameter. Have to be specified for Direct Untagged vlan only.") private Long podId; @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the VLAN IP range") private String startIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the VLAN. If not specified," + - " will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged") + " will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged") private String vlan; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the VLAN IP range") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the VLAN IP range") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="the network id") private Long networkID; - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the physical network id") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the physical network id") private Long physicalNetworkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -147,17 +149,17 @@ public class CreateVlanIpRangeCmd extends BaseCmd { return physicalNetworkId; } - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException{ try { @@ -175,6 +177,6 @@ public class CreateVlanIpRangeCmd extends BaseCmd { } catch (InsufficientCapacityException ex) { s_logger.info(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java index f44c92ee3f9..f12b2175aef 100644 --- a/api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Creates a VLAN IP range.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVlanIpRange", description="Creates a VLAN IP range.", responseObject=SuccessResponse.class) public class DeleteVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVlanIpRangeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteVlanIpRangeCmd.class.getName()); private static final String s_name = "deletevlaniprangeresponse"; @@ -37,8 +37,8 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the VLAN IP range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + required=true, description="the id of the VLAN IP range") private Long id; ///////////////////////////////////////////////////// @@ -57,12 +57,12 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteVlanIpRange(this); @@ -73,4 +73,4 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete vlan ip range"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java index 5cefa65cb24..9b6b997c4b8 100644 --- a/api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java @@ -14,26 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; import com.cloud.dc.Vlan; import com.cloud.utils.Pair; -@Implementation(description="Lists all VLAN IP ranges.", responseObject=VlanIpRangeResponse.class) +@APICommand(name = "listVlanIpRanges", description="Lists all VLAN IP ranges.", responseObject=VlanIpRangeResponse.class) public class ListVlanIpRangesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListVlanIpRangesCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListVlanIpRangesCmd.class.getName()); private static final String s_name = "listvlaniprangesresponse"; @@ -43,39 +48,39 @@ public class ListVlanIpRangesCmd extends BaseListCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account with which the VLAN IP range is associated. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="project who will own the VLAN") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="project who will own the VLAN") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID with which the VLAN IP range is associated. If used with the account parameter, returns all VLAN IP ranges for that account in the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID with which the VLAN IP range is associated. If used with the account parameter, returns all VLAN IP ranges for that account in the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=false, description="the ID of the VLAN IP range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + required=false, description="the ID of the VLAN IP range") private Long id; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the VLAN IP range") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID of the VLAN IP range") private Long podId; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the VLAN. Default is an \"untagged\" VLAN.") private String vlan; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the VLAN IP range") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the VLAN IP range") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="network id of the VLAN IP range") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="network id of the VLAN IP range") private Long networkId; - + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="true if VLAN is of Virtual type, false if Direct") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="physical network id of the VLAN IP range") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="physical network id of the VLAN IP range") private Long physicalNetworkId; ///////////////////////////////////////////////////// @@ -109,34 +114,34 @@ public class ListVlanIpRangesCmd extends BaseListCmd { public Long getNetworkId() { return networkId; } - + public Boolean getForVirtualNetwork() { - return forVirtualNetwork; - } - + return forVirtualNetwork; + } + public Long getProjectId() { return projectId; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override + + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> vlans = _mgr.searchForVlans(this); ListResponse response = new ListResponse(); List vlanResponses = new ArrayList(); - for (Vlan vlan : vlans.first()) { + for (Vlan vlan : vlans.first()) { VlanIpRangeResponse vlanResponse = _responseGenerator.createVlanIpRangeResponse(vlan); vlanResponse.setObjectName("vlaniprange"); vlanResponses.add(vlanResponse); diff --git a/api/src/com/cloud/api/commands/AssignVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java similarity index 65% rename from api/src/com/cloud/api/commands/AssignVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java index be28cc037d4..3482ec756fb 100644 --- a/api/src/com/cloud/api/commands/AssignVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java @@ -14,31 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; -import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.ZoneResponse; -import com.cloud.async.AsyncJob; -import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Move a user VM to another user under same domain.", responseObject=UserVmResponse.class, since="3.0.0") +@APICommand(name = "assignVirtualMachine", description="Move a user VM to another user under same domain.", responseObject=UserVmResponse.class, since="3.0.0") public class AssignVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AssignVMCmd.class.getName()); @@ -47,27 +41,27 @@ public class AssignVMCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the vm ID of the user VM to be moved") + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="the vm ID of the user VM to be moved") private Long virtualMachineId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="account name of the new VM owner.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="domain id of the new VM owner.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="domain id of the new VM owner.") private Long domainId; //Network information - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of network ids that will be part of VM network after move in advanced network setting.") + @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=NetworkResponse.class, + description="list of network ids that will be part of VM network after move in advanced network setting.") private List networkIds; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is moved in a zone with Basic Network support.") + @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is moved in a zone with Basic Network support.") private List securityGroupIdList; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -80,17 +74,17 @@ public class AssignVMCmd extends BaseCmd { return accountName; } - public Long getDomainId() { - return domainId; - } - - public List getNetworkIds() { - return networkIds; - } + public Long getDomainId() { + return domainId; + } - public List getSecurityGroupIdList() { - return securityGroupIdList; - } + public List getNetworkIds() { + return networkIds; + } + + public List getSecurityGroupIdList() { + return securityGroupIdList; + } ///////////////////////////////////////////////////// @@ -101,22 +95,22 @@ public class AssignVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ try { UserVm userVm = _userVmService.moveVMToUser(this); if (userVm == null){ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm"); - } - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + } + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); }catch (Exception e){ e.printStackTrace(); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm " + e.getMessage()); } - + } @Override diff --git a/api/src/com/cloud/api/commands/MigrateVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java similarity index 61% rename from api/src/com/cloud/api/commands/MigrateVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java index c292a2e4e1b..5bb694da655 100644 --- a/api/src/com/cloud/api/commands/MigrateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java @@ -14,18 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -39,7 +37,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; -@Implementation(description="Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool", responseObject=UserVmResponse.class) +@APICommand(name = "migrateVirtualMachine", description="Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool", responseObject=UserVmResponse.class) public class MigrateVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MigrateVMCmd.class.getName()); @@ -49,16 +47,16 @@ public class MigrateVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, required=false, description="Destination Host ID to migrate VM to. Required for live migrating a VM from host to host") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + required=false, description="Destination Host ID to migrate VM to. Required for live migrating a VM from host to host") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, required=false, description="Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume") + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, entityType=StoragePoolResponse.class, + required=false, description="Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume") private Long storageId; ///////////////////////////////////////////////////// @@ -72,9 +70,9 @@ public class MigrateVMCmd extends BaseAsyncCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getStoragePoolId() { - return storageId; + return storageId; } @@ -86,7 +84,7 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -106,66 +104,66 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - if (getHostId() == null && getStoragePoolId() == null) { - throw new InvalidParameterValueException("either hostId or storageId must be specified"); - } - - if (getHostId() != null && getStoragePoolId() != null) { - throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); - } - + if (getHostId() == null && getStoragePoolId() == null) { + throw new InvalidParameterValueException("either hostId or storageId must be specified"); + } + + if (getHostId() != null && getStoragePoolId() != null) { + throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); + } + UserVm userVm = _userVmService.getUserVm(getVirtualMachineId()); if (userVm == null) { throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId()); } - + Host destinationHost = null; if (getHostId() != null) { - destinationHost = _resourceService.getHost(getHostId()); - if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + destinationHost = _resourceService.getHost(getHostId()); + if (destinationHost == null) { + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); } - + StoragePool destStoragePool = null; if (getStoragePoolId() != null) { - destStoragePool = _storageService.getStoragePool(getStoragePoolId()); - if (destStoragePool == null) { - throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); + destStoragePool = _storageService.getStoragePool(getStoragePoolId()); + if (destStoragePool == null) { + throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); } - + try{ - VirtualMachine migratedVm = null; - if (getHostId() != null) { - migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - } else if (getStoragePoolId() != null) { - migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); - } - if (migratedVm != null) { + VirtualMachine migratedVm = null; + if (getHostId() != null) { + migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + } else if (getStoragePoolId() != null) { + migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); + } + if (migratedVm != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", (UserVm)migratedVm).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RecoverVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/RecoverVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java index 50dd5e7c820..f8308614b89 100644 --- a/api/src/com/cloud/api/commands/RecoverVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java @@ -14,22 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.ResourceAllocationException; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Recovers a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "recoverVirtualMachine", description="Recovers a virtual machine.", responseObject=UserVmResponse.class) public class RecoverVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RecoverVMCmd.class.getName()); @@ -39,8 +38,8 @@ public class RecoverVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +58,7 @@ public class RecoverVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -69,7 +68,7 @@ public class RecoverVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute() throws ResourceAllocationException{ UserVm result = _userVmService.recoverVirtualMachine(this); @@ -80,6 +79,6 @@ public class RecoverVMCmd extends BaseCmd { } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recover vm"); } - + } } diff --git a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java index c56f9affc4b..5bb76ab034b 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java @@ -14,19 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +39,7 @@ import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Creates a private gateway", responseObject=PrivateGatewayResponse.class) +@APICommand(name = "createPrivateGateway", description="Creates a private gateway", responseObject=PrivateGatewayResponse.class) public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePrivateGatewayCmd.class.getName()); @@ -47,27 +48,27 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the Private gateway") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the Private gateway") private String netmask; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the Vlan for the private gateway") private String vlan; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="the VPC network belongs to") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + required=true, description="the VPC network belongs to") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,7 +80,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getVlan() { return vlan; } - + public String getNetmask() { return netmask; } @@ -87,11 +88,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getStartIp() { return ipAddress; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getVpcId() { return vpcId; } @@ -103,8 +104,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { PrivateGateway result = null; @@ -119,16 +120,17 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override - public void execute() throws InsufficientCapacityException, ConcurrentOperationException, + public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException, ResourceUnavailableException { PrivateGateway result = _vpcService.applyVpcPrivateGateway(getEntityId(), true); if (result != null) { @@ -139,7 +141,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -154,13 +156,9 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating private gateway"; } - - @Override - public String getEntityTable() { - return "vpc_gateways"; - } - - + + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -174,7 +172,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { } return vpc.getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; diff --git a/api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java index 78ce2856679..273f7c05233 100644 --- a/api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.vpc.VpcOffering; import com.cloud.user.Account; -@Implementation(description="Creates VPC offering", responseObject=VpcOfferingResponse.class) +@APICommand(name = "createVPCOffering", description="Creates VPC offering", responseObject=VpcOfferingResponse.class) public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ public static final Logger s_logger = Logger.getLogger(CreateVPCOfferingCmd.class.getName()); private static final String _name = "createvpcofferingresponse"; @@ -41,22 +36,22 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the vpc offering") private String vpcOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of " + - "the vpc offering") + "the vpc offering") private String displayText; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the vpc offering") private List supportedServices; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcOfferingName() { return vpcOfferingName; } @@ -68,18 +63,19 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ public List getSupportedServices() { return supportedServices; } - + @Override public void create() throws ResourceAllocationException { VpcOffering vpcOff = _vpcService.createVpcOffering(getVpcOfferingName(), getDisplayText(), getSupportedServices()); if (vpcOff != null) { this.setEntityId(vpcOff.getId()); + this.setEntityUuid(vpcOff.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC offering"); } } - + @Override public void execute() { VpcOffering vpc = _vpcService.getVpcOffering(this.getEntityId()); @@ -92,10 +88,6 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ } } - @Override - public String getEntityTable() { - return "vpc_offerings"; - } @Override public String getEventType() { diff --git a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java index 2767efdae65..4a1e8d05912 100644 --- a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,7 +35,7 @@ import com.cloud.network.vpc.VpcGateway; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Private gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deletePrivateGateway", description="Deletes a Private gateway", responseObject=SuccessResponse.class) public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePrivateGatewayCmd.class.getName()); private static final String s_name = "deleteprivategatewayresponse"; @@ -44,8 +44,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the private gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = PrivateGatewayResponse.class, + required=true, description="the ID of the private gateway") private Long id; ///////////////////////////////////////////////////// @@ -55,7 +55,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -63,7 +63,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_PRIVATE_GATEWAY_DELETE; @@ -73,16 +73,16 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting private gateway id=" + id); } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { UserContext.current().setEventDetails("Network ACL Id: " + id); - boolean result = _vpcService.deleteVpcPrivateGateway(id); + boolean result = _vpcService.deleteVpcPrivateGateway(id); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -90,8 +90,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete private gateway"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -105,10 +105,10 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java index 88d40e58b4c..231f2ee2955 100644 --- a/api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(description="Deletes VPC offering", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVPCOffering", description="Deletes VPC offering", responseObject=SuccessResponse.class) public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVPCOfferingCmd.class.getName()); private static final String s_name = "deletevpcofferingresponse"; @@ -38,11 +38,10 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the VPC offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcOfferingResponse.class, + required=true, description="the ID of the VPC offering") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +50,6 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +58,12 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _vpcService.deleteVpcOffering(getId()); @@ -76,7 +74,7 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC offering"); } } - + @Override public String getEventType(){ return EventTypes.EVENT_VPC_OFFERING_DELETE; @@ -87,6 +85,6 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public String getEventDescription() { return "Deleting VPC offering id=" + getId(); } - - + + } diff --git a/api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java index 77f2c030cdb..65df48e3e1f 100644 --- a/api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java @@ -14,23 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.network.vpc.VpcOffering; import com.cloud.user.Account; -@Implementation(description="Updates VPC offering", responseObject=VpcOfferingResponse.class) +@APICommand(name = "updateVPCOffering", description="Updates VPC offering", responseObject=VpcOfferingResponse.class) public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(UpdateVPCOfferingCmd.class.getName()); private static final String _name = "updatevpcofferingresponse"; @@ -38,33 +33,33 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC offering") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcOfferingResponse.class, + description="the id of the VPC offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the VPC offering") private String vpcOffName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the VPC offering") private String displayText; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="update state for the VPC offering; " + - "supported states - Enabled/Disabled") + "supported states - Enabled/Disabled") private String state; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcOfferingName() { return vpcOffName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } @@ -72,7 +67,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -81,7 +76,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java old mode 100755 new mode 100644 similarity index 84% rename from api/src/com/cloud/api/commands/CreateZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java index 1e9170d45e2..e49f2439288 --- a/api/src/com/cloud/api/commands/CreateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a Zone.", responseObject=ZoneResponse.class) +@APICommand(name = "createZone", description="Creates a Zone.", responseObject=ZoneResponse.class) public class CreateZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateZoneCmd.class.getName()); @@ -60,16 +61,16 @@ public class CreateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="Network domain name for the networks in the zone") private String domain; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public zones") - private Long domainId; - + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public zones") + private Long domainId; + @Parameter(name=ApiConstants.NETWORK_TYPE, type=CommandType.STRING, required=true, description="network type of the zone, can be Basic or Advanced") - private String networkType; - + private String networkType; + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Zone for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true if network is security group enabled, false otherwise") private Boolean securitygroupenabled; @@ -109,17 +110,17 @@ public class CreateZoneCmd extends BaseCmd { } public Long getDomainId(){ - return domainId; + return domainId; } - + public String getNetworkType(){ return networkType; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public Boolean getSecuritygroupenabled() { if (securitygroupenabled == null) { return false; @@ -140,16 +141,16 @@ public class CreateZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - UserContext.current().setEventDetails("Zone Name: "+getZoneName()); - DataCenter result = _configService.createZone(this); + UserContext.current().setEventDetails("Zone Name: "+getZoneName()); + DataCenter result = _configService.createZone(this); if (result != null){ ZoneResponse response = _responseGenerator.createZoneResponse(result,false); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DeleteZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/DeleteZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java index c695d8fdf83..d09c7fff891 100644 --- a/api/src/com/cloud/api/commands/DeleteZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Zone.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteZone", description="Deletes a Zone.", responseObject=SuccessResponse.class) public class DeleteZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteZoneCmd.class.getName()); @@ -38,8 +35,8 @@ public class DeleteZoneCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the Zone") private Long id; @@ -60,7 +57,7 @@ public class DeleteZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -68,8 +65,8 @@ public class DeleteZoneCmd extends BaseCmd { @Override public void execute(){ - UserContext.current().setEventDetails("Zone Id: "+getId()); - boolean result = _configService.deleteZone(this); + UserContext.current().setEventDetails("Zone Id: "+getId()); + boolean result = _configService.deleteZone(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java similarity index 56% rename from api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java index 7f06926070c..816befbd029 100644 --- a/api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java @@ -15,23 +15,25 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ApiConstants; -import com.cloud.api.IdentityMapper; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.user.Account; import com.cloud.event.EventTypes; import com.cloud.async.AsyncJob; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="Marks a default zone for this account", responseObject=AccountResponse.class, since="4.0") +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.BaseCmd; + +@APICommand(name = "markDefaultZoneForAccount", description="Marks a default zone for this account", responseObject=AccountResponse.class, since="4.0") public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MarkDefaultZoneForAccountCmd.class.getName()); @@ -41,16 +43,16 @@ public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { ////////////////API parameters ////////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Name of the account that is to be marked.") + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, entityType=AccountResponse.class, + required=true, description="Name of the account that is to be marked.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="Marks the account that belongs to the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="Marks the account that belongs to the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="The Zone ID with which the account is to be marked.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="The Zone ID with which the account is to be marked.") private Long defaultZoneId; ///////////////////////////////////////////////////// @@ -68,47 +70,47 @@ public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { public Long getDefaultZoneId() { return defaultZoneId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { - return s_name; + return s_name; } @Override public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; + return Account.ACCOUNT_ID_SYSTEM; } - + @Override public String getEventType() { - return EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE; + return EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE; } - + @Override public String getEventDescription() { - return "Marking account with the default zone: " + getDefaultZoneId(); + return "Marking account with the default zone: " + getDefaultZoneId(); } @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; } - + @Override public void execute(){ - Account result = _configService.markDefaultZone(getAccountName(),getDomainId(), getDefaultZoneId()); - if (result != null) { - AccountResponse response = _responseGenerator.createAccountResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to mark the account with the default zone"); - } + Account result = _configService.markDefaultZone(getAccountName(),getDomainId(), getDefaultZoneId()); + if (result != null) { + AccountResponse response = _responseGenerator.createAccountResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to mark the account with the default zone"); + } } } diff --git a/api/src/com/cloud/api/commands/UpdateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java old mode 100755 new mode 100644 similarity index 87% rename from api/src/com/cloud/api/commands/UpdateZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java index 1fa0f79da6b..0bfd1a31a0f --- a/api/src/com/cloud/api/commands/UpdateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates a Zone.", responseObject=ZoneResponse.class) +@APICommand(name = "updateZone", description="Updates a Zone.", responseObject=ZoneResponse.class) public class UpdateZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateZoneCmd.class.getName()); @@ -51,8 +47,8 @@ public class UpdateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.GUEST_CIDR_ADDRESS, type=CommandType.STRING, description="the guest CIDR address for the Zone") private String guestCidrAddress; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the Zone") private Long id; @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS for the Zone") @@ -66,21 +62,21 @@ public class UpdateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.IS_PUBLIC, type=CommandType.BOOLEAN, description="updates a private zone to public if set, but not vice-versa") private Boolean isPublic; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the Zone") private Map details; - + @Parameter(name=ApiConstants.DHCP_PROVIDER, type=CommandType.STRING, description="the dhcp Provider for the Zone") private String dhcpProvider; - + @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="Network domain name for the networks in the zone; empty string will update domain with NULL value") private String domain; - + @Parameter(name=ApiConstants.DNS_SEARCH_ORDER, type=CommandType.LIST, collectionType = CommandType.STRING, description="the dns search order list") - private List dnsSearchOrder; + private List dnsSearchOrder; @Parameter(name=ApiConstants.LOCAL_STORAGE_ENABLED, type=CommandType.BOOLEAN, description="true if local storage offering enabled, false otherwise") private Boolean localStorageEnabled; @@ -120,26 +116,26 @@ public class UpdateZoneCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public Map getDetails() { return details; } - + public String getDhcpProvider() { return dhcpProvider; } - + public String getDomain() { return domain; } public List getDnsSearchOrder() { return dnsSearchOrder; - } + } public Boolean getLocalStorageEnabled() { return localStorageEnabled; @@ -153,16 +149,16 @@ public class UpdateZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - UserContext.current().setEventDetails("Zone Id: "+getId()); - DataCenter result = _configService.editZone(this); + UserContext.current().setEventDetails("Zone Id: "+getId()); + DataCenter result = _configService.editZone(this); if (result != null) { ZoneResponse response = _responseGenerator.createZoneResponse(result, false); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/AddAccountToProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java index 73609fb52ef..889c3697515 100644 --- a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -import com.cloud.utils.AnnotationHelper; -@Implementation(description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "addAccountToProject", description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") public class AddAccountToProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddAccountToProjectCmd.class.getName()); @@ -43,13 +38,13 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to add the account to") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project to add the account to") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="name of the account to be added to the project") private String accountName; - + @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, description="email to which invitation to the project is going to be sent") private String email; @@ -66,7 +61,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { return projectId; } - + public String getEmail() { return email; } @@ -85,7 +80,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { if (accountName == null && email == null) { throw new InvalidParameterValueException("Either accountName or email is required"); } - + UserContext.current().setEventDetails("Project id: "+ projectId + "; accountName " + accountName); boolean result = _projectService.addAccountToProject(getProjectId(), getAccountName(), getEmail()); if (result) { @@ -95,31 +90,31 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add account to the project"); } } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(getProjectId()); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, getProjectId(), "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, getProjectId(), "projectId"); throw ex; - } - - return _projectService.getProjectOwner(getProjectId()).getId(); + } + + return _projectService.getProjectOwner(getProjectId()).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_ADD; } - + @Override public String getEventDescription() { if (accountName != null) { return "Adding account " + getAccountName() + " to project: " + getProjectId(); } else { return "Sending invitation to email " + email + " to join project: " + getProjectId(); - } + } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java index d9b3bf19bee..f9e967ad4c2 100644 --- a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java @@ -14,24 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.project.DeleteProjectCmd; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Deletes account from the project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteAccountFromProject", description="Deletes account from the project", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectCmd.class.getName()); @@ -40,10 +37,10 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to remove the account from") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project to remove the account from") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="name of the account to be removed from the project") private String accountName; @@ -52,7 +49,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// - + @Override public String getCommandName() { @@ -82,26 +79,26 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete account from the project"); } } - - + + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); - } - - return _projectService.getProjectOwner(projectId).getId(); + } + + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE; } - + @Override public String getEventDescription() { return "Removing account " + accountName + " from project: " + projectId; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListAccountsCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java old mode 100755 new mode 100644 similarity index 69% rename from api/src/com/cloud/api/commands/ListAccountsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java index 6e0a524cc93..f679a5ae7d1 --- a/api/src/com/cloud/api/commands/ListAccountsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListDomainResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListDomainResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserResponse; + import com.cloud.user.Account; import com.cloud.utils.Pair; -@Implementation(description="Lists accounts and provides detailed account information for listed accounts", responseObject=AccountResponse.class) +@APICommand(name = "listAccounts", description="Lists accounts and provides detailed account information for listed accounts", responseObject=AccountResponse.class) public class ListAccountsCmd extends BaseListDomainResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); private static final String s_name = "listaccountsresponse"; ///////////////////////////////////////////////////// @@ -43,8 +44,8 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.LONG, description="list accounts by account type. Valid account types are 1 (admin), 2 (domain-admin), and 0 (user).") private Long accountType; - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list account by account ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AccountResponse.class, + description="list account by account ID") private Long id; @Parameter(name=ApiConstants.IS_CLEANUP_REQUIRED, type=CommandType.BOOLEAN, description="list accounts by cleanuprequred attribute (values are true or false)") @@ -55,7 +56,7 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list accounts by state. Valid states are enabled, disabled, and locked.") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,7 +80,7 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -92,17 +93,8 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Override public void execute(){ - Pair, Integer> accounts = _accountService.searchForAccounts(this); - ListResponse response = new ListResponse(); - List accountResponses = new ArrayList(); - for (Account account : accounts.first()) { - AccountResponse acctResponse = _responseGenerator.createAccountResponse(account); - acctResponse.setObjectName("account"); - accountResponses.add(acctResponse); - } - response.setResponses(accountResponses, accounts.second()); + ListResponse response = _queryService.searchForAccounts(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListProjectAccountsCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/ListProjectAccountsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java index 088363377c7..2c279db64a8 100644 --- a/api/src/com/cloud/api/commands/ListProjectAccountsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.projects.ProjectAccount; -import com.cloud.user.Account; -import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectResponse; -@Implementation(description="Lists project's accounts", responseObject=ProjectResponse.class, since="3.0.0") +import com.cloud.user.Account; + +@APICommand(name = "listProjectAccounts", description="Lists project's accounts", responseObject=ProjectResponse.class, since="3.0.0") public class ListProjectAccountsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListProjectAccountsCmd.class.getName()); @@ -42,14 +37,14 @@ public class ListProjectAccountsCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project") private Long projectId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="list accounts of the project by account name") private String accountName; - + @Parameter(name=ApiConstants.ROLE, type=CommandType.STRING, description="list accounts of the project by role") private String role; ///////////////////////////////////////////////////// @@ -60,18 +55,29 @@ public class ListProjectAccountsCmd extends BaseListCmd { return accountName; } + + public Long getProjectId() { + return projectId; + } + + + public String getRole() { + return role; + } + + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { //TODO - return project entity ownerId return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -79,17 +85,9 @@ public class ListProjectAccountsCmd extends BaseListCmd { @Override public void execute(){ - Pair, Integer> projectAccounts = _projectService.listProjectAccounts(projectId, - accountName, role, this.getStartIndex(), this.getPageSizeVal()); - ListResponse response = new ListResponse(); - List projectResponses = new ArrayList(); - for (ProjectAccount projectAccount : projectAccounts.first()) { - ProjectAccountResponse projectAccountResponse = _responseGenerator.createProjectAccountResponse(projectAccount); - projectResponses.add(projectAccountResponse); - } - response.setResponses(projectResponses, projectAccounts.second()); + ListResponse response = _queryService.listProjectAccounts(this); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/AssociateIPAddrCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index 878a9fc4667..93bb2401d8f 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -14,21 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.IPAddressResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -45,7 +49,7 @@ import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Acquires and associates a public IP to an account.", responseObject=IPAddressResponse.class) +@APICommand(name = "associateIpAddress", description="Acquires and associates a public IP to an account.", responseObject=IPAddressResponse.class) public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName()); private static final String s_name = "associateipaddressresponse"; @@ -54,45 +58,38 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account to associate with this IP address") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, description="the ID of the domain to associate with this IP address") private Long domainId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, description="the ID of the availability zone you want to acquire an public IP address from") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, description="The network this ip address should be associated to.") private Long networkId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, description="Deploy vm for the project") private Long projectId; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC you want the ip address to " + - "be associated with") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="the VPC you want the ip address to " + + "be associated with") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "user_ip_address"; - } - + public String getAccountName() { - if (accountName != null) { + if (accountName != null) { return accountName; } return UserContext.current().getCaller().getAccountName(); @@ -119,56 +116,56 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { return ntwk.getDataCenterId(); } } - + throw new InvalidParameterValueException("Unable to figure out zone to assign ip to"); } - + public Long getVpcId() { return vpcId; } - + public Long getNetworkId() { if (vpcId != null) { return null; } - + if (networkId != null) { return networkId; - } + } Long zoneId = getZoneId(); - + if (zoneId == null) { return null; } - + DataCenter zone = _configService.getZone(zoneId); if (zone.getNetworkType() == NetworkType.Advanced) { - List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), + List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); - throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + + throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default Guest network for account " + + throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); } else { return defaultGuestNetwork.getId(); } } } - + @Override public long getEntityOwnerId() { Account caller = UserContext.current().getCaller(); @@ -193,7 +190,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public String getEventType() { return EventTypes.EVENT_NET_IP_ASSIGN; } - + @Override public String getEventDescription() { return "associating ip to network id: " + getNetworkId() + " in zone " + getZoneId(); @@ -210,16 +207,17 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { } public static String getResultObjectName() { - return "addressinfo"; + return "addressinfo"; } - + @Override public void create() throws ResourceAllocationException{ try { - IpAddress ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), getZoneId(), getNetworkId()); + IpAddress ip = _networkService.allocateIP(_accountService.getAccount(getEntityOwnerId()), false, getZoneId()); if (ip != null) { this.setEntityId(ip.getId()); + this.setEntityUuid(ip.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to allocate ip address"); } @@ -232,9 +230,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } - + @Override - public void execute() throws ResourceUnavailableException, ResourceAllocationException, + public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { UserContext.current().setEventDetails("Ip Id: " + getEntityId()); @@ -243,9 +241,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { if (getVpcId() != null) { result = _vpcService.associateIPToVpc(getEntityId(), getVpcId()); } else if (getNetworkId() != null) { - result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId()); + result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId()); } - + if (result != null) { IPAddressResponse ipResponse = _responseGenerator.createIPAddressResponse(result); ipResponse.setResponseName(getCommandName()); @@ -254,8 +252,8 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign ip address"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -265,7 +263,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { return getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; diff --git a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java index 2f2addb3f9b..20ccd89ba84 100644 --- a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; @@ -34,7 +31,7 @@ import com.cloud.network.IpAddress; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Disassociates an ip address from the account.", responseObject=SuccessResponse.class) +@APICommand(name = "disassociateIpAddress", description="Disassociates an ip address from the account.", responseObject=SuccessResponse.class) public class DisassociateIPAddrCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisassociateIPAddrCmd.class.getName()); @@ -44,14 +41,14 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the public ip address" + - " to disassociate") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID,entityType = IPAddressResponse.class, + required=true, description="the id of the public ip address" + + " to disassociate") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -81,7 +78,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disassociate ip address"); } } - + @Override public String getEventType() { return EventTypes.EVENT_NET_IP_RELEASE; @@ -91,7 +88,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disassociating ip address with id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -101,13 +98,13 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { } ownerId = ip.getAccountId(); } - + if (ownerId == null) { return Account.ACCOUNT_ID_SYSTEM; } return ownerId; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -118,22 +115,22 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { IpAddress ip = getIpAddress(id); return ip.getAssociatedWithNetworkId(); } - + private IpAddress getIpAddress(long id) { IpAddress ip = _entityMgr.findById(IpAddress.class, id); - + if (ip == null) { throw new InvalidParameterValueException("Unable to find ip address by id=" + id); } else { return ip; } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } - + @Override public Long getInstanceId() { return getIpAddressId(); diff --git a/api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java index a49c5fe6b79..06b08da6907 100644 --- a/api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java @@ -14,27 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.network.IpAddress; import com.cloud.utils.Pair; - -@Implementation(description="Lists all public ip addresses", responseObject=IPAddressResponse.class) -public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { +@APICommand(name = "listPublicIpAddresses", description="Lists all public ip addresses", responseObject=IPAddressResponse.class) +public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListPublicIpAddressesCmd.class.getName()); private static final String s_name = "listpublicipaddressesresponse"; @@ -48,41 +51,41 @@ public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="the virtual network for the IP address") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists ip address by id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="lists ip address by id") private Long id; @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="lists the specified IP address") private String ipAddress; - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.VLAN_ID, type=CommandType.LONG, description="lists all public IP addresses by VLAN ID") + @Parameter(name=ApiConstants.VLAN_ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + description="lists all public IP addresses by VLAN ID") private Long vlanId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists all public IP addresses by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="lists all public IP addresses by Zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.FOR_LOAD_BALANCING, type=CommandType.BOOLEAN, description="list only ips used for load balancing") private Boolean forLoadBalancing; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="lists all public IP addresses by physical network id") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="lists all public IP addresses by physical network id") private Long physicalNetworkId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ASSOCIATED_NETWORK_ID, type=CommandType.LONG, description="lists all public IP addresses associated to the network specified") + + @Parameter(name=ApiConstants.ASSOCIATED_NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="lists all public IP addresses associated to the network specified") private Long associatedNetworkId; - + @Parameter(name=ApiConstants.IS_SOURCE_NAT, type=CommandType.BOOLEAN, description="list only source nat ip addresses") private Boolean isSourceNat; - + @Parameter(name=ApiConstants.IS_STATIC_NAT, type=CommandType.BOOLEAN, description="list only static nat ip addresses") private Boolean isStaticNat; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List ips belonging to the VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="List ips belonging to the VPC") private Long vpcId; ///////////////////////////////////////////////////// @@ -111,35 +114,35 @@ public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getAssociatedNetworkId() { - return associatedNetworkId; - } + return associatedNetworkId; + } public Boolean getIsSourceNat() { - return isSourceNat; - } + return isSourceNat; + } - public Boolean getIsStaticNat() { - return isStaticNat; - } + public Boolean getIsStaticNat() { + return isStaticNat; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; - } + } - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _mgr.searchForIPAddresses(this); @@ -155,7 +158,7 @@ public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { response.setResponseName(getCommandName()); this.setResponseObject(response); } - + public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } diff --git a/api/src/com/cloud/api/commands/CreateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/CreateAutoScalePolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java index 4d9374791ed..e92721d77bf 100644 --- a/api/src/com/cloud/api/commands/CreateAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java @@ -1,33 +1,29 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import com.cloud.async.AsyncJob; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; @@ -36,7 +32,7 @@ import com.cloud.network.as.AutoScalePolicy; import com.cloud.network.as.Condition; import com.cloud.user.Account; -@Implementation(description = "Creates an autoscale policy for a provision or deprovision action, the action is taken when the all the conditions evaluates to true for the specified duration. The policy is in effect once it is attached to a autscale vm group.", responseObject = AutoScalePolicyResponse.class) +@APICommand(name = "createAutoScalePolicy", description = "Creates an autoscale policy for a provision or deprovision action, the action is taken when the all the conditions evaluates to true for the specified duration. The policy is in effect once it is attached to a autscale vm group.", responseObject = AutoScalePolicyResponse.class) public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateAutoScalePolicyCmd.class.getName()); @@ -55,8 +51,8 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.QUIETTIME, type = CommandType.INTEGER, description = "the cool down period for which the policy should not be evaluated after the action has been taken") private Integer quietTime; - @IdentityMapper(entityTableName = "conditions") - @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, required = true, description = "the list of IDs of the conditions that are being evaluated on every interval") + @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ConditionResponse.class, + required = true, description = "the list of IDs of the conditions that are being evaluated on every interval") private List conditionIds; // /////////////////////////////////////////////////// @@ -66,10 +62,6 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { private Long conditionDomainId; private Long conditionAccountId; - @Override - public String getEntityTable() { - return "autoscale_policies"; - } public int getDuration() { return duration; @@ -163,6 +155,7 @@ public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { AutoScalePolicy result = _autoScaleService.createAutoScalePolicy(this); if (result != null) { this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create AutoScale Policy"); } diff --git a/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java index 83d76072d83..e3d47a09c7d 100644 --- a/api/src/com/cloud/api/commands/CreateAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java @@ -1,33 +1,31 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +33,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.network.rules.LoadBalancer; -@Implementation(description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = AutoScaleVmGroupResponse.class) +@APICommand(name = "createAutoScaleVmGroup", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = AutoScaleVmGroupResponse.class) public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmGroupCmd.class.getName()); @@ -45,8 +43,8 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, required = true, description = "the ID of the load balancer rule") + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") private long lbRuleId; @Parameter(name = ApiConstants.MIN_MEMBERS, type = CommandType.INTEGER, required = true, description = "the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.") @@ -58,26 +56,22 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.INTERVAL, type = CommandType.INTEGER, description = "the frequency at which the conditions have to be evaluated") private Integer interval; - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, required = true, description = "list of scaleup autoscale policies") + @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "list of scaleup autoscale policies") private List scaleUpPolicyIds; - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, required = true, description = "list of scaledown autoscale policies") + @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "list of scaledown autoscale policies") private List scaleDownPolicyIds; - @IdentityMapper(entityTableName = "autoscale_vmprofiles") - @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.LONG, required = true, description = "the autoscale profile that contains information about the vms in the vm group.") + @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the autoscale profile that contains information about the vms in the vm group.") private long profileId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - @Override - public String getEntityTable() { - return "autoscale_vmgroups"; - } public int getMinMembers() { return minMembers; @@ -163,6 +157,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { AutoScaleVmGroup result = _autoScaleService.createAutoScaleVmGroup(this); if (result != null) { this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); } diff --git a/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java index 68c85d09199..25bb03b778f 100644 --- a/api/src/com/cloud/api/commands/CreateAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java @@ -1,34 +1,37 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +41,7 @@ import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description = "Creates a profile that contains information about the virtual machine which will be provisioned automatically by autoscale feature.", responseObject = AutoScaleVmProfileResponse.class) +@APICommand(name = "createAutoScaleVmProfile", description = "Creates a profile that contains information about the virtual machine which will be provisioned automatically by autoscale feature.", responseObject = AutoScaleVmProfileResponse.class) @SuppressWarnings("rawtypes") public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmProfileCmd.class.getName()); @@ -49,16 +52,16 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, required = true, description = "availability zone for the auto deployed virtual machine") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + required = true, description = "availability zone for the auto deployed virtual machine") private Long zoneId; - @IdentityMapper(entityTableName = "disk_offering") - @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.LONG, required = true, description = "the service offering of the auto deployed virtual machine") + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, + required = true, description = "the service offering of the auto deployed virtual machine") private Long serviceOfferingId; - @IdentityMapper(entityTableName = "vm_template") - @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.LONG, required = true, description = "the template of the auto deployed virtual machine") + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, + required = true, description = "the template of the auto deployed virtual machine") private Long templateId; @Parameter(name = ApiConstants.OTHER_DEPLOY_PARAMS, type = CommandType.STRING, description = "parameters other than zoneId/serviceOfferringId/templateId of the auto deployed virtual machine") @@ -70,8 +73,8 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.COUNTERPARAM_LIST, type = CommandType.MAP, description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161") private Map counterParamList; - @IdentityMapper(entityTableName = "user") - @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.LONG, description = "the ID of the user used to launch and destroy the VMs") + @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.UUID, entityType = UserResponse.class, + description = "the ID of the user used to launch and destroy the VMs") private Long autoscaleUserId; private Map otherDeployParamMap; @@ -83,10 +86,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { private Long domainId; private Long accountId; - @Override - public String getEntityTable() { - return "autoscale_vmprofiles"; - } + public Long getDomainId() { if (domainId == null) { @@ -229,6 +229,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { AutoScaleVmProfile result = _autoScaleService.createAutoScaleVmProfile(this); if (result != null) { this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile"); } diff --git a/api/src/com/cloud/api/commands/CreateConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreateConditionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java index eafd8a05ab9..58926f2a4ff 100644 --- a/api/src/com/cloud/api/commands/CreateConditionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java @@ -15,25 +15,26 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ConditionResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ConditionResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.as.Condition; import com.cloud.user.UserContext; -@Implementation(description = "Creates a condition", responseObject = ConditionResponse.class) +@APICommand(name = "createCondition", description = "Creates a condition", responseObject = ConditionResponse.class) public class CreateConditionCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateConditionCmd.class.getName()); private static final String s_name = "conditionresponse"; @@ -42,8 +43,8 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "counter") - @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.LONG, required = true, description = "ID of the Counter.") + @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.UUID, entityType = CounterResponse.class, + required = true, description = "ID of the Counter.") private long counterId; @Parameter(name = ApiConstants.RELATIONAL_OPERATOR, type = CommandType.STRING, required = true, description = "Relational Operator to be used with threshold.") @@ -56,8 +57,8 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd { "Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of the account.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "the domain ID of the account.") private Long domainId; // /////////////////////////////////////////////////// @@ -71,6 +72,7 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd { if (condition != null) { this.setEntityId(condition.getId()); + this.setEntityUuid(condition.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create condition."); } @@ -145,8 +147,5 @@ public class CreateConditionCmd extends BaseAsyncCreateCmd { return accountId; } - @Override - public String getEntityTable() { - return "conditions"; - } + } diff --git a/api/src/com/cloud/api/commands/DeleteAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteAutoScalePolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java index 6d7ce5e8861..483a87ac892 100644 --- a/api/src/com/cloud/api/commands/DeleteAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java @@ -1,38 +1,38 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScalePolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Deletes a autoscale policy.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteAutoScalePolicy", description = "Deletes a autoscale policy.", responseObject = SuccessResponse.class) public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteAutoScalePolicyCmd.class.getName()); private static final String s_name = "deleteautoscalepolicyresponse"; @@ -40,8 +40,8 @@ public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale policy") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "the ID of the autoscale policy") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteAutoScaleVmGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java index 0acc09f14c0..1d78fe80395 100644 --- a/api/src/com/cloud/api/commands/DeleteAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java @@ -1,38 +1,38 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Deletes a autoscale vm group.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteAutoScaleVmGroup", description = "Deletes a autoscale vm group.", responseObject = SuccessResponse.class) public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "deleteautoscalevmgroupresponse"; @@ -40,8 +40,8 @@ public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "autoscale_vmgroups") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale group") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required = true, description = "the ID of the autoscale group") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteAutoScaleVmProfileCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java index e248c8e2050..e49f0c862a3 100644 --- a/api/src/com/cloud/api/commands/DeleteAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java @@ -1,38 +1,38 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmProfile; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Deletes a autoscale vm profile.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteAutoScaleVmProfile", description = "Deletes a autoscale vm profile.", responseObject = SuccessResponse.class) public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmProfileCmd.class.getName()); private static final String s_name = "deleteautoscalevmprofileresponse"; @@ -40,8 +40,8 @@ public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "autoscale_vmprofiles") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale profile") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the ID of the autoscale profile") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteConditionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java index 4f4914dd511..a1fba2e3725 100644 --- a/api/src/com/cloud/api/commands/DeleteConditionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java @@ -15,25 +15,25 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceInUseException; import com.cloud.network.as.Condition; import com.cloud.user.Account; -@Implementation(description = "Removes a condition", responseObject = SuccessResponse.class) +@APICommand(name = "deleteCondition", description = "Removes a condition", responseObject = SuccessResponse.class) public class DeleteConditionCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteConditionCmd.class.getName()); private static final String s_name = "deleteconditionresponse"; @@ -42,8 +42,8 @@ public class DeleteConditionCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "conditions") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the condition.") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ConditionResponse.class, + required= true, description = "the ID of the condition.") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java index bd37d0a2479..2aba82c2a93 100644 --- a/api/src/com/cloud/api/commands/DisableAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java @@ -15,24 +15,23 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; -@Implementation(description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) +@APICommand(name = "disableAutoScaleVmGroup", description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "disableautoscalevmGroupresponse"; @@ -41,8 +40,8 @@ public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="autoscale_vmgroups") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the autoscale group") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required=true, description="the ID of the autoscale group") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java index dee1d27e29c..db7acdf5d98 100644 --- a/api/src/com/cloud/api/commands/EnableAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java @@ -15,24 +15,19 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; -@Implementation(description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) +@APICommand(name = "enableAutoScaleVmGroup", description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(EnableAutoScaleVmGroupCmd.class.getName()); private static final String s_name = "enableautoscalevmGroupresponse"; @@ -41,8 +36,8 @@ public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="autoscale_vmgroups") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the autoscale group") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required=true, description="the ID of the autoscale group") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListAutoScalePoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListAutoScalePoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java index edab908977f..31621442252 100644 --- a/api/src/com/cloud/api/commands/ListAutoScalePoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java @@ -1,36 +1,37 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AutoScalePolicyResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.as.AutoScalePolicy; -@Implementation(description = "Lists autoscale policies.", responseObject = AutoScalePolicyResponse.class) +@APICommand(name = "listAutoScalePolicies", description = "Lists autoscale policies.", responseObject = AutoScalePolicyResponse.class) public class ListAutoScalePoliciesCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListAutoScalePoliciesCmd.class.getName()); @@ -40,19 +41,19 @@ public class ListAutoScalePoliciesCmd extends BaseListAccountResourcesCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the autoscale policy") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the autoscale policy") private Long id; - @IdentityMapper(entityTableName = "conditions") - @Parameter(name = ApiConstants.CONDITION_ID, type = CommandType.LONG, description = "the ID of the condition of the policy") + @Parameter(name = ApiConstants.CONDITION_ID, type = CommandType.UUID, entityType = ConditionResponse.class, + description = "the ID of the condition of the policy") private Long conditionId; @Parameter(name = ApiConstants.ACTION, type = CommandType.STRING, description = "the action to be executed if all the conditions evaluate to true for the specified duration.") private String action; - @IdentityMapper(entityTableName="autoscale_vmgroups") - @Parameter(name = ApiConstants.VMGROUP_ID, type = CommandType.LONG, description = "the ID of the autoscale vm group") + @Parameter(name = ApiConstants.VMGROUP_ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + description = "the ID of the autoscale vm group") private Long vmGroupId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java index 0d1b2e00b11..7561757fcab 100644 --- a/api/src/com/cloud/api/commands/ListAutoScaleVmGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java @@ -1,37 +1,40 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AutoScaleVmGroupResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.as.AutoScaleVmGroup; -@Implementation(description = "Lists autoscale vm groups.", responseObject = AutoScaleVmGroupResponse.class) +@APICommand(name = "listAutoScaleVmGroups", description = "Lists autoscale vm groups.", responseObject = AutoScaleVmGroupResponse.class) public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmGroupsCmd.class.getName()); @@ -41,24 +44,24 @@ public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResources // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="autoscale_vmgroups") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the autoscale vm group") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + description = "the ID of the autoscale vm group") private Long id; - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, description = "the ID of the loadbalancer") + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + description = "the ID of the loadbalancer") private Long loadBalancerId; - @IdentityMapper(entityTableName="autoscale_vmprofiles") - @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.LONG, description = "the ID of the profile") + @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + description = "the ID of the profile") private Long profileId; - @IdentityMapper(entityTableName="autoscale_policies") - @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.LONG, description = "the ID of the policy") + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the policy") private Long policyId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the availability zone ID") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the availability zone ID") private Long zoneId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// diff --git a/api/src/com/cloud/api/commands/ListAutoScaleVmProfilesCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListAutoScaleVmProfilesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java index 80348006b85..7a88db3e7b9 100644 --- a/api/src/com/cloud/api/commands/ListAutoScaleVmProfilesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java @@ -1,36 +1,36 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AutoScaleVmProfileResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.as.AutoScaleVmProfile; -@Implementation(description = "Lists autoscale vm profiles.", responseObject = AutoScaleVmProfileResponse.class) +@APICommand(name = "listAutoScaleVmProfiles", description = "Lists autoscale vm profiles.", responseObject = AutoScaleVmProfileResponse.class) public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmProfilesCmd.class.getName()); @@ -40,12 +40,12 @@ public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourc // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="autoscale_vmprofiles") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the autoscale vm profile") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + description = "the ID of the autoscale vm profile") private Long id; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, description="the templateid of the autoscale vm profile") + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + description="the templateid of the autoscale vm profile") private Long templateId; @Parameter(name=ApiConstants.OTHER_DEPLOY_PARAMS, type=CommandType.STRING, description="the otherdeployparameters of the autoscale vm profile") diff --git a/api/src/com/cloud/api/commands/ListConditionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListConditionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java index 4d50b8bf368..0b3ffec040c 100644 --- a/api/src/com/cloud/api/commands/ListConditionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java @@ -15,24 +15,24 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ConditionResponse; -import com.cloud.api.response.CounterResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.as.Condition; -@Implementation(description = "List Conditions for the specific user", responseObject = CounterResponse.class) +@APICommand(name = "listConditions", description = "List Conditions for the specific user", responseObject = CounterResponse.class) public class ListConditionsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListConditionsCmd.class.getName()); private static final String s_name = "listconditionsresponse"; @@ -41,16 +41,16 @@ public class ListConditionsCmd extends BaseListAccountResourcesCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "conditions") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = false, description = "ID of the Condition.") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ConditionResponse.class, + required = false, description = "ID of the Condition.") private Long id; - @IdentityMapper(entityTableName = "counter") - @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.LONG, required = false, description = "Counter-id of the condition.") + @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.UUID, entityType = CounterResponse.class, + required = false, description = "Counter-id of the condition.") private Long counterId; - @IdentityMapper(entityTableName="autoscale_policies") - @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.LONG, description = "the ID of the policy") + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the policy") private Long policyId; // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// diff --git a/api/src/com/cloud/api/commands/ListCountersCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/ListCountersCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java index 60108ca22b8..66a38f34396 100644 --- a/api/src/com/cloud/api/commands/ListCountersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java @@ -15,24 +15,23 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.CounterResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.as.Counter; import com.cloud.user.Account; -@Implementation(description = "List the counters", responseObject = CounterResponse.class) +@APICommand(name = "listCounters", description = "List the counters", responseObject = CounterResponse.class) public class ListCountersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListCountersCmd.class.getName()); private static final String s_name = "counterresponse"; @@ -41,8 +40,8 @@ public class ListCountersCmd extends BaseListCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "counter") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "ID of the Counter.") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = CounterResponse.class, + description = "ID of the Counter.") private Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "Name of the counter.") diff --git a/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java index baefcffd164..56d71078ece 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScalePolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java @@ -15,27 +15,27 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; +import org.apache.cloudstack.api.response.ConditionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScalePolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Updates an existing autoscale policy.", responseObject = AutoScalePolicyResponse.class) +@APICommand(name = "updateAutoScalePolicy", description = "Updates an existing autoscale policy.", responseObject = AutoScalePolicyResponse.class) public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateAutoScalePolicyCmd.class.getName()); @@ -51,12 +51,12 @@ public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.QUIETTIME, type = CommandType.INTEGER, description = "the cool down period for which the policy should not be evaluated after the action has been taken") private Integer quietTime; - @IdentityMapper(entityTableName = "conditions") - @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "the list of IDs of the conditions that are being evaluated on every interval") + @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ConditionResponse.class, + description = "the list of IDs of the conditions that are being evaluated on every interval") private List conditionIds; - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale policy") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "the ID of the autoscale policy") private Long id; @Override diff --git a/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java index f71a9880f33..ea5b6a9f489 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScaleVmGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java @@ -15,27 +15,23 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Updates an existing autoscale vm group.", responseObject = AutoScaleVmGroupResponse.class) +@APICommand(name = "updateAutoScaleVmGroup", description = "Updates an existing autoscale vm group.", responseObject = AutoScaleVmGroupResponse.class) public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmGroupCmd.class.getName()); @@ -54,16 +50,16 @@ public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.INTERVAL, type=CommandType.INTEGER, description="the frequency at which the conditions have to be evaluated") private Integer interval; - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "list of scaleup autoscale policies") + @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "list of scaleup autoscale policies") private List scaleUpPolicyIds; - @IdentityMapper(entityTableName = "autoscale_policies") - @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "list of scaledown autoscale policies") + @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "list of scaledown autoscale policies") private List scaleDownPolicyIds; - @IdentityMapper(entityTableName = "autoscale_vmgroups") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale group") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required = true, description = "the ID of the autoscale group") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java rename to api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java index c94dad4dd3e..c8ef8b11198 100644 --- a/api/src/com/cloud/api/commands/UpdateAutoScaleVmProfileCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java @@ -15,27 +15,24 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.autoscale; import java.util.Map; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.as.AutoScaleVmProfile; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Updates an existing autoscale vm profile.", responseObject = AutoScaleVmProfileResponse.class) +@APICommand(name = "updateAutoScaleVmProfile", description = "Updates an existing autoscale vm profile.", responseObject = AutoScaleVmProfileResponse.class) public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmProfileCmd.class.getName()); @@ -45,12 +42,12 @@ public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "autoscale_vmprofiles") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the autoscale vm profile") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the ID of the autoscale vm profile") private Long id; - @IdentityMapper(entityTableName = "vm_template") - @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.LONG, description = "the template of the auto deployed virtual machine") + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, + description = "the template of the auto deployed virtual machine") private Long templateId; @Parameter(name = ApiConstants.AUTOSCALE_VM_DESTROY_TIME, type = CommandType.INTEGER, description = "the time allowed for existing connections to get closed before a vm is destroyed") @@ -59,8 +56,8 @@ public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.COUNTERPARAM_LIST, type = CommandType.MAP, description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161") private Map counterParamList; - @IdentityMapper(entityTableName = "user") - @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.LONG, description = "the ID of the user used to launch and destroy the VMs") + @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.UUID, entityType = UserResponse.class, + description = "the ID of the user used to launch and destroy the VMs") private Long autoscaleUserId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java index 108b268ae5d..129aeb85d24 100644 --- a/api/src/com/cloud/api/commands/ListCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.config; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.CapabilitiesResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.CapabilitiesResponse; import com.cloud.user.Account; -@Implementation(description="Lists capabilities", responseObject=CapabilitiesResponse.class) +@APICommand(name = "listCapabilities", description="Lists capabilities", responseObject=CapabilitiesResponse.class) public class ListCapabilitiesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); private static final String s_name = "listcapabilitiesresponse"; @@ -35,12 +35,12 @@ public class ListCapabilitiesCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Map capabilities = _mgr.listCapabilities(this); diff --git a/api/src/com/cloud/api/commands/ListEventTypesCmd.java b/api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/ListEventTypesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java index cd1d1291f21..4c432f35ebb 100644 --- a/api/src/com/cloud/api/commands/ListEventTypesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.event; import java.util.ArrayList; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.EventTypeResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.EventTypeResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.user.Account; -@Implementation(description = "List Event Types", responseObject = EventTypeResponse.class) +@APICommand(name = "listEventTypes", description = "List Event Types", responseObject = EventTypeResponse.class) public class ListEventTypesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListEventTypesCmd.class.getName()); private static final String s_name = "listeventtypesresponse"; diff --git a/api/src/com/cloud/api/commands/ListEventsCmd.java b/api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/commands/ListEventsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java index 512d377fabd..94205d13226 --- a/api/src/com/cloud/api/commands/ListEventsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java @@ -14,24 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.event; -import java.util.ArrayList; import java.util.Date; -import java.util.List; - import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.event.Event; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ListResponse; -@Implementation(description="A command to list events.", responseObject=EventResponse.class) +@APICommand(name = "listEvents", description="A command to list events.", responseObject=EventResponse.class) public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListEventsCmd.class.getName()); @@ -41,10 +36,10 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="event") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the event") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = EventResponse.class, + description="the ID of the event") private Long id; - + @Parameter(name=ApiConstants.DURATION, type=CommandType.INTEGER, description="the duration of the event") private Integer duration; @@ -70,7 +65,7 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { public Long getId() { return id; } - + public Integer getDuration() { return duration; } @@ -106,14 +101,8 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { @Override public void execute(){ - List result = _mgr.searchForEvents(this); - ListResponse response = new ListResponse(); - List eventResponses = new ArrayList(); - for (Event event : result) { - eventResponses.add(_responseGenerator.createEventResponse(event)); - } - response.setResponses(eventResponses); + ListResponse response = _queryService.searchForEvents(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java index 937e9aa91e5..7039b417ced 100644 --- a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +41,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description = "Creates a firewall rule for a given ip address", responseObject = FirewallResponse.class) +@APICommand(name = "createFirewallRule", description = "Creates a firewall rule for a given ip address", responseObject = FirewallResponse.class) public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements FirewallRule { public static final Logger s_logger = Logger.getLogger(CreateFirewallRuleCmd.class.getName()); @@ -51,8 +51,8 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.LONG, required=true, description = "the IP address id of the port forwarding rule") + @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description = "the IP address id of the port forwarding rule") private Long ipAddressId; @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the firewall rule. Valid values are TCP/UDP/ICMP.") @@ -63,26 +63,23 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of firewall rule") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "type of firewallrule: system/user") private String type; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - - public String getEntityTable() { - return "firewall_rules"; - } + public Long getIpAddressId() { return ipAddressId; @@ -101,7 +98,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal oneCidrList.add(NetUtils.ALL_CIDRS); return oneCidrList; } - + } // /////////////////////////////////////////////////// @@ -112,7 +109,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -128,7 +125,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal // State is different after the rule is applied, so get new object here rule = _entityMgr.findById(FirewallRule.class, getEntityId()); - FirewallResponse fwResponse = new FirewallResponse(); + FirewallResponse fwResponse = new FirewallResponse(); if (rule != null) { fwResponse = _responseGenerator.createFirewallResponse(rule); setResponseObject(fwResponse); @@ -153,6 +150,13 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return ipAddressId; @@ -175,7 +179,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } else { return publicEndPort.intValue(); } - + return null; } @@ -193,13 +197,13 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -227,7 +231,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -235,6 +239,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal try { FirewallRule result = _firewallService.createFirewallRule(this); setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); @@ -276,7 +281,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return ip; } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -286,14 +291,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { return -1; - + } return null; } @@ -303,20 +308,20 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } - @Override - public FirewallRuleType getType() { - if (type != null && type.equalsIgnoreCase("system")) { - return FirewallRuleType.System; - } else { - return FirewallRuleType.User; - } - } - + @Override + public FirewallRuleType getType() { + if (type != null && type.equalsIgnoreCase("system")) { + return FirewallRuleType.System; + } else { + return FirewallRuleType.User; + } + } + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java index 3f3915a705d..1feefde9a1a 100644 --- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +37,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.Ip; -@Implementation(description = "Creates a port forwarding rule", responseObject = FirewallRuleResponse.class) +@APICommand(name = "createPortForwardingRule", description = "Creates a port forwarding rule", responseObject = FirewallRuleResponse.class) public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements PortForwardingRule { public static final Logger s_logger = Logger.getLogger(CreatePortForwardingRuleCmd.class.getName()); @@ -50,31 +47,31 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "user_ip_address") - @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.LONG, required = true, + @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + required = true, description = "the IP address id of the port forwarding rule") private Long ipAddressId; - @Parameter(name = ApiConstants.PRIVATE_START_PORT, type = CommandType.INTEGER, required = true, + @Parameter(name = ApiConstants.PRIVATE_START_PORT, type = CommandType.INTEGER, required = true, description = "the starting port of port forwarding rule's private port range") private Integer privateStartPort; - @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, + @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the port fowarding rule. Valid values are TCP or UDP.") private String protocol; @Parameter(name = ApiConstants.PRIVATE_END_PORT, type = CommandType.INTEGER, required = false, description = "the ending port of port forwarding rule's private port range") private Integer privateEndPort; - @Parameter(name = ApiConstants.PUBLIC_START_PORT, type = CommandType.INTEGER, required = true, + @Parameter(name = ApiConstants.PUBLIC_START_PORT, type = CommandType.INTEGER, required = true, description = "the starting port of port forwarding rule's public port range") private Integer publicStartPort; - + @Parameter(name = ApiConstants.PUBLIC_END_PORT, type = CommandType.INTEGER, required = false, description = "the ending port of port forwarding rule's private port range") private Integer publicEndPort; - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, required = true, + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, + required = true, description = "the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; @@ -82,25 +79,21 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P description = "the cidr list to forward traffic from") private List cidrlist; - @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; " + - "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + - " rule is being created for VPC guest network 2) in all other cases defaulted to true") + "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network of the vm the Port Forwarding rule will be created for. " + - "Required when public Ip address is not associated with any Guest network yet (VPC case)") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="The network of the vm the Port Forwarding rule will be created for. " + + "Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - public String getEntityTable() { - return "firewall_rules"; - } public Long getIpAddressId() { return ipAddressId; @@ -119,11 +112,11 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall " + - "rule for the specific cidr, please refer to createFirewallRule command"); + "rule for the specific cidr, please refer to createFirewallRule command"); } return null; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { @@ -138,7 +131,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return true; } } - + private Long getVpcId() { if (ipAddressId != null) { IpAddress ipAddr = _networkService.getIp(ipAddressId); @@ -168,16 +161,16 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P PortForwardingRule rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(ipAddressId, callerContext.getCaller()); } - + success = success && _rulesService.applyPortForwardingRules(ipAddressId, callerContext.getCaller()); // State is different after the rule is applied, so get new object here rule = _entityMgr.findById(PortForwardingRule.class, getEntityId()); - FirewallRuleResponse fwResponse = new FirewallRuleResponse(); + FirewallRuleResponse fwResponse = new FirewallRuleResponse(); if (rule != null) { fwResponse = _responseGenerator.createPortForwardingRuleResponse(rule); setResponseObject(fwResponse); @@ -185,13 +178,13 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P fwResponse.setResponseName(getCommandName()); } finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokePortForwardingRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply port forwarding rule"); } } @@ -208,6 +201,13 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return ipAddressId; @@ -220,7 +220,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @Override public Integer getSourcePortEnd() { - return (publicEndPort == null)? publicStartPort.intValue() : publicEndPort.intValue(); + return (publicEndPort == null)? publicStartPort.intValue() : publicEndPort.intValue(); } @Override @@ -237,14 +237,14 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { ntwkId = networkId; } if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -272,10 +272,10 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public Ip getDestinationIpAddress() { return null; } - + @Override public void setDestinationIpAddress(Ip destinationIpAddress) { - return; + return; } @Override @@ -294,10 +294,11 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } - + try { PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, getOpenFirewall()); setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " , ex); s_logger.trace("Network Rule Conflict: ", ex); @@ -339,26 +340,26 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } @Override public AsyncJob.Type getInstanceType() { diff --git a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java index 36ae4aa3a15..5655b5e430f 100644 --- a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a firewall rule", responseObject=SuccessResponse.class) +@APICommand(name = "deleteFirewallRule", description="Deletes a firewall rule", responseObject=SuccessResponse.class) public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteFirewallRuleCmd.class.getName()); private static final String s_name = "deletefirewallruleresponse"; @@ -42,13 +39,13 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the firewall rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the firewall rule") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +54,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +62,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -75,7 +72,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting firewall rule id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +85,12 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Rule Id: " + id); boolean result = _firewallService.revokeFirewallRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +98,8 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete firewall rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,7 +109,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java index ed2c32a279f..8f4d5996df8 100644 --- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java @@ -14,25 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.PortForwardingRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a port forwarding rule", responseObject=SuccessResponse.class) +@APICommand(name = "deletePortForwardingRule", description="Deletes a port forwarding rule", responseObject=SuccessResponse.class) public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); private static final String s_name = "deleteportforwardingruleresponse"; @@ -41,13 +38,13 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the port forwarding rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the port forwarding rule") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -56,7 +53,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +61,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_NET_RULE_DELETE; @@ -74,7 +71,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting port forwarding rule for id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -84,18 +81,18 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { } else { ownerId = _entityMgr.findById(PortForwardingRule.class, id).getAccountId(); } - + } return ownerId; } - + @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); //revoke corresponding firewall rule first boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _rulesService.revokePortForwardingRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -103,8 +100,8 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete port forwarding rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,7 +111,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getPortForwardigRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/ListFirewallRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListFirewallRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java index c136266b85f..80581fb7d3b 100644 --- a/api/src/com/cloud/api/commands/ListFirewallRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.FirewallRule; import com.cloud.utils.Pair; -@Implementation(description="Lists all firewall rules for an IP address.", responseObject=FirewallResponse.class) +@APICommand(name = "listFirewallRules", description="Lists all firewall rules for an IP address.", responseObject=FirewallResponse.class) public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListFirewallRulesCmd.class.getName()); private static final String s_name = "listfirewallrulesresponse"; @@ -39,22 +40,22 @@ public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="the id of IP address of the firwall services") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="the id of IP address of the firwall services") private Long ipAddressId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getIpAddressId() { return ipAddressId; } - + public Long getId() { return id; } @@ -67,13 +68,13 @@ public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _firewallService.listFirewallRules(this); ListResponse response = new ListResponse(); List fwResponses = new ArrayList(); - + for (FirewallRule fwRule : result.first()) { FirewallResponse ruleData = _responseGenerator.createFirewallResponse(fwRule); ruleData.setObjectName("firewallrule"); @@ -81,6 +82,6 @@ public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { } response.setResponses(fwResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java index 0315a12d1a5..665af44ad96 100644 --- a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java @@ -14,49 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.PortForwardingRule; import com.cloud.utils.Pair; -@Implementation(description="Lists all port forwarding rules for an IP address.", responseObject=FirewallRuleResponse.class) -public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListPortForwardingRulesCmd.class.getName()); - - private static final String s_name = "listportforwardingrulesresponse"; - +@APICommand(name = "listPortForwardingRules", description="Lists all port forwarding rules for an IP address.", responseObject=FirewallRuleResponse.class) +public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListPortForwardingRulesCmd.class.getName()); + + private static final String s_name = "listportforwardingrulesresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="the id of IP address of the port forwarding services") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="the id of IP address of the port forwarding services") private Long ipAddressId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getIpAddressId() { return ipAddressId; } - + public Long getId() { return id; } @@ -69,13 +69,13 @@ public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _rulesService.listPortForwardingRules(this); ListResponse response = new ListResponse(); List fwResponses = new ArrayList(); - + for (PortForwardingRule fwRule : result.first()) { FirewallRuleResponse ruleData = _responseGenerator.createPortForwardingRuleResponse(fwRule); ruleData.setObjectName("portforwardingrule"); @@ -83,6 +83,6 @@ public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { } response.setResponses(fwResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java index 37da43a2200..a52ebb77257 100644 --- a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.event.EventTypes; import com.cloud.network.IpAddress; import com.cloud.user.Account; -@Implementation(responseObject=FirewallRuleResponse.class, description="Updates a port forwarding rule. Only the private port and the virtual machine can be updated.") +@APICommand(name = "updatePortForwardingRule", responseObject=FirewallRuleResponse.class, description="Updates a port forwarding rule. Only the private port and the virtual machine can be updated.") public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdatePortForwardingRuleCmd.class.getName()); private static final String s_name = "updateportforwardingruleresponse"; @@ -46,15 +47,15 @@ public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the port fowarding rule. Valid values are TCP or UDP.") private String protocol; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the IP address id of the port forwarding rule") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the IP address id of the port forwarding rule") private Long publicIpId; @Parameter(name=ApiConstants.PUBLIC_PORT, type=CommandType.STRING, required=true, description="the public port of the port forwarding rule") private String publicPort; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine for the port forwarding rule") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java index 79ce7097d8a..3b4c4cd2c34 100644 --- a/api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.guest; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GuestOSCategoryResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.storage.GuestOsCategory; import com.cloud.utils.Pair; -@Implementation(description="Lists all supported OS categories for this cloud.", responseObject=GuestOSCategoryResponse.class) +@APICommand(name = "listOsCategories", description="Lists all supported OS categories for this cloud.", responseObject=GuestOSCategoryResponse.class) public class ListGuestOsCategoriesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -41,10 +41,10 @@ public class ListGuestOsCategoriesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list Os category by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="list Os category by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list os category by name", since="3.0.1") private String name; @@ -70,7 +70,7 @@ public class ListGuestOsCategoriesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _mgr.listGuestOSCategoriesByCriteria(this); @@ -78,7 +78,7 @@ public class ListGuestOsCategoriesCmd extends BaseListCmd { List osCatResponses = new ArrayList(); for (GuestOsCategory osCategory : result.first()) { GuestOSCategoryResponse categoryResponse = new GuestOSCategoryResponse(); - categoryResponse.setId(osCategory.getId()); + categoryResponse.setId(osCategory.getUuid()); categoryResponse.setName(osCategory.getName()); categoryResponse.setObjectName("oscategory"); diff --git a/api/src/com/cloud/api/commands/ListGuestOsCmd.java b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListGuestOsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java index 61ec453b83c..3c145e9bd95 100644 --- a/api/src/com/cloud/api/commands/ListGuestOsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.guest; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GuestOSResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.storage.GuestOS; import com.cloud.utils.Pair; -@Implementation(description="Lists all supported OS types for this cloud.", responseObject=GuestOSResponse.class) +@APICommand(name = "listOsTypes", description="Lists all supported OS types for this cloud.", responseObject=GuestOSResponse.class) public class ListGuestOsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -41,14 +42,14 @@ public class ListGuestOsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list by Os type Id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="list by Os type Id") private Long id; - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.LONG, description="list by Os Category id") + @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="list by Os Category id") private Long osCategoryId; - + @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="list os by description", since="3.0.1") private String description; @@ -68,7 +69,7 @@ public class ListGuestOsCmd extends BaseListCmd { public String getDescription() { return description; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -77,19 +78,14 @@ public class ListGuestOsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _mgr.listGuestOSByCriteria(this); ListResponse response = new ListResponse(); List osResponses = new ArrayList(); for (GuestOS guestOS : result.first()) { - GuestOSResponse guestOSResponse = new GuestOSResponse(); - guestOSResponse.setDescription(guestOS.getDisplayName()); - guestOSResponse.setId(guestOS.getId()); - guestOSResponse.setOsCategoryId(guestOS.getCategoryId()); - - guestOSResponse.setObjectName("ostype"); + GuestOSResponse guestOSResponse = _responseGenerator.createGuestOSResponse(guestOS); osResponses.add(guestOSResponse); } diff --git a/api/src/com/cloud/api/commands/AttachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/AttachIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java index 75f2ac71e99..1e154e2a07d --- a/api/src/com/cloud/api/commands/AttachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Attaches an ISO to a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "attachIso", description="Attaches an ISO to a virtual machine.", responseObject=UserVmResponse.class) public class AttachIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AttachIsoCmd.class.getName()); @@ -41,12 +42,12 @@ public class AttachIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; @@ -71,14 +72,14 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm vm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); if (vm == null) { throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId()); - } - + } + return vm.getAccountId(); } @@ -91,16 +92,16 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching ISO: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); + UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); boolean result = _templateService.attachIso(id, virtualMachineId); if (result) { UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId); if (userVm != null) { - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to attach iso"); diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java new file mode 100644 index 00000000000..b449ff59180 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.iso; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd; + +@APICommand(name = "copyIso", description="Copies an iso from one zone to another.", responseObject=TemplateResponse.class) +public class CopyIsoCmd extends CopyTemplateCmd { + public static final Logger s_logger = Logger.getLogger(CopyIsoCmd.class.getName()); + private static final String s_name = "copyisoresponse"; +} + diff --git a/api/src/com/cloud/api/commands/DeleteIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/DeleteIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java index 70ce7312c49..44efbf88f2c --- a/api/src/com/cloud/api/commands/DeleteIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes an ISO file.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteIso", description="Deletes an ISO file.", responseObject=SuccessResponse.class) public class DeleteIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteIsoCmd.class.getName()); private static final String s_name = "deleteisosresponse"; @@ -41,12 +42,12 @@ public class DeleteIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones") private Long zoneId; @@ -70,11 +71,11 @@ public class DeleteIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getStaticName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate iso = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -94,18 +95,18 @@ public class DeleteIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting iso " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("ISO Id: "+getId()); + UserContext.current().setEventDetails("ISO Id: "+getId()); boolean result = _templateService.deleteIso(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DetachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/DetachIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java index af318d7537c..eb1c6eed2d6 --- a/api/src/com/cloud/api/commands/DetachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.uservm.UserVm; -@Implementation(description="Detaches any ISO file (if any) currently attached to a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "detachIso", description="Detaches any ISO file (if any) currently attached to a virtual machine.", responseObject=UserVmResponse.class) public class DetachIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DetachIsoCmd.class.getName()); @@ -40,8 +41,8 @@ public class DetachIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="The ID of the virtual machine") private Long virtualMachineId; ///////////////////////////////////////////////////// @@ -68,7 +69,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { return vm.getAccountId(); } else { throw new InvalidParameterValueException("Unable to find vm by id " + getVirtualMachineId()); - } + } } @Override @@ -80,14 +81,14 @@ public class DetachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "detaching ISO from vm: " + getVirtualMachineId(); } - + @Override public void execute(){ boolean result = _templateService.detachIso(virtualMachineId); if (result) { - UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId); - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId); + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach iso"); diff --git a/api/src/com/cloud/api/commands/ExtractIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/ExtractIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java index a9fb606bb08..5f8303ec320 --- a/api/src/com/cloud/api/commands/ExtractIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InternalErrorException; @@ -33,9 +30,9 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts an ISO", responseObject=ExtractResponse.class) +@APICommand(name = "extractIso", description="Extracts an ISO", responseObject=ExtractResponse.class) public class ExtractIsoCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractIsoCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractIsoCmd.class.getName()); private static final String s_name = "extractisoresponse"; @@ -43,17 +40,17 @@ public class ExtractIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the ISO would be extracted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="the ID of the zone where the ISO is originally located") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="the ID of the zone where the ISO is originally located") private Long zoneId; - + @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; @@ -109,19 +106,19 @@ public class ExtractIsoCmd extends BaseAsyncCmd { public static String getStaticName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); Long uploadId = _templateService.extract(this); if (uploadId != null){ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode); diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java new file mode 100644 index 00000000000..0ca711f4664 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java @@ -0,0 +1,46 @@ +// Licensedname = "listIsoPermissions", to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.iso; + +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.log4j.Logger; + +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.template.VirtualMachineTemplate; + +@APICommand(name="listIsoPermissions", description="List iso visibility and all accounts that have permissions to view this iso.", responseObject=TemplatePermissionsResponse.class) +public class ListIsoPermissionsCmd extends BaseListTemplateOrIsoPermissionsCmd { + protected String getResponseName() { + return "listisopermissionsresponse"; + } + + @Override + public String getMediaType() { + return "iso"; + } + + @Override + protected Logger getLogger() { + return Logger.getLogger(ListIsoPermissionsCmd.class.getName()); + } + + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { + return template.getFormat().equals(ImageFormat.ISO); + } +} diff --git a/api/src/com/cloud/api/commands/ListIsosCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/commands/ListIsosCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java index 752c834f81b..e6ccfff3449 --- a/api/src/com/cloud/api/commands/ListIsosCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java @@ -14,28 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import java.util.ArrayList; import java.util.List; import java.util.Set; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.async.AsyncJob; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.Pair; -@Implementation(description="Lists all available ISO files.", responseObject=TemplateResponse.class) +@APICommand(name = "listIsos", description="Lists all available ISO files.", responseObject=TemplateResponse.class) public class ListIsosCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -51,8 +51,8 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list all isos by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + description="list all isos by id") private Long id; @Parameter(name=ApiConstants.IS_PUBLIC, type=CommandType.BOOLEAN, description="true if the ISO is publicly available to all users, false otherwise.") @@ -62,19 +62,19 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { private Boolean ready; @Parameter(name=ApiConstants.ISO_FILTER, type=CommandType.STRING, description="possible values are \"featured\", \"self\", \"self-executable\",\"executable\", and \"community\". " + - "* featured-ISOs that are featured and are publicself-ISOs that have been registered/created by the owner. " + - "* selfexecutable-ISOs that have been registered/created by the owner that can be used to deploy a new VM. " + - "* executable-all ISOs that can be used to deploy a new VM " + - "* community-ISOs that are public.") + "* featured-ISOs that are featured and are publicself-ISOs that have been registered/created by the owner. " + + "* selfexecutable-ISOs that have been registered/created by the owner that can be used to deploy a new VM. " + + "* executable-all ISOs that can be used to deploy a new VM " + + "* community-ISOs that are public.") private String isoFilter = TemplateFilter.selfexecutable.toString(); @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list all isos by name") private String isoName; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of the zone") private Long zoneId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -111,7 +111,7 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public boolean listInReadyState() { Account account = UserContext.current().getCaller(); // It is account specific if account is admin type and domainId and accountName are not null @@ -120,29 +120,29 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { TemplateFilter templateFilter = TemplateFilter.valueOf(getIsoFilter()); boolean onlyReady = (templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.selfexecutable) || (templateFilter == TemplateFilter.sharedexecutable) || (templateFilter == TemplateFilter.executable && isAccountSpecific) || (templateFilter == TemplateFilter.community); - + if (!onlyReady) { - if (isReady() != null && isReady().booleanValue() != onlyReady) { - onlyReady = isReady().booleanValue(); - } + if (isReady() != null && isReady().booleanValue() != onlyReady) { + onlyReady = isReady().booleanValue(); + } } - + return onlyReady; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + @Override public void execute(){ Set> isoZonePairSet = _mgr.listIsos(this); diff --git a/api/src/com/cloud/api/commands/RegisterIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/RegisterIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java index 34554772c4b..214d18de5cc --- a/api/src/com/cloud/api/commands/RegisterIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java @@ -14,28 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=TemplateResponse.class, description="Registers an existing ISO into the CloudStack Cloud.") +@APICommand(name = "registerIso", responseObject=TemplateResponse.class, description="Registers an existing ISO into the CloudStack Cloud.") public class RegisterIsoCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterIsoCmd.class.getName()); @@ -59,35 +56,35 @@ public class RegisterIsoCmd extends BaseCmd { @Parameter(name=ApiConstants.IS_EXTRACTABLE, type=CommandType.BOOLEAN, description="true if the iso or its derivatives are extractable; default is false") private Boolean extractable; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the ISO") private String isoName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS Type that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="the ID of the OS Type that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed") private Long osTypeId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL to where the ISO is currently being hosted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone you wish to register the ISO to.") - private Long zoneId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone you wish to register the ISO to.") + private Long zoneId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") private Long domainId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account name. Must be used with domainId.") private String accountName; - + @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this ISO") private String checksum; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Register iso for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Register iso for the project") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -111,7 +108,7 @@ public class RegisterIsoCmd extends BaseCmd { public Boolean isExtractable() { return extractable; } - + public String getIsoName() { return isoName; } @@ -129,36 +126,36 @@ public class RegisterIsoCmd extends BaseCmd { } public Long getDomainId() { - return domainId; - } + return domainId; + } - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } public String getChecksum() { return checksum; - } - + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } - + } + @Override public void execute() throws ResourceAllocationException{ VirtualMachineTemplate template = _templateService.registerIso(this); @@ -166,11 +163,11 @@ public class RegisterIsoCmd extends BaseCmd { ListResponse response = new ListResponse(); List templateResponses = _responseGenerator.createIsoResponses(template.getId(), zoneId, false); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register iso"); } - + } } diff --git a/api/src/com/cloud/api/commands/UpdateIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/commands/UpdateIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java index 92417912cc9..f54f8a66daa --- a/api/src/com/cloud/api/commands/UpdateIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java @@ -14,31 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates an ISO file.", responseObject=TemplateResponse.class) -public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { +@APICommand(name = "updateIso", description="Updates an ISO file.", responseObject=TemplateResponse.class) +public class UpdateIsoCmd extends BaseUpdateTemplateOrIsoCmd { public static final Logger s_logger = Logger.getLogger(UpdateIsoCmd.class.getName()); private static final String s_name = "updateisoresponse"; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + @Override public Boolean isPasswordEnabled() { return null; } - + @Override public String getFormat() { return null; @@ -52,7 +53,7 @@ public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -62,7 +63,7 @@ public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualMachineTemplate result = _mgr.updateTemplate(this); diff --git a/api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java index 7173d91bb87..b7a2c5685e0 100644 --- a/api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; import org.apache.log4j.Logger; -import com.cloud.api.Implementation; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates iso permissions", responseObject=SuccessResponse.class) -public class UpdateIsoPermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd { +@APICommand(name = "updateIsoPermissions", description="Updates iso permissions", responseObject=SuccessResponse.class) +public class UpdateIsoPermissionsCmd extends BaseUpdateTemplateOrIsoPermissionsCmd { protected String getResponseName() { - return "updateisopermissionsresponse"; + return "updateisopermissionsresponse"; + } + + protected Logger getLogger() { + return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName()); } - protected Logger getLogger() { - return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName()); - } - @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); diff --git a/api/src/com/cloud/api/commands/ListAsyncJobsCmd.java b/api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListAsyncJobsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java index e0520cd63a9..50ac52e025f 100644 --- a/api/src/com/cloud/api/commands/ListAsyncJobsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.job; import java.util.ArrayList; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.async.AsyncJob; import com.cloud.utils.Pair; -@Implementation(description="Lists all pending asynchronous jobs for the account.", responseObject=AsyncJobResponse.class) +@APICommand(name = "listAsyncJobs", description="Lists all pending asynchronous jobs for the account.", responseObject=AsyncJobResponse.class) public class ListAsyncJobsCmd extends BaseListAccountResourcesCmd { private static final String s_name = "listasyncjobsresponse"; @@ -59,15 +60,10 @@ public class ListAsyncJobsCmd extends BaseListAccountResourcesCmd { @Override public void execute(){ - Pair, Integer> result = _mgr.searchForAsyncJobs(this); - ListResponse response = new ListResponse(); - List jobResponses = new ArrayList(); - for (AsyncJob job : result.first()) { - jobResponses.add(_responseGenerator.createAsyncJobResponse(job)); - } - response.setResponses(jobResponses, result.second()); + ListResponse response = _queryService.searchForAsyncJobs(this); response.setResponseName(getCommandName()); this.setResponseObject(response); + } } diff --git a/api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java b/api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java rename to api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java index d011a7eb571..256d4ff5cc3 100644 --- a/api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java @@ -14,19 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.job; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AsyncJobResponse; import com.cloud.user.Account; -@Implementation(description="Retrieves the current status of asynchronous job.", responseObject=AsyncJobResponse.class) +@APICommand(name = "queryAsyncJobResult", description="Retrieves the current status of asynchronous job.", responseObject=AsyncJobResponse.class) public class QueryAsyncJobResultCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(QueryAsyncJobResultCmd.class.getName()); @@ -36,8 +35,8 @@ public class QueryAsyncJobResultCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="async_job") - @Parameter(name=ApiConstants.JOB_ID, type=CommandType.LONG, required=true, description="the ID of the asychronous job") + @Parameter(name=ApiConstants.JOB_ID, type=CommandType.UUID, entityType=AsyncJobResponse.class, + required=true, description="the ID of the asychronous job") private Long id; ///////////////////////////////////////////////////// @@ -56,12 +55,12 @@ public class QueryAsyncJobResultCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ AsyncJobResponse response = _responseGenerator.queryJobResult(this); diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java index 2a88e878597..972673f4954 100644 --- a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.LoadBalancer; @@ -35,7 +36,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(description="Assigns virtual machine or a list of virtual machines to a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "assignToLoadBalancerRule", description="Assigns virtual machine or a list of virtual machines to a load balancer rule.", responseObject=SuccessResponse.class) public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AssignToLoadBalancerRuleCmd.class.getName()); @@ -45,12 +46,12 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, required=true, description="the list of IDs of the virtual machine that are being assigned to the load balancer rule(i.e. virtualMachineIds=1,2,3)") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the list of IDs of the virtual machine that are being assigned to the load balancer rule(i.e. virtualMachineIds=1,2,3)") private List virtualMachineIds; ///////////////////////////////////////////////////// @@ -92,7 +93,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "applying instances for load balancer: " + getLoadBalancerId() + " (ids: " + StringUtils.join(getVirtualMachineIds(), ",") + ")"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getLoadBalancerId()+" VmIds: "+StringUtils.join(getVirtualMachineIds(), ",")); @@ -104,7 +105,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,10 +113,10 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java index c2410c882fa..c01e138c1d1 100644 --- a/api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.Map; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.event.EventTypes; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.StickinessPolicy; -import com.cloud.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates a Load Balancer stickiness policy ", responseObject = LBStickinessResponse.class, since="3.0.0") +@APICommand(name = "createLBStickinessPolicy", description = "Creates a Load Balancer stickiness policy ", responseObject = LBStickinessResponse.class, since="3.0.0") @SuppressWarnings("rawtypes") public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger @@ -50,9 +50,9 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, required = true, description = "the ID of the load balancer rule") + + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") private Long lbRuleId; @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the LB Stickiness policy") @@ -91,9 +91,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { return paramList; } - public String getEntityTable() { - return "firewall_rules"; - } + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -117,7 +115,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { public void execute() throws ResourceAllocationException, ResourceUnavailableException { StickinessPolicy policy = null; boolean success = false; - + try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); success = _lbService.applyLBStickinessPolicy(this); @@ -131,9 +129,9 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { } } finally { if (!success || (policy == null)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create stickiness policy "); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create stickiness policy "); } - } + } } @Override @@ -141,6 +139,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { try { StickinessPolicy result = _lbService.createLBStickinessPolicy(this); this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java index 80a86847a7e..4e76a6b676f 100644 --- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -44,7 +47,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) +@APICommand(name = "createLoadBalancerRule", description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements LoadBalancer */{ public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName()); @@ -66,37 +69,37 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @Parameter(name=ApiConstants.PRIVATE_PORT, type=CommandType.INTEGER, required=true, description="the private port of the private ip address/virtual machine where the network traffic will be load balanced to") private Integer privatePort; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="public ip address id from where the network traffic will be load balanced from") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="public ip address id from where the network traffic will be load balanced from") private Long publicIpId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") private Long zoneId; @Parameter(name=ApiConstants.PUBLIC_PORT, type=CommandType.INTEGER, required=true, description="the public port from where the network traffic will be load balanced from") private Integer publicPort; @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for" + - " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + + " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the load balancer") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID associated with the load balancer") private Long domainId; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="The guest network this " + - "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="The guest network this " + + "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -117,24 +120,21 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return privatePort; } - public String getEntityTable() { - return "firewall_rules"; - } - + public Long getSourceIpAddressId() { - if (publicIpId != null) { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); - } - } else if (getEntityId() != null) { - LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - return rule.getSourceIpAddressId(); - } - - return publicIpId; + if (publicIpId != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr == null || !ipAddr.readyToUse()) { + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); + } + } else if (getEntityId() != null) { + LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); + return rule.getSourceIpAddressId(); + } + + return publicIpId; } - + private Long getVpcId() { if (publicIpId != null) { IpAddress ipAddr = _networkService.getIp(publicIpId); @@ -146,36 +146,36 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } return null; } - - + + public Long getNetworkId() { if (networkId != null) { return networkId; - } - Long zoneId = getZoneId(); - - if (zoneId == null) { - Long ipId = getSourceIpAddressId(); - if (ipId == null) { - throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); - } } - + Long zoneId = getZoneId(); + + if (zoneId == null) { + Long ipId = getSourceIpAddressId(); + if (ipId == null) { + throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); + } + } + if (zoneId != null) { - DataCenter zone = _configService.getZone(zoneId); - if (zone.getNetworkType() == NetworkType.Advanced) { + DataCenter zone = _configService.getZone(zoneId); + if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); @@ -186,23 +186,23 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } else { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr.getAssociatedWithNetworkId() != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr.getAssociatedWithNetworkId() != null) { return ipAddr.getAssociatedWithNetworkId(); - } else { - throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); - } + } else { + throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); + } } } public Integer getPublicPort() { return publicPort; } - + public String getName() { return loadBalancerRuleName; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { @@ -217,7 +217,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return true; } } - + public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); @@ -233,33 +233,33 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getCommandName() { return s_name; } - + @Override - public void execute() throws ResourceAllocationException, ResourceUnavailableException { - + public void execute() throws ResourceAllocationException, ResourceUnavailableException { + UserContext callerContext = UserContext.current(); boolean success = true; LoadBalancer rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller()); } // State might be different after the rule is applied, so get new object here rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - LoadBalancerResponse lbResponse = new LoadBalancerResponse(); + LoadBalancerResponse lbResponse = new LoadBalancerResponse(); if (rule != null) { lbResponse = _responseGenerator.createLoadBalancerResponse(rule); setResponseObject(lbResponse); } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create LB rule due to exception ", ex); + s_logger.warn("Failed to create LB rule due to exception ", ex); }finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } @@ -270,7 +270,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } - + @Override public void create() { //cidr list parameter is deprecated @@ -280,6 +280,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements try { LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall()); this.setEntityId(result.getId()); + this.setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); @@ -300,11 +301,11 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getProtocol() { return NetUtils.TCP_PROTO; } - - public long getAccountId() { + + public long getAccountId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getAccountId(); - + Account account = null; if ((domainId != null) && (accountName != null)) { account = _responseGenerator.findAccountByNameDomain(accountName, domainId); @@ -334,16 +335,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public int getDefaultPortEnd() { return privatePort.intValue(); } - + @Override public long getEntityOwnerId() { return getAccountId(); } - + public String getAccountName() { return accountName; } - + public Long getZoneId() { return zoneId; } @@ -371,7 +372,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public void setSourceIpAddressId(Long ipId) { this.publicIpId = ipId; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java index 55195f7180e..9329bd35aba 100644 --- a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.StickinessPolicy; @@ -33,7 +33,7 @@ import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Deletes a LB stickiness policy.", responseObject = SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteLBStickinessPolicy", description = "Deletes a LB stickiness policy.", responseObject = SuccessResponse.class, since="3.0.0") public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteLBStickinessPolicyCmd.class.getName()); private static final String s_name = "deleteLBstickinessrruleresponse"; @@ -41,8 +41,8 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="load_balancer_stickiness_policies") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the LB stickiness policy") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = LBStickinessResponse.class, + required = true, description = "the ID of the LB stickiness policy") private Long id; // /////////////////////////////////////////////////// @@ -105,11 +105,11 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { StickinessPolicy policy = _entityMgr.findById(StickinessPolicy.class, getId()); if (policy == null) { - throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); } LoadBalancer lb = _lbService.findById(policy.getLoadBalancerId()); if (lb == null) { - throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); } return lb.getNetworkId(); } diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java index 72330c20912..d53155f17b9 100644 --- a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +29,7 @@ import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteLoadBalancerRule", description="Deletes a load balancer rule.", responseObject=SuccessResponse.class) public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteLoadBalancerRuleCmd.class.getName()); private static final String s_name = "deleteloadbalancerruleresponse"; @@ -41,8 +37,8 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; @@ -82,13 +78,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting load balancer: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _lbService.deleteLoadBalancerRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -96,7 +92,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -104,13 +100,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java index 6be47c13221..90708c0bfe0 100644 --- a/api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java @@ -14,26 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.StickinessPolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Lists LBStickiness policies.", responseObject = LBStickinessResponse.class, since="3.0.0") +@APICommand(name = "listLBStickinessPolicies", description = "Lists LBStickiness policies.", responseObject = LBStickinessResponse.class, since="3.0.0") public class ListLBStickinessPoliciesCmd extends BaseListCmd { public static final Logger s_logger = Logger .getLogger(ListLBStickinessPoliciesCmd.class.getName()); @@ -43,11 +43,9 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, required = true, description = "the ID of the load balancer rule") + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") private Long lbRuleId; - - // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// @@ -55,8 +53,6 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { public Long getLbRuleId() { return lbRuleId; } - - // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// @@ -72,17 +68,17 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { List spResponses = new ArrayList(); LoadBalancer lb = _lbService.findById(getLbRuleId()); ListResponse response = new ListResponse(); - + if (lb != null) { - //check permissions - Account caller = UserContext.current().getCaller(); - _accountService.checkAccess(caller, null, true, lb); + //check permissions + Account caller = UserContext.current().getCaller(); + _accountService.checkAccess(caller, null, true, lb); List stickinessPolicies = _lbService.searchForLBStickinessPolicies(this); LBStickinessResponse spResponse = _responseGenerator.createLBStickinessPolicyResponse(stickinessPolicies, lb); spResponses.add(spResponse); response.setResponses(spResponses); } - + response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java index d721914f5f9..374c6fb25e5 100644 --- a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.uservm.UserVm; -@Implementation(description="List all virtual machine instances that are assigned to a load balancer rule.", responseObject=UserVmResponse.class) +@APICommand(name = "listLoadBalancerRuleInstances", description="List all virtual machine instances that are assigned to a load balancer rule.", responseObject=UserVmResponse.class) public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger (ListLoadBalancerRuleInstancesCmd.class.getName()); @@ -43,8 +43,8 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { @Parameter(name=ApiConstants.APPLIED, type=CommandType.BOOLEAN, description="true if listing all virtual machines currently applied to the load balancer rule; default is true") private Boolean applied; - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; ///////////////////////////////////////////////////// @@ -67,14 +67,14 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = _lbService.listLoadBalancerInstances(this); ListResponse response = new ListResponse(); List vmResponses = new ArrayList(); if (result != null) { - vmResponses = _responseGenerator.createUserVmResponse("loadbalancerruleinstance", result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("loadbalancerruleinstance", result.toArray(new UserVm[result.size()])); } response.setResponses(vmResponses); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java index 8413f607a6b..d0d4e8db85c 100644 --- a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java @@ -14,24 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.Pair; -@Implementation(description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class) +@APICommand(name = "listLoadBalancerRules", description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class) public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRulesCmd.class.getName()); @@ -41,23 +44,23 @@ public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the load balancer rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + description = "the ID of the load balancer rule") private Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the load balancer rule") private String loadBalancerRuleName; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name = ApiConstants.PUBLIC_IP_ID, type = CommandType.LONG, description = "the public IP address id of the load balancer rule ") + @Parameter(name = ApiConstants.PUBLIC_IP_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + description = "the public IP address id of the load balancer rule ") private Long publicIpId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, description = "the ID of the virtual machine of the load balancer rule") + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, + description = "the ID of the virtual machine of the load balancer rule") private Long virtualMachineId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the availability zone ID") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the availability zone ID") private Long zoneId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java index abc850f7471..f56f06d15c5 100644 --- a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.LoadBalancer; @@ -35,22 +32,22 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(description="Removes a virtual machine or a list of virtual machines from a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "removeFromLoadBalancerRule", description="Removes a virtual machine or a list of virtual machines from a load balancer rule.", responseObject=SuccessResponse.class) public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveFromLoadBalancerRuleCmd.class.getName()); private static final String s_name = "removefromloadbalancerruleresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="The ID of the load balancer rule") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, required = true, collectionType=CommandType.LONG, description="the list of IDs of the virtual machines that are being removed from the load balancer rule (i.e. virtualMachineIds=1,2,3)") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, required = true, collectionType=CommandType.UUID, entityType = UserVmResponse.class, + description="the list of IDs of the virtual machines that are being removed from the load balancer rule (i.e. virtualMachineIds=1,2,3)") private List virtualMachineIds; ///////////////////////////////////////////////////// @@ -104,7 +101,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,10 +109,10 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java index a110a8d9af1..8a86f74260d 100644 --- a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates load balancer", responseObject=LoadBalancerResponse.class) +@APICommand(name = "updateLoadBalancerRule", description="Updates load balancer", responseObject=LoadBalancerResponse.class) public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateLoadBalancerRuleCmd.class.getName()); private static final String s_name = "updateloadbalancerruleresponse"; @@ -46,8 +42,8 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the load balancer rule", length=4096) private String description; - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the load balancer rule to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the id of the load balancer rule to update") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the load balancer rule") @@ -100,7 +96,7 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "updating load balancer rule"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java index a688d134352..1ce3458dde3 100644 --- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +41,7 @@ import com.cloud.network.rules.StaticNatRule; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class) +@APICommand(name = "createIpForwardingRule", description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class) public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements StaticNatRule { public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); @@ -51,22 +51,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") private Long ipAddressId; - + @Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, required=true, description="the start port for the rule") private Integer startPort; @Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="the end port for the rule") private Integer endPort; - + @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the rule. Valid values are TCP or UDP.") private String protocol; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; @@ -74,23 +74,20 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - public String getEntityTable() { - return "firewall_rules"; - } - + + public Long getIpAddressId() { return ipAddressId; } - + public int getStartPort() { return startPort; } - + public int getEndPort() { return endPort; } - + public Boolean getOpenFirewall() { if (openFirewall != null) { return openFirewall; @@ -109,17 +106,17 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta } @Override - public void execute() throws ResourceUnavailableException{ + public void execute() throws ResourceUnavailableException{ boolean result = true; FirewallRule rule = null; try { UserContext.current().setEventDetails("Rule Id: "+ getEntityId()); - + if (getOpenFirewall()) { result = result && _firewallService.applyFirewallRules(ipAddressId, UserContext.current().getCaller()); } - + result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller()); rule = _entityMgr.findById(FirewallRule.class, getEntityId()); StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); @@ -128,34 +125,35 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta this.setResponseObject(fwResponse); } finally { if (!result || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokeStaticNatRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } } - @Override - public void create() { - - //cidr list parameter is deprecated + @Override + public void create() { + + //cidr list parameter is deprecated if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } - + try { StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall()); this.setEntityId(rule.getId()); + this.setEntityUuid(rule.getUuid()); } catch (NetworkRuleConflictException e) { s_logger.info("Unable to create Static Nat Rule due to ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } - } + } @Override public long getEntityOwnerId() { @@ -178,16 +176,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ("Applying an ipforwarding 1:1 NAT rule for Ip: "+ip.getAddress()+" with virtual machine:"+ this.getVirtualMachineId()); } - + private long getVirtualMachineId() { Long vmId = _networkService.getIp(ipAddressId).getAssociatedWithVmId(); - + if (vmId == null) { throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule"); } return vmId; } - + @Override public String getDestIpAddress(){ return null; @@ -248,13 +246,20 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ip.getAccountId(); } - + @Override public String getXid() { // FIXME: We should allow for end user to specify Xid. return null; } - + + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -272,12 +277,12 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -287,22 +292,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta public List getSourceCidrList() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } - - @Override + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } + + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java index 475e09a017b..6300a412d54 100644 --- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes an ip forwarding rule", responseObject=SuccessResponse.class) +@APICommand(name = "deleteIpForwardingRule", description="Deletes an ip forwarding rule", responseObject=SuccessResponse.class) public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteIpForwardingRuleCmd.class.getName()); @@ -42,14 +43,13 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the forwarding rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the id of the forwarding rule") private Long id; - // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -71,8 +71,8 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); - boolean result = _firewallService.revokeRelatedFirewallRule(id, true); - result = result && _rulesService.revokeStaticNatRule(id, true); + boolean result = _firewallService.revokeRelatedFirewallRule(id, true); + result = result && _rulesService.revokeStaticNatRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -104,7 +104,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting an ipforwarding 1:1 NAT rule id:"+id); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,7 +114,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DisableStaticNatCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java index 5983264d4c3..fbd0b5ce900 100644 --- a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; +import org.apache.cloudstack.api.command.user.firewall.DeletePortForwardingRuleCmd; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +34,7 @@ import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; -@Implementation(description="Disables static rule for given ip address", responseObject=SuccessResponse.class) +@APICommand(name = "disableStaticNat", description="Disables static rule for given ip address", responseObject=SuccessResponse.class) public class DisableStaticNatCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); private static final String s_name = "disablestaticnatresponse"; @@ -42,10 +43,10 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id for which static nat feature is being disableed") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP address id for which static nat feature is being disableed") private Long ipAddressId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,7 +54,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public Long getIpAddress() { return ipAddressId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -61,7 +62,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_DISABLE_STATIC_NAT; @@ -71,16 +72,16 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disabling static nat for ip id=" + ipAddressId); } - + @Override public long getEntityOwnerId() { return _entityMgr.findById(IpAddress.class, ipAddressId).getAccountId(); } - + @Override public void execute() throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException { boolean result = _rulesService.disableStaticNat(ipAddressId); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -88,8 +89,8 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable static nat"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; diff --git a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/EnableStaticNatCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java index 9e21b8378ff..79a8e2bc9ff 100644 --- a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java @@ -14,17 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; @@ -32,7 +34,7 @@ import com.cloud.network.IpAddress; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Enables static nat for given ip address", responseObject=SuccessResponse.class) +@APICommand(name = "enableStaticNat", description="Enables static nat for given ip address", responseObject=SuccessResponse.class) public class EnableStaticNatCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); @@ -42,20 +44,19 @@ public class EnableStaticNatCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP " + - "address id for which static nat feature is being enabled") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP " + + "address id for which static nat feature is being enabled") private Long ipAddressId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of " + - "the virtual machine for enabling static nat feature") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of " + + "the virtual machine for enabling static nat feature") private Long virtualMachineId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, description="The network of the vm the static nat will be enabled for." + - " Required when public Ip address is not associated with any Guest network yet (VPC case)") + " Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; ///////////////////////////////////////////////////// @@ -69,18 +70,18 @@ public class EnableStaticNatCmd extends BaseCmd{ public Long getVirtualMachineId() { return virtualMachineId; } - + public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { ntwkId = networkId; } if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -94,7 +95,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -106,7 +107,7 @@ public class EnableStaticNatCmd extends BaseCmd{ } @Override - public void execute() throws ResourceUnavailableException{ + public void execute() throws ResourceUnavailableException{ try { boolean result = _rulesService.enableStaticNat(ipAddressId, virtualMachineId, getNetworkId(), false); if (result) { diff --git a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java index fedbac0d177..e4aaff3e56f 100644 --- a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.utils.Pair; -@Implementation(description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class) +@APICommand(name = "listIpForwardingRules", description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class) public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListIpForwardingRulesCmd.class.getName()); @@ -42,17 +43,17 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="list the rule belonging to this public ip address") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="list the rule belonging to this public ip address") private Long publicIpAddressId; - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="Lists all rules applied to the specified Vm.") + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="Lists all rules applied to the specified Vm.") private Long vmId; ///////////////////////////////////////////////////// @@ -64,15 +65,15 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - - public Long getPublicIpAddressId() { - return publicIpAddressId; - } - public Long getId() { + public Long getPublicIpAddressId() { + return publicIpAddressId; + } + + public Long getId() { return id; } @@ -82,7 +83,7 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources @Override public void execute(){ - Pair, Integer> result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, + Pair, Integer> result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(), this.getProjectId(), this.isRecursive(), this.listAll()); ListResponse response = new ListResponse(); List ipForwardingResponses = new ArrayList(); @@ -97,5 +98,5 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources response.setResponseName(getCommandName()); this.setResponseObject(response); } - + } diff --git a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/CreateNetworkACLCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java index 033a496d35d..16843b56d67 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkACLResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -42,7 +42,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description = "Creates a ACL rule the given network (the network has to belong to VPC)", +@APICommand(name = "createNetworkACL", description = "Creates a ACL rule the given network (the network has to belong to VPC)", responseObject = NetworkACLResponse.class) public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallRule { public static final Logger s_logger = Logger.getLogger(CreateNetworkACLCmd.class.getName()); @@ -53,7 +53,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = + @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the ACL rule. Valid values are TCP/UDP/ICMP.") private String protocol; @@ -62,33 +62,29 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of ACL") private Integer publicEndPort; - - @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, + + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to allow traffic from/to") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required=true, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="The network of the vm the ACL will be created for") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="the traffic type for the ACL," + - "can be Ingress or Egress, defaulted to Ingress if not specified") + "can be Ingress or Egress, defaulted to Ingress if not specified") private String trafficType; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - - public String getEntityTable() { - return "firewall_rules"; - } public Long getIpAddressId() { return null; @@ -108,21 +104,21 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return oneCidrList; } } - + public long getVpcId() { Network network = _networkService.getNetwork(getNetworkId()); if (network == null) { throw new InvalidParameterValueException("Invalid networkId is given"); } - + Long vpcId = network.getVpcId(); if (vpcId == null) { throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC"); } - + return vpcId; } - + @Override public FirewallRule.TrafficType getTrafficType() { if (trafficType == null) { @@ -144,7 +140,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -159,7 +155,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR success = _networkACLService.applyNetworkACLs(rule.getNetworkId(), callerContext.getCaller()); // State is different after the rule is applied, so get new object here - NetworkACLResponse aclResponse = new NetworkACLResponse(); + NetworkACLResponse aclResponse = new NetworkACLResponse(); if (rule != null) { aclResponse = _responseGenerator.createNetworkACLResponse(rule); setResponseObject(aclResponse); @@ -184,6 +180,13 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return null; @@ -206,7 +209,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } else { return publicEndPort.intValue(); } - + return null; } @@ -247,7 +250,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -255,6 +258,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR try { FirewallRule result = _networkACLService.createNetworkACL(this); setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network Rule Conflict: ", ex); @@ -288,7 +292,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public Long getSyncObjId() { return getNetworkId(); } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -298,14 +302,14 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { return -1; - + } return null; } @@ -319,7 +323,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/CreateNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java index a53635722ef..3b2608729a4 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java @@ -14,17 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -34,7 +39,7 @@ import com.cloud.network.Network.GuestType; import com.cloud.offering.NetworkOffering; import com.cloud.user.UserContext; -@Implementation(description="Creates a network", responseObject=NetworkResponse.class) +@APICommand(name = "createNetwork", description="Creates a network", responseObject=NetworkResponse.class) public class CreateNetworkCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateNetworkCmd.class.getName()); @@ -43,68 +48,68 @@ public class CreateNetworkCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, required=true, description="the network offering id") + + @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + required=true, description="the network offering id") private Long networkOfferingId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the Zone ID for the network") private Long zoneId; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway of the network. Required " + - "for Shared networks and Isolated networks when it belongs to VPC") + "for Shared networks and Isolated networks when it belongs to VPC") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the network. Required " + "for Shared networks and Isolated networks when it belongs to VPC") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + - " range. If not specified, will be defaulted to startIP") + " range. If not specified, will be defaulted to startIP") private String endIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the network") private String vlan; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="Access control type; supported values" + - " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + - " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") + " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + + " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") private String aclType; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a network") private Long domainId; - + @Parameter(name=ApiConstants.SUBDOMAIN_ACCESS, type=CommandType.BOOLEAN, description="Defines whether to allow" + - " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") + " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") private Boolean subdomainAccess; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC network belongs to") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="the VPC network belongs to") private Long vpcId; @@ -130,7 +135,7 @@ public class CreateNetworkCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -142,11 +147,11 @@ public class CreateNetworkCmd extends BaseCmd { public String getEndIp() { return endIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } @@ -154,39 +159,39 @@ public class CreateNetworkCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; } - + public Long getProjectId() { return projectId; } public String getAclType() { - return aclType; - } + return aclType; + } - public Boolean getSubdomainAccess() { - return subdomainAccess; - } + public Boolean getSubdomainAccess() { + return subdomainAccess; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; } public Long getZoneId() { Long physicalNetworkId = getPhysicalNetworkId(); - + if (physicalNetworkId == null && zoneId == null) { throw new InvalidParameterValueException("Zone id is required"); } - + return zoneId; } - + public Long getPhysicalNetworkId() { NetworkOffering offering = _configService.getNetworkOffering(networkOfferingId); if (offering == null) { throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); } - + if (physicalNetworkId != null) { if (offering.getGuestType() == GuestType.Shared) { return physicalNetworkId; @@ -208,19 +213,19 @@ public class CreateNetworkCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override - // an exception thrown by createNetwork() will be caught by the dispatcher. + // an exception thrown by createNetwork() will be caught by the dispatcher. public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.createGuestNetwork(this); if (result != null) { diff --git a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java index 0499f531c11..4b078ed7fe3 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +34,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Network ACL", responseObject=SuccessResponse.class) +@APICommand(name = "deleteNetworkACL", description="Deletes a Network ACL", responseObject=SuccessResponse.class) public class DeleteNetworkACLCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetworkACLCmd.class.getName()); private static final String s_name = "deletenetworkaclresponse"; @@ -42,13 +43,13 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network ACL") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the network ACL") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +58,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +66,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -75,7 +76,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting Network ACL id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +89,12 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Network ACL Id: " + id); boolean result = _networkACLService.revokeNetworkACL(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +102,8 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network ACL"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,7 +113,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/DeleteNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java index 5e1350ff15b..df070ff8ecb 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java @@ -14,24 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; import com.cloud.user.UserContext; -@Implementation(description="Deletes a network", responseObject=SuccessResponse.class) +@APICommand(name = "deleteNetwork", description="Deletes a network", responseObject=SuccessResponse.class) public class DeleteNetworkCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteNetworkOfferingCmd.class.getName()); private static final String s_name = "deletenetworkresponse"; @@ -40,8 +37,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="the ID of the network") private Long id; @@ -62,7 +59,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network Id: " + id); @@ -74,8 +71,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -85,17 +82,17 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public Long getSyncObjId() { return id; } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_DELETE; } - + @Override public String getEventDescription() { return "Deleting network: " + id; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); diff --git a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ListNetworkACLsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java index bdb3c3b733b..f556ce1cbfd 100644 --- a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java @@ -14,26 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.network.rules.FirewallRule; import com.cloud.utils.Pair; -@Implementation(description="Lists all network ACLs", responseObject=NetworkACLResponse.class) +@APICommand(name = "listNetworkACLs", description="Lists all network ACLs", responseObject=NetworkACLResponse.class) public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkACLsCmd.class.getName()); @@ -42,29 +41,29 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists network ACL with the specified ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists network ACL with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list network ACLs by network Id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="list network ACLs by network Id") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="list network ACLs by traffic type - Ingress or Egress") private String trafficType; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { return networkId; } - + public Long getId() { return id; } - + public String getTrafficType() { return trafficType; } @@ -77,19 +76,19 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair,Integer> result = _networkACLService.listNetworkACLs(this); ListResponse response = new ListResponse(); List aclResponses = new ArrayList(); - + for (FirewallRule acl : result.first()) { NetworkACLResponse ruleData = _responseGenerator.createNetworkACLResponse(acl); aclResponses.add(ruleData); } response.setResponses(aclResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java index 70dd1be2e74..94bc71dc993 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.offering.NetworkOffering; - -@Implementation(description="Lists all available network offerings.", responseObject=NetworkOfferingResponse.class) +@APICommand(name = "listNetworkOfferings", description="Lists all available network offerings.", responseObject=NetworkOfferingResponse.class) public class ListNetworkOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); private static final String _name = "listnetworkofferingsresponse"; @@ -39,73 +39,73 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list network offerings by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + description="list network offerings by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list network offerings by name") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list network offerings by display text") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="list by traffic type") private String trafficType; - + @Parameter(name=ApiConstants.IS_DEFAULT, type=CommandType.BOOLEAN, description="true if need to list only default network offerings. Default value is false") - private Boolean isDefault; - + private Boolean isDefault; + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="the tags for the network offering.") private Boolean specifyVlan; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Required") private String availability; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list netowrk offerings available for network creation in specific zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="list netowrk offerings available for network creation in specific zone") private Long zoneId; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") private String state; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") private Long networkId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="list network offerings by guest type: Shared or Isolated") private String guestIpType; @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list network offerings supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.SOURCE_NAT_SUPPORTED, type=CommandType.BOOLEAN, description="true if need to list only netwok offerings where source nat is supported, false otherwise") private Boolean sourceNatSupported; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if need to list only network offerings which support specifying ip ranges") private Boolean specifyIpRanges; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="list network offerings by tags", length=4096) private String tags; - + @Parameter(name=ApiConstants.IS_TAGGED, type=CommandType.BOOLEAN, description="true if offering has tags specified") private Boolean isTagged; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="the network offering can be used" + - " only for network creation inside the VPC") + " only for network creation inside the VPC") private Boolean forVpc; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } - + public String getTrafficType() { return trafficType; } @@ -117,7 +117,7 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { public Boolean getIsDefault() { return isDefault; } - + public Boolean getSpecifyVlan() { return specifyVlan; } @@ -147,14 +147,14 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { } public Boolean getSourceNatSupported() { - return sourceNatSupported; - } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges; + return sourceNatSupported; } - public String getTags() { + public Boolean getSpecifyIpRanges() { + return specifyIpRanges; + } + + public String getTags() { return tags; } diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListNetworksCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java index 61aff018edf..1f366c223a6 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.network.Network; - -@Implementation(description="Lists all available networks.", responseObject=NetworkResponse.class) +@APICommand(name = "listNetworks", description="Lists all available networks.", responseObject=NetworkResponse.class) public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworksCmd.class.getName()); private static final String _name = "listnetworksresponse"; @@ -39,50 +40,50 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list networks by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="list networks by id") private Long id; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the network") private Long zoneId; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the type of the network. Supported values are: Isolated and Shared") private String guestIpType; - + @Parameter(name=ApiConstants.IS_SYSTEM, type=CommandType.BOOLEAN, description="true if network is system, false otherwise") private Boolean isSystem; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="list networks by ACL (access control list) type. Supported values are Account and Domain") private String aclType; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="type of the traffic") private String trafficType; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="list networks by physical network id") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="list networks by physical network id") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list networks supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.RESTART_REQUIRED, type=CommandType.BOOLEAN, description="list networks by restartRequired") - + private Boolean restartRequired; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if need to list only networks which support specifying ip ranges") private Boolean specifyIpRanges; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="List networks by VPC") private Long vpcId; @Parameter(name=ApiConstants.CAN_USE_FOR_DEPLOY, type=CommandType.BOOLEAN, description="list networks available for vm deployment") private Boolean canUseForDeploy; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="the network belongs to vpc") private Boolean forVpc; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -90,7 +91,7 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public Long getId() { return id; } - + public Long getZoneId() { return zoneId; } @@ -102,10 +103,10 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public Boolean getIsSystem() { return isSystem; } - + public String getAclType() { - return aclType; - } + return aclType; + } public String getTrafficType() { return trafficType; @@ -120,21 +121,21 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { } public Boolean getRestartRequired() { - return restartRequired; - } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges; + return restartRequired; } - public Long getVpcId() { + public Boolean getSpecifyIpRanges() { + return specifyIpRanges; + } + + public Long getVpcId() { return vpcId; - } - - public Boolean canUseForDeploy() { + } + + public Boolean canUseForDeploy() { return canUseForDeploy; } - + public Boolean getForVpc() { return forVpc; } diff --git a/api/src/com/cloud/api/commands/RestartNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/RestartNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java index 0141d24f438..ee9af3b0009 100644 --- a/api/src/com/cloud/api/commands/RestartNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java @@ -14,19 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -35,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -@Implementation(description="Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules", responseObject=IPAddressResponse.class) +@APICommand(name = "restartNetwork", description="Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules", responseObject=IPAddressResponse.class) public class RestartNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RestartNetworkCmd.class.getName()); private static final String s_name = "restartnetworkresponse"; @@ -44,9 +40,8 @@ public class RestartNetworkCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The id of the network to restart.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="The id of the network to restart.") private Long id; @Parameter(name=ApiConstants.CLEANUP, type=CommandType.BOOLEAN, required=false, description="If cleanup old network elements") @@ -56,7 +51,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { Network network = _networkService.getNetwork(id); if (network == null) { @@ -65,7 +60,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { return network.getId(); } } - + public Boolean getCleanup() { if (cleanup != null) { return cleanup; @@ -87,7 +82,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public static String getResultObjectName() { return "addressinfo"; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { boolean result = _networkService.restartNetwork(this, getCleanup()); @@ -98,7 +93,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart network"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,16 +103,16 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public Long getSyncObjId() { return id; } - + public String getEventDescription() { return "Restarting network: " + getNetworkId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_RESTART; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdateNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java index 15d8451a81b..5ab8a6035ad 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -35,7 +35,7 @@ import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Updates a network", responseObject=NetworkResponse.class) +@APICommand(name = "updateNetwork", description="Updates a network", responseObject=NetworkResponse.class) public class UpdateNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); @@ -44,46 +44,46 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="the ID of the network") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the new name for the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the new display text for the network") private String displayText; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.CHANGE_CIDR, type=CommandType.BOOLEAN, description="Force update even if cidr type is different") private Boolean changeCidr; - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID") + + @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + description="network offering ID") private Long networkOfferingId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + private String getNetworkDomain() { return networkDomain; } - + private Long getNetworkOfferingId() { return networkOfferingId; } @@ -102,7 +102,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); @@ -112,7 +112,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { return _networkService.getNetwork(id).getAccountId(); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException{ User callerUser = _accountService.getActiveUser(UserContext.current().getCallerUserId()); @@ -121,7 +121,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { if (network == null) { throw new InvalidParameterValueException("Couldn't find network by id"); } - + Network result = null; if (network.getVpcId() != null) { result = _vpcService.updateVpcGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, @@ -130,7 +130,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr()); } - + if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(result); response.setResponseName(getCommandName()); @@ -139,12 +139,12 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network"); } } - + @Override public String getEventDescription() { return "Updating network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; diff --git a/api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java index fbf655d7e88..7209429cfa0 100644 --- a/api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.offering; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.offering.DiskOffering; -@Implementation(description="Lists all available disk offerings.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "listDiskOfferings", description="Lists all available disk offerings.", responseObject=DiskOfferingResponse.class) public class ListDiskOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListDiskOfferingsCmd.class.getName()); @@ -40,12 +40,12 @@ public class ListDiskOfferingsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain of the disk offering.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the ID of the domain of the disk offering.") private Long domainId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DiskOfferingResponse.class, + description="ID of the disk offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the disk offering") diff --git a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java index 39cc7c80948..9fad577d8ad 100644 --- a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.offering; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.offering.ServiceOffering; -@Implementation(description="Lists all available service offerings.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "listServiceOfferings", description="Lists all available service offerings.", responseObject=ServiceOfferingResponse.class) public class ListServiceOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); @@ -40,19 +41,19 @@ public class ListServiceOfferingsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the service offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = ServiceOfferingResponse.class, + description="ID of the service offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the service offering") private String serviceOfferingName; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to.") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to.") private Long virtualMachineId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain associated with the service offering") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the ID of the domain associated with the service offering") private Long domainId; @Parameter(name=ApiConstants.IS_SYSTEM_OFFERING, type=CommandType.BOOLEAN, description="is this a system vm offering") @@ -61,7 +62,7 @@ public class ListServiceOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"consoleproxy\", \"secondarystoragevm\" or \"domainrouter\".") private String systemVmType; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,13 +80,13 @@ public class ListServiceOfferingsCmd extends BaseListCmd { } public Long getDomainId(){ - return domainId; + return domainId; } - + public Boolean getIsSystem() { return isSystem == null ? false : isSystem; } - + public String getSystemVmType(){ return systemVmType; } @@ -98,7 +99,7 @@ public class ListServiceOfferingsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List offerings = _mgr.searchForServiceOfferings(this); diff --git a/api/src/com/cloud/api/commands/ActivateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/ActivateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java index b8c4721a8f9..6cc9387ac2b 100644 --- a/api/src/com/cloud/api/commands/ActivateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java @@ -14,25 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Activates a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "activateProject", description="Activates a project", responseObject=ProjectResponse.class, since="3.0.0") public class ActivateProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ActivateProjectCmd.class.getName()); @@ -41,9 +35,9 @@ public class ActivateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be modified") private Long id; ///////////////////////////////////////////////////// @@ -58,19 +52,19 @@ public class ActivateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - - + + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(getId()); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + getId()); - } - - return _projectService.getProjectOwner(getId()).getId(); + } + + return _projectService.getProjectOwner(getId()).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -88,14 +82,14 @@ public class ActivateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to activate a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACTIVATE; } - + @Override public String getEventDescription() { return "Activating project: " + id; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/CreateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/CreateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java index 12d1a2c6ea9..865f7a0aa99 100644 --- a/api/src/com/cloud/api/commands/CreateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +29,7 @@ import com.cloud.projects.Project; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0") +@APICommand(name = "createProject", description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0") public class CreateProjectCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateProjectCmd.class.getName()); @@ -46,8 +42,8 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will be Admin for the project") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "domain ID of the account owning a project") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "domain ID of the account owning a project") private Long domainId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the project") @@ -60,9 +56,6 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - public String getEntityTable() { - return "projects"; - } public String getAccountName() { if (accountName != null) { @@ -131,6 +124,7 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { Project project = _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId()); if (project != null) { this.setEntityId(project.getId()); + this.setEntityUuid(project.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); } @@ -146,4 +140,4 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { return "creating project"; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java index fb1b508826a..fb41a7f14ef 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Deletes a project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteProject", description="Deletes a project", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectCmd.class.getName()); @@ -41,8 +41,8 @@ public class DeleteProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be deleted") private Long id; ///////////////////////////////////////////////////// @@ -74,26 +74,26 @@ public class DeleteProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_DELETE; } - + @Override public String getEventDescription() { return "Deleting project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java index a13bbda8cf0..67c7cefc252 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") +@APICommand(name = "deleteProjectInvitation", description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class DeleteProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectInvitationCmd.class.getName()); private static final String s_name = "deleteprojectinvitationresponse"; @@ -38,8 +38,8 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "project_invitations") - @Parameter(name = ApiConstants.ID, required = true, type = CommandType.LONG, description = "id of the invitation") + @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=ProjectInvitationResponse.class, + required = true, description = "id of the invitation") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java similarity index 59% rename from api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java index fe697808b4b..4157daa7b4a 100644 --- a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java @@ -14,24 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.projects.ProjectInvitation; -import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; -@Implementation(description = "Lists projects and provides detailed information for listed projects", responseObject = ProjectInvitationResponse.class, since = "3.0.0") +@APICommand(name = "listProjectInvitations", description = "Lists projects and provides detailed information for listed projects", responseObject = ProjectInvitationResponse.class, since = "3.0.0") public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListProjectInvitationsCmd.class.getName()); private static final String s_name = "listprojectinvitationsresponse"; @@ -39,8 +34,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list by project id") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + description = "list by project id") private Long projectId; @Parameter(name = ApiConstants.ACTIVE_ONLY, type = CommandType.BOOLEAN, description = "if true, list only active invitations - having Pending state and ones that are not timed out yet") @@ -49,8 +44,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { @Parameter(name = ApiConstants.STATE, type = CommandType.STRING, description = "list invitations by state") private String state; - @IdentityMapper(entityTableName = "project_invitations") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "list invitations by id") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=ProjectInvitationResponse.class, + description = "list invitations by id") private Long id; // /////////////////////////////////////////////////// @@ -83,18 +78,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { @Override public void execute() { - Pair, Integer> invites = _projectService.listProjectInvitations(id, projectId, - this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(), - this.isRecursive(), this.listAll()); - ListResponse response = new ListResponse(); - List projectInvitationResponses = new ArrayList(); - for (ProjectInvitation invite : invites.first()) { - ProjectInvitationResponse projectResponse = _responseGenerator.createProjectInvitationResponse(invite); - projectInvitationResponses.add(projectResponse); - } - response.setResponses(projectInvitationResponses, invites.second()); + ListResponse response = _queryService.listProjectInvitations(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListProjectsCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/ListProjectsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java index b7a04eb4e33..321a19fe62d 100644 --- a/api/src/com/cloud/api/commands/ListProjectsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java @@ -14,29 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; -import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.projects.Project; -import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; -@Implementation(description="Lists projects and provides detailed information for listed projects", responseObject=ProjectResponse.class, since="3.0.0") +import com.cloud.exception.InvalidParameterValueException; + +@APICommand(name = "listProjects", description="Lists projects and provides detailed information for listed projects", responseObject=ProjectResponse.class, since="3.0.0") public class ListProjectsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListProjectsCmd.class.getName()); private static final String s_name = "listprojectsresponse"; @@ -44,9 +40,9 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list projects by project ID") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="list projects by project ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list projects by name") @@ -54,13 +50,13 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list projects by display text") private String displayText; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list projects by state") private String state; - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List projects by tags (key/value pairs)") private Map tags; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -76,12 +72,17 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { public String getDisplayText() { return displayText; } - + + + public String getState() { + return state; + } + @Override public String getCommandName() { return s_name; } - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { @@ -107,18 +108,8 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Override public void execute(){ - Pair, Integer> projects = _projectService.listProjects(id, name, displayText, state, - this.getAccountName(), this.getDomainId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), - this.listAll(), this.isRecursive(), getTags()); - ListResponse response = new ListResponse(); - List projectResponses = new ArrayList(); - for (Project project : projects.first()) { - ProjectResponse projectResponse = _responseGenerator.createProjectResponse(project); - projectResponses.add(projectResponse); - } - response.setResponses(projectResponses, projects.second()); + ListResponse response = _queryService.listProjects(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/SuspendProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/SuspendProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java index 62f6da68cbc..120e4fe0c55 100644 --- a/api/src/com/cloud/api/commands/SuspendProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +28,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Suspends a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "suspendProject", description="Suspends a project", responseObject=ProjectResponse.class, since="3.0.0") public class SuspendProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(SuspendProjectCmd.class.getName()); @@ -43,8 +38,8 @@ public class SuspendProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be suspended") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be suspended") private Long id; ///////////////////////////////////////////////////// @@ -77,26 +72,26 @@ public class SuspendProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to suspend a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_SUSPEND; } - + @Override public String getEventDescription() { return "Suspending project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/UpdateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java index 0c90e165d6a..bad117727e0 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java @@ -14,25 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Updates a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "updateProject", description="Updates a project", responseObject=ProjectResponse.class, since="3.0.0") public class UpdateProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateProjectCmd.class.getName()); @@ -41,14 +40,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be modified") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="new Admin account for the project") private String accountName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="display text of the project") private String displayText; @@ -72,18 +71,18 @@ public class UpdateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -101,14 +100,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_UPDATE; } - + @Override public String getEventDescription() { return "Updating project: " + id; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java index 20cb8c1cad3..32e1a755484 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") +@APICommand(name = "updateProjectInvitation", description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class UpdateProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateProjectInvitationCmd.class.getName()); private static final String s_name = "updateprojectinvitationresponse"; @@ -38,8 +34,8 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, required = true, type = CommandType.LONG, description = "id of the project to join") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + required = true, description = "id of the project to join") private Long projectId; @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account that is joining the project") diff --git a/api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java index e1f7cd3e217..0d62c18f55d 100644 --- a/api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.CloudIdentifierResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CloudIdentifierResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; -@Implementation(description="Retrieves a cloud identifier.", responseObject=CloudIdentifierResponse.class) +@APICommand(name = "getCloudIdentifier", description="Retrieves a cloud identifier.", responseObject=CloudIdentifierResponse.class) public class GetCloudIdentifierCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetCloudIdentifierCmd.class.getName()); private static final String s_name = "getcloudidentifierresponse"; @@ -38,11 +38,10 @@ public class GetCloudIdentifierCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.USER_ID, type=CommandType.LONG, required=true, description="the user ID for the cloud identifier") + @Parameter(name=ApiConstants.USER_ID, type=CommandType.UUID, entityType = UserResponse.class, + required=true, description="the user ID for the cloud identifier") private Long userid; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +50,6 @@ public class GetCloudIdentifierCmd extends BaseCmd { return userid; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -59,12 +57,12 @@ public class GetCloudIdentifierCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ ArrayList result = _mgr.getCloudIdentifierResponse(userid); @@ -78,6 +76,6 @@ public class GetCloudIdentifierCmd extends BaseCmd { } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to get cloud identifier"); } - + } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListHypervisorsCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/ListHypervisorsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java index e058df68bc2..c1e29d3f37e 100644 --- a/api/src/com/cloud/api/commands/ListHypervisorsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HypervisorResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HypervisorResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.user.Account; -@Implementation(description = "List hypervisors", responseObject = HypervisorResponse.class) +@APICommand(name = "listHypervisors", description = "List hypervisors", responseObject = HypervisorResponse.class) public class ListHypervisorsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); private static final String s_name = "listhypervisorsresponse"; @@ -44,8 +45,8 @@ public class ListHypervisorsCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the zone id for listing hypervisors.") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone id for listing hypervisors.") private Long zoneId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListResourceLimitsCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListResourceLimitsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java index 58d03b3c8dd..12a8494bde8 100644 --- a/api/src/com/cloud/api/commands/ListResourceLimitsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; import com.cloud.configuration.ResourceLimit; -@Implementation(description="Lists resource limits.", responseObject=ResourceLimitResponse.class) +@APICommand(name = "listResourceLimits", description="Lists resource limits.", responseObject=ResourceLimitResponse.class) public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListResourceLimitsCmd.class.getName()); @@ -43,12 +43,12 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd private Long id; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description="Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") - private Integer resourceType; - + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") + private Integer resourceType; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -64,12 +64,12 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = _resourceLimitService.searchForLimits(id, finalyzeAccountId(this.getAccountName(), this.getDomainId(), this.getProjectId(), false), this.getDomainId(), resourceType, this.getStartIndex(), this.getPageSizeVal()); diff --git a/api/src/com/cloud/api/commands/UpdateResourceCountCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/UpdateResourceCountCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java index 6a71a4c7231..d2b6870f0ca 100644 --- a/api/src/com/cloud/api/commands/UpdateResourceCountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java @@ -14,27 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; import com.cloud.configuration.ResourceCount; import com.cloud.user.Account; import com.cloud.user.UserContext; - -@Implementation(description="Recalculate and update resource count for an account or domain.", responseObject=ResourceCountResponse.class) +@APICommand(name = "updateResourceCount", description="Recalculate and update resource count for an account or domain.", responseObject=ResourceCountResponse.class) public class UpdateResourceCountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateResourceCountCmd.class.getName()); @@ -48,20 +45,20 @@ public class UpdateResourceCountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Update resource count for a specified account. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + required=true, description="If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.") private Long domainId; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description= "Type of resource to update. If specifies valid values are 0, 1, 2, 3, and 4. If not specified will update all resource counts" + - "0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") + "0 - Instance. Number of instances a user can create. " + + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") private Integer resourceType; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Update resource limits for project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Update resource limits for project") private Long projectId; ///////////////////////////////////////////////////// @@ -83,12 +80,12 @@ public class UpdateResourceCountCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -110,7 +107,7 @@ public class UpdateResourceCountCmd extends BaseCmd { @Override public void execute(){ - List result = _resourceLimitService.recalculateResourceCount(finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType()); + List result = _resourceLimitService.recalculateResourceCount(finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType()); if ((result != null) && (result.size()>0)){ ListResponse response = new ListResponse(); @@ -129,4 +126,4 @@ public class UpdateResourceCountCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recalculate resource counts"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java index 4c2801d4e5b..262d12dc264 100644 --- a/api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java @@ -14,27 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; import com.cloud.configuration.ResourceLimit; import com.cloud.user.UserContext; -@Implementation(description="Updates resource limits for an account or domain.", responseObject=ResourceLimitResponse.class) +@APICommand(name = "updateResourceLimit", description="Updates resource limits for an account or domain.", responseObject=ResourceLimitResponse.class) public class UpdateResourceLimitCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateResourceLimitCmd.class.getName()); private static final String s_name = "updateresourcelimitresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -42,28 +39,28 @@ public class UpdateResourceLimitCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Update resource for a specified account. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Update resource limits for project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Update resource limits for project") private Long projectId; - @Parameter(name=ApiConstants.MAX, type=CommandType.LONG, description=" Maximum resource limit.") + @Parameter(name=ApiConstants.MAX, type=CommandType.LONG, description=" Maximum resource limit.") private Long max; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, required=true, description="Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") private Integer resourceType; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getMax() { return max; } @@ -79,19 +76,19 @@ public class UpdateResourceLimitCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java index a6088d0b959..acafcbe19a9 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java @@ -14,23 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupRuleResponse; -import com.cloud.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +36,7 @@ import com.cloud.network.security.SecurityRule; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular egress rule for this security group", since="3.0.0") +@APICommand(name = "authorizeSecurityGroupEgress", responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular egress rule for this security group", since="3.0.0") @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName()); @@ -69,22 +67,19 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="an optional project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") + + @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with securityGroupName parameter", entityType=SecurityGroupResponse.class) private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -116,7 +111,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (securityGroupId != null && securityGroupName != null) { throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { @@ -124,11 +119,11 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { } securityGroupName = null; } - + if (securityGroupId == null) { throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); } - + return securityGroupId; } @@ -166,7 +161,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java index e8f8b986b4b..abd20fcc81d 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import java.util.Collection; import java.util.HashMap; @@ -24,15 +24,16 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +42,7 @@ import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; -@Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular ingress rule for this security group") +@APICommand(name = "authorizeSecurityGroupIngress", responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular ingress rule for this security group") @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName()); @@ -72,22 +73,19 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="an optional project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") + + @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with securityGroupName parameter", entityType=SecurityGroupResponse.class) private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -119,7 +117,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (securityGroupId != null && securityGroupName != null) { throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { @@ -127,11 +125,11 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { } securityGroupName = null; } - + if (securityGroupId == null) { throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); } - + return securityGroupId; } @@ -169,7 +167,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -210,7 +208,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Override public void execute() { if(cidrList != null){ - for(String cidr : cidrList ){ + for(String cidr : cidrList ){ if (!NetUtils.isValidCIDR(cidr)){ throw new ServerApiException(BaseCmd.PARAM_ERROR, cidr + " is an Invalid CIDR "); } diff --git a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java index 62fae921f7d..c494355e15e 100644 --- a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject = SecurityGroupResponse.class, description = "Creates a security group") +@APICommand(name = "createSecurityGroup", responseObject = SecurityGroupResponse.class, description = "Creates a security group") public class CreateSecurityGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName()); @@ -42,8 +43,7 @@ public class CreateSecurityGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the security group. Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the security group") @@ -52,8 +52,7 @@ public class CreateSecurityGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the security group") private String securityGroupName; - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, description = "Deploy vm for the project", entityType=ProjectAccountResponse.class) private Long projectId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java index 924e8a83d0f..15a00253b63 100644 --- a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java @@ -14,22 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceInUseException; import com.cloud.user.UserContext; -@Implementation(description="Deletes security group", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSecurityGroup", description="Deletes security group", responseObject=SuccessResponse.class) public class DeleteSecurityGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteSecurityGroupCmd.class.getName()); private static final String s_name = "deletesecuritygroupresponse"; @@ -41,18 +43,15 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the security group. Must be specified with domain ID") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the security group") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="the domain ID of account owning the security group", entityType=DomainResponse.class) private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="the project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with name parameter") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with name parameter", entityType=SecurityGroupResponse.class) private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="The ID of the security group. Mutually exclusive with id parameter") private String name; @@ -68,7 +67,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } @@ -77,18 +76,18 @@ public class DeleteSecurityGroupCmd extends BaseCmd { if (id != null && name != null) { throw new InvalidParameterValueException("name and id parameters are mutually exclusive"); } - + if (name != null) { id = _responseGenerator.getSecurityGroupId(name, getEntityOwnerId()); if (id == null) { throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId()); } } - + if (id == null) { throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command"); } - + return id; } @@ -102,17 +101,17 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute(){ try{ diff --git a/api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java similarity index 66% rename from api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java index 6da023af848..cf1ab84bad0 100644 --- a/api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java @@ -14,44 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.List; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.async.AsyncJob; -import com.cloud.network.security.SecurityGroupRules; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; - -@Implementation(description="Lists security groups", responseObject=SecurityGroupResponse.class) -public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSecurityGroupsCmd.class.getName()); - - private static final String s_name = "listsecuritygroupsresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="lists security groups by name") - private String securityGroupName; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="lists security groups by virtual machine id") +import com.cloud.async.AsyncJob; + +@APICommand(name = "listSecurityGroups", description="Lists security groups", responseObject=SecurityGroupResponse.class) +public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListSecurityGroupsCmd.class.getName()); + + private static final String s_name = "listsecuritygroupsresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="lists security groups by name") + private String securityGroupName; + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, description="lists security groups by virtual machine id", entityType=UserVmResponse.class) private Long virtualMachineId; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list the security group by the id provided") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, description="list the security group by the id provided", entityType=SecurityGroupResponse.class) private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -62,9 +57,9 @@ public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getId(){ - return id; + return id; } ///////////////////////////////////////////////////// @@ -78,13 +73,11 @@ public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { @Override public void execute(){ - List securityGroups = _securityGroupService.searchForSecurityGroupRules(this); - - ListResponse response = _responseGenerator.createSecurityGroupResponses(securityGroups); + ListResponse response = _queryService.searchForSecurityGroups(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.SecurityGroup; diff --git a/api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java index 273c145bdbd..53d8fcf59c7 100644 --- a/api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; -@Implementation(responseObject = SuccessResponse.class, description = "Deletes a particular egress rule from this security group", since="3.0.0") +@APICommand(name = "revokeSecurityGroupEgress", responseObject = SuccessResponse.class, description = "Deletes a particular egress rule from this security group", since="3.0.0") public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupEgressCmd.class.getName()); @@ -41,8 +37,7 @@ public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="security_group_rule") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the egress rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, required = true, description = "The ID of the egress rule", entityType=SecurityGroupRuleResponse.class) private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java index 9782c1d03f6..1f56dee9bca 100644 --- a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; -@Implementation(responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group") +@APICommand(name = "revokeSecurityGroupIngress", responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group") public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName()); @@ -41,8 +41,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="security_group_rule") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the ingress rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, required = true, description = "The ID of the ingress rule", entityType=SecurityGroupRuleResponse.class) private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/CreateSnapshotCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java index e78dbdabe67..14f46540cc3 --- a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java @@ -14,19 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SnapshotResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +35,7 @@ import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates an instant snapshot of a volume.", responseObject = SnapshotResponse.class) +@APICommand(name = "createSnapshot", description = "Creates an instant snapshot of a volume.", responseObject = SnapshotResponse.class) public class CreateSnapshotCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateSnapshotCmd.class.getName()); private static final String s_name = "createsnapshotresponse"; @@ -50,27 +47,24 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "The account of the snapshot. The account parameter must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.") private Long domainId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.LONG, required = true, description = "The ID of the disk volume") + @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.UUID, entityType = VolumeResponse.class, + required = true, description = "The ID of the disk volume") private Long volumeId; - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.LONG, description = "policy id of the snapshot, if this is null, then use MANUAL_POLICY.") + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description = "policy id of the snapshot, if this is null, then use MANUAL_POLICY.") private Long policyId; - + private String syncObjectType = BaseAsyncCmd.snapshotHostSyncObject; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - - public String getEntityTable() { - return "snapshots"; - } + public String getAccountName() { return accountName; @@ -91,7 +85,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { return Snapshot.MANUAL_POLICY_ID; } } - + private Long getHostId() { Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { @@ -100,7 +94,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { return _snapshotService.getHostIdForSnapshotOperation(volume); } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -116,23 +110,23 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Override public long getEntityOwnerId() { - + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } @@ -156,6 +150,7 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { Snapshot snapshot = _snapshotService.allocSnapshot(getVolumeId(), getPolicyId()); if (snapshot != null) { this.setEntityId(snapshot.getId()); + this.setEntityUuid(snapshot.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot"); } @@ -173,8 +168,8 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId); } } - - + + @Override public String getSyncObjType() { if (getSyncObjId() != null) { diff --git a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java index 6708bf9e8b2..cafb79e0523 100644 --- a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java @@ -14,17 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.projects.Project; @@ -32,7 +29,7 @@ import com.cloud.storage.Volume; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.user.Account; -@Implementation(description="Creates a snapshot policy for the account.", responseObject=SnapshotPolicyResponse.class) +@APICommand(name = "createSnapshotPolicy", description="Creates a snapshot policy for the account.", responseObject=SnapshotPolicyResponse.class) public class CreateSnapshotPolicyCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSnapshotPolicyCmd.class.getName()); @@ -49,18 +46,18 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { private Integer maxSnaps; @Parameter(name=ApiConstants.SCHEDULE, type=CommandType.STRING, required=true, description="time the snapshot is scheduled to be taken. " + - "Format is:" + - "* if HOURLY, MM" + - "* if DAILY, MM:HH" + - "* if WEEKLY, MM:HH:DD (1-7)" + - "* if MONTHLY, MM:HH:DD (1-28)") + "Format is:" + + "* if HOURLY, MM" + + "* if DAILY, MM:HH" + + "* if WEEKLY, MM:HH:DD (1-7)" + + "* if MONTHLY, MM:HH:DD (1-28)") private String schedule; @Parameter(name=ApiConstants.TIMEZONE, type=CommandType.STRING, required=true, description="Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long volumeId; @@ -97,30 +94,30 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); throw ex; } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } - + @Override public void execute(){ SnapshotPolicy result = _snapshotService.createPolicy(this, _accountService.getAccount(getEntityOwnerId())); diff --git a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteSnapshotCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java index 97c25a50df0..6def8730cbd 100644 --- a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Snapshot; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a snapshot of a disk volume.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSnapshot", description="Deletes a snapshot of a disk volume.", responseObject=SuccessResponse.class) public class DeleteSnapshotCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteSnapshotCmd.class.getName()); private static final String s_name = "deletesnapshotresponse"; @@ -41,11 +37,10 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the snapshot") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotResponse.class, + required=true, description="The ID of the snapshot") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -82,13 +77,13 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting snapshot: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Snapshot; + return AsyncJob.Type.Snapshot; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override diff --git a/api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java index ebd4d40d401..17f28d931ea --- a/api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java @@ -14,40 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes snapshot policies for the account.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSnapshotPolicies", description="Deletes snapshot policies for the account.", responseObject=SuccessResponse.class) public class DeleteSnapshotPoliciesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteSnapshotPoliciesCmd.class.getName()); private static final String s_name = "deletesnapshotpoliciesresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the Id of the snapshot policy") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description="the Id of the snapshot policy") private Long id; - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name=ApiConstants.IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of snapshots policy IDs separated by comma") + @Parameter(name=ApiConstants.IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description="list of snapshots policy IDs separated by comma") private List ids; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -60,7 +59,6 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd { return ids; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -69,7 +67,7 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java index c19924be627..647c503a445 100644 --- a/api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.storage.snapshot.SnapshotPolicy; -@Implementation(description="Lists snapshot policies.", responseObject=SnapshotPolicyResponse.class) +@APICommand(name = "listSnapshotPolicies", description="Lists snapshot policies.", responseObject=SnapshotPolicyResponse.class) public class ListSnapshotPoliciesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSnapshotPoliciesCmd.class.getName()); @@ -40,8 +40,8 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long volumeId; ///////////////////////////////////////////////////// @@ -72,7 +72,7 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { policyResponses.add(policyResponse); } response.setResponses(policyResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListSnapshotsCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListSnapshotsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java index cc2aad8f0e1..5c6e79c9170 100644 --- a/api/src/com/cloud/api/commands/ListSnapshotsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java @@ -14,37 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.storage.Snapshot; import com.cloud.utils.Pair; +@APICommand(name = "listSnapshots", description="Lists all available snapshots for the account.", responseObject=SnapshotResponse.class) +public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListSnapshotsCmd.class.getName()); + + private static final String s_name = "listsnapshotsresponse"; -@Implementation(description="Lists all available snapshots for the account.", responseObject=SnapshotResponse.class) -public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSnapshotsCmd.class.getName()); - - private static final String s_name = "listsnapshotsresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists snapshot by snapshot ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotResponse.class, + description="lists snapshot by snapshot ID") private Long id; @Parameter(name=ApiConstants.INTERVAL_TYPE, type=CommandType.STRING, description="valid values are HOURLY, DAILY, WEEKLY, and MONTHLY.") @@ -56,8 +55,8 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.SNAPSHOT_TYPE, type=CommandType.STRING, description="valid values are MANUAL or RECURRING.") private String snapshotType; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + description="the ID of the disk volume") private Long volumeId; ///////////////////////////////////////////////////// @@ -83,7 +82,7 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { public Long getVolumeId() { return volumeId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -92,9 +91,9 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Snapshot; + return AsyncJob.Type.Snapshot; } @Override @@ -109,7 +108,7 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { } response.setResponses(snapshotResponses, result.second()); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java similarity index 58% rename from api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java index f750ee88d88..bade8572f82 100644 --- a/api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java @@ -14,57 +14,58 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; import com.cloud.user.UserContext; -@Implementation(description="Create a new keypair and returns the private key", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "createSSHKeyPair", description="Create a new keypair and returns the private key", responseObject=SSHKeyPairResponse.class) public class CreateSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSSHKeyPairCmd.class.getName()); private static final String s_name = "createsshkeypairresponse"; - - + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + //Owner information @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the ssh key. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - + + public String getName() { + return name; + } + public String getAccountName() { return accountName; } - + public Long getDomainId() { return domainId; } @@ -72,31 +73,31 @@ public class CreateSSHKeyPairCmd extends BaseCmd { public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } + } - @Override - public void execute() { - SSHKeyPair r = _mgr.createSSHKeyPair(this); - SSHKeyPairResponse response = new SSHKeyPairResponse(r.getName(), r.getFingerprint(), r.getPrivateKey()); - response.setResponseName(getCommandName()); - response.setObjectName("keypair"); - this.setResponseObject(response); - } + @Override + public void execute() { + SSHKeyPair r = _mgr.createSSHKeyPair(this); + SSHKeyPairResponse response = new SSHKeyPairResponse(r.getName(), r.getFingerprint(), r.getPrivateKey()); + response.setResponseName(getCommandName()); + response.setObjectName("keypair"); + this.setResponseObject(response); + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java index d4f6b472f6d..9b6d403f48e 100644 --- a/api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java @@ -14,81 +14,81 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a keypair by name", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSSHKeyPair", description="Deletes a keypair by name", responseObject=SuccessResponse.class) public class DeleteSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSSHKeyPairCmd.class.getName()); private static final String s_name = "deletesshkeypairresponse"; - - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the keypair. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the keypair") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID associated with the keypair") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project associated with keypair") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="the project associated with keypair") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - - public String getAccountName() { - return accountName; + ///////////////////////////////////////////////////// + + public String getName() { + return name; + } + + public String getAccountName() { + return accountName; } public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// @Override - public void execute() { - boolean result = _mgr.deleteSSHKeyPair(this); - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setSuccess(result); - this.setResponseObject(response); - } + public void execute() { + boolean result = _mgr.deleteSSHKeyPair(this); + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setSuccess(result); + this.setResponseObject(response); + } - @Override - public String getCommandName() { - return s_name; - } - - @Override + @Override + public String getCommandName() { + return s_name; + } + + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); if ((account == null) || isAdmin(account.getType())) { diff --git a/api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java similarity index 58% rename from api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java index 8a6cb2730a4..27013dfd5f6 100644 --- a/api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java @@ -14,75 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; import com.cloud.utils.Pair; -@Implementation(description="List registered keypairs", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "listSSHKeyPairs", description="List registered keypairs", responseObject=SSHKeyPairResponse.class) public class ListSSHKeyPairsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListSSHKeyPairsCmd.class.getName()); private static final String s_name = "listsshkeypairsresponse"; - - + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="A key pair name to look for") - private String name; - - @Parameter(name="fingerprint", type=CommandType.STRING, description="A public key fingerprint to look for") + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="A key pair name to look for") + private String name; + + @Parameter(name="fingerprint", type=CommandType.STRING, description="A public key fingerprint to look for") private String fingerprint; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - - public String getFingerprint() { - return fingerprint; - } - - + ///////////////////////////////////////////////////// + + public String getName() { + return name; + } + + public String getFingerprint() { + return fingerprint; + } + + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override - public void execute() { - Pair, Integer> resultList = _mgr.listSSHKeyPairs(this); - List responses = new ArrayList(); - for (SSHKeyPair result : resultList.first()) { - SSHKeyPairResponse r = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); - r.setObjectName("sshkeypair"); - responses.add(r); - } - + + @Override + public void execute() { + Pair, Integer> resultList = _mgr.listSSHKeyPairs(this); + List responses = new ArrayList(); + for (SSHKeyPair result : resultList.first()) { + SSHKeyPairResponse r = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); + r.setObjectName("sshkeypair"); + responses.add(r); + } + ListResponse response = new ListResponse(); response.setResponses(responses, resultList.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); - } + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java similarity index 60% rename from api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java index 321be365fa4..2f08692f09b 100644 --- a/api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java @@ -14,97 +14,97 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; import com.cloud.user.UserContext; -@Implementation(description="Register a public key in a keypair under a certain name", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "registerSSHKeyPair", description="Register a public key in a keypair under a certain name", responseObject=SSHKeyPairResponse.class) public class RegisterSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterSSHKeyPairCmd.class.getName()); private static final String s_name = "registersshkeypairresponse"; - - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - - @Parameter(name="publickey", type=CommandType.STRING, required=true, description="Public key material of the keypair", length=5120) + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + + @Parameter(name="publickey", type=CommandType.STRING, required=true, description="Public key material of the keypair", length=5120) private String publicKey; //Owner information @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the ssh key. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } + ///////////////////////////////////////////////////// - public String getPublicKey() { - return publicKey; - } + public String getName() { + return name; + } + + public String getPublicKey() { + return publicKey; + } + + public String getAccountName() { + return accountName; + } - public String getAccountName() { - return accountName; - } - public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } - - @Override - public void execute() { - SSHKeyPair result = _mgr.registerSSHKeyPair(this); + } + + @Override + public void execute() { + SSHKeyPair result = _mgr.registerSSHKeyPair(this); SSHKeyPairResponse response = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); response.setResponseName(getCommandName()); - response.setObjectName("keypair"); + response.setObjectName("keypair"); this.setResponseObject(response); - } + } + + @Override + public String getCommandName() { + return s_name; + } - @Override - public String getCommandName() { - return s_name; - } - } diff --git a/api/src/com/cloud/api/commands/CreateTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java index d52c52fdd6b..54338bd24e2 100644 --- a/api/src/com/cloud/api/commands/CreateTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; import java.util.Collection; import java.util.HashMap; @@ -25,18 +25,17 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; -@Implementation(description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +@APICommand(name = "createTags", description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") public class CreateTagsCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(CreateTagsCmd.class.getName()); @@ -45,30 +44,30 @@ public class CreateTagsCmd extends BaseAsyncCmd{ // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, required=true, description = "Map of tags (key/value pairs)") private Map tag; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="type of the resource") private String resourceType; - - @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="list of resources to create the tags for") private List resourceIds; - + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="identifies client specific tag. " + - "When the value is not null, the tag can't be used by cloudStack code internally") + "When the value is not null, the tag can't be used by cloudStack code internally") private String customer; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public TaggedResourceType getResourceType(){ return _taggedResourceService.getResourceType(resourceType); - } - + } + public Map getTags() { Map tagsMap = null; if (!tag.isEmpty()) { @@ -84,11 +83,11 @@ public class CreateTagsCmd extends BaseAsyncCmd{ } return tagsMap; } - + public List getResourceIds() { return resourceIds; } - + public String getCustomer() { return customer; } @@ -111,7 +110,7 @@ public class CreateTagsCmd extends BaseAsyncCmd{ @Override public void execute() { List tags = _taggedResourceService.createTags(getResourceIds(), getResourceType(), getTags(), getCustomer()); - + if (tags != null && !tags.isEmpty()) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DeleteTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java similarity index 87% rename from api/src/com/cloud/api/commands/DeleteTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java index 03f734523e2..cf2ea9ec1cb 100644 --- a/api/src/com/cloud/api/commands/DeleteTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; import java.util.Collection; import java.util.HashMap; @@ -25,16 +25,16 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.server.ResourceTag.TaggedResourceType; -@Implementation(description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +@APICommand(name = "deleteTags", description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") public class DeleteTagsCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteTagsCmd.class.getName()); @@ -43,14 +43,14 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "Delete tags matching key/value pairs") private Map tag; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="Delete tag by resource type") private String resourceType; - - @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="Delete tags for resource id(s)") private List resourceIds; @@ -58,11 +58,11 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public TaggedResourceType getResourceType(){ return _taggedResourceService.getResourceType(resourceType); - } - + } + public Map getTags() { Map tagsMap = null; if (tag != null && !tag.isEmpty()) { @@ -78,7 +78,7 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ } return tagsMap; } - + public List getResourceIds() { return resourceIds; } @@ -101,7 +101,7 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ @Override public void execute() { boolean success = _taggedResourceService.deleteTags(getResourceIds(), getResourceType(), getTags()); - + if (success) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/ListTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java index b832b423fd0..e3dc108a757 100644 --- a/api/src/com/cloud/api/commands/ListTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java @@ -15,56 +15,43 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; -import java.util.ArrayList; -import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.server.ResourceTag; -import com.cloud.utils.Pair; - -@Implementation(description = "List resource tag(s)", responseObject = ResourceTagResponse.class, since = "Burbank") +@APICommand(name = "listTags", description = "List resource tag(s)", responseObject = ResourceTagResponse.class, since = "Burbank") public class ListTagsCmd extends BaseListProjectAndAccountResourcesCmd{ private static final String s_name = "listtagsresponse"; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, description="list by resource type") private String resourceType; - + @Parameter(name=ApiConstants.RESOURCE_ID, type=CommandType.STRING, description="list by resource id") private String resourceId; - + @Parameter(name=ApiConstants.KEY, type=CommandType.STRING, description="list by key") private String key; - + @Parameter(name=ApiConstants.VALUE, type=CommandType.STRING, description="list by value") private String value; - + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="list by customer name") private String customer; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @Override public void execute() { - - Pair, Integer> tags = _taggedResourceService.listTags(this); - ListResponse response = new ListResponse(); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags.first()) { - ResourceTagResponse tagResponse = _responseGenerator.createResourceTagResponse(tag, false); - tagResponses.add(tagResponse); - } - response.setResponses(tagResponses, tags.second()); - + + ListResponse response = _queryService.listTags(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } @@ -89,7 +76,7 @@ public class ListTagsCmd extends BaseListProjectAndAccountResourcesCmd{ public String getCommandName() { return s_name; } - + public String getCustomer() { return customer; } diff --git a/api/src/com/cloud/api/commands/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/CopyTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index d825bbce68c..c6461a75e28 --- a/api/src/com/cloud/api/commands/CopyTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -36,25 +37,25 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Copies a template from one zone to another.", responseObject=TemplateResponse.class) +@APICommand(name = "copyTemplate", description="Copies a template from one zone to another.", responseObject=TemplateResponse.class) public class CopyTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName()); private static final String s_name = "copytemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.DESTINATION_ZONE_ID, type=CommandType.LONG, required=true, description="ID of the zone the template is being copied to.") + @Parameter(name=ApiConstants.DESTINATION_ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="ID of the zone the template is being copied to.") private Long destZoneId; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Template ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="Template ID.") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.SOURCE_ZONE_ID, type=CommandType.LONG, required=true, description="ID of the zone the template is currently hosted on.") + @Parameter(name=ApiConstants.SOURCE_ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="ID of the zone the template is currently hosted on.") private Long sourceZoneId; @@ -107,29 +108,29 @@ public class CopyTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "copying template: " + getId() + " from zone: " + getSourceZoneId() + " to zone: " + getDestinationZoneId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override public void execute() throws ResourceAllocationException{ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); VirtualMachineTemplate template = _templateService.copyTemplate(this); - + if (template != null){ List listResponse = _responseGenerator.createTemplateResponses(template.getId(), getDestinationZoneId(), false); TemplateResponse response = new TemplateResponse(); if (listResponse != null && !listResponse.isEmpty()) { response = listResponse.get(0); } - - response.setResponseName(getCommandName()); + + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template"); @@ -137,7 +138,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd { } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/CreateTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java index 05f18fb9a49..e72b49b4e4d --- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -43,7 +42,7 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject = StoragePoolResponse.class, description = "Creates a template of a virtual machine. " + "The virtual machine must be in a STOPPED state. " +@APICommand(name = "createTemplate", responseObject = StoragePoolResponse.class, description = "Creates a template of a virtual machine. " + "The virtual machine must be in a STOPPED state. " + "A template created from this command is automatically designated as a private template visible to the account that created it.") public class CreateTemplateCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateTemplateCmd.class.getName()); @@ -68,8 +67,8 @@ import com.cloud.user.UserContext; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the template") private String templateName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name = ApiConstants.OS_TYPE_ID, type = CommandType.LONG, required = true, description = "the ID of the OS Type that best represents the OS of this template.") + @Parameter(name = ApiConstants.OS_TYPE_ID, type = CommandType.UUID, entityType = GuestOSResponse.class, + required = true, description = "the ID of the OS Type that best represents the OS of this template.") private Long osTypeId; @Parameter(name = ApiConstants.PASSWORD_ENABLED, type = CommandType.BOOLEAN, description = "true if the template supports the password reset feature; default is false") @@ -78,16 +77,16 @@ import com.cloud.user.UserContext; @Parameter(name = ApiConstants.REQUIRES_HVM, type = CommandType.BOOLEAN, description = "true if the template requres HVM, false otherwise") private Boolean requiresHvm; - @IdentityMapper(entityTableName="snapshots") - @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.LONG, description = "the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in") + @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.UUID, entityType = SnapshotResponse.class, + description = "the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in") private Long snapshotId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.LONG, description = "the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in") + @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.UUID, entityType = VolumeResponse.class, + description = "the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in") private Long volumeId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal") private Long vmId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="Optional, only for baremetal hypervisor. The directory name where template stored on CIFS server") @@ -95,17 +94,14 @@ import com.cloud.user.UserContext; @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - - public String getEntityTable() { - return "vm_template"; - } + public Integer getBits() { return bits; @@ -158,17 +154,17 @@ import com.cloud.user.UserContext; public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -192,29 +188,29 @@ import com.cloud.user.UserContext; if (volume != null) { accountId = volume.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } } else { Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId); if (snapshot != null) { accountId = snapshot.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); + throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); } } - + Account account = _accountService.getAccount(accountId); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(accountId); + Project project = _projectService.findByProjectAccountId(accountId); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return accountId; } @@ -241,13 +237,15 @@ import com.cloud.user.UserContext; public void create() throws ResourceAllocationException { if (isBareMetal()) { _bareMetalVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId())); - /*Baremetal creates template record after taking image proceeded, use vmId as entity id here*/ + /*Baremetal creates template record after taking image proceeded, use vmId as entity id and uuid here*/ this.setEntityId(vmId); + this.setEntityUuid(vmId.toString()); } else { VirtualMachineTemplate template = null; template = _userVmService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId())); if (template != null) { this.setEntityId(template.getId()); + this.setEntityUuid(template.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a template"); @@ -276,7 +274,7 @@ import com.cloud.user.UserContext; if (templateResponses != null && !templateResponses.isEmpty()) { response = templateResponses.get(0); } - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private template"); diff --git a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/DeleteTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java index bdbb95ba7e7..26f3e841f68 --- a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java @@ -14,39 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=SuccessResponse.class, description="Deletes a template from the system. All virtual machines using the deleted template will not be affected.") +@APICommand(name = "deleteTemplate", responseObject=SuccessResponse.class, description="Deletes a template from the system. All virtual machines using the deleted template will not be affected.") public class DeleteTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteTemplateCmd.class.getName()); private static final String s_name = "deletetemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the template") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of the template") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of zone of the template") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of zone of the template") private Long zoneId; @@ -66,12 +63,12 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + public static String getStaticName() { return s_name; } @@ -95,15 +92,15 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting template " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Template Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/ExtractTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java index 975897e3789..521293cb275 --- a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InternalErrorException; @@ -33,9 +30,9 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts a template", responseObject=ExtractResponse.class) +@APICommand(name = "extractTemplate", description="Extracts a template", responseObject=ExtractResponse.class) public class ExtractTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; @@ -43,20 +40,20 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the template") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of the template") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the ISO would be extracted") private String url; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="the ID of the zone where the ISO is originally located" ) + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="the ID of the zone where the ISO is originally located" ) private Long zoneId; @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -76,16 +73,16 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { public String getMode() { return mode; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } + public static String getStaticName() { return s_name; } @@ -110,19 +107,19 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "extracting template: " + getId() + " from zone: " + getZoneId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); Long uploadId = _templateService.extract(this); if (uploadId != null){ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode); diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java new file mode 100644 index 00000000000..7446195d5fb --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java @@ -0,0 +1,46 @@ +// Licensedname = "listTemplatePermissions", to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.template; + +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.log4j.Logger; + +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.template.VirtualMachineTemplate; + +@APICommand(name = "listTemplatePermissions", description="List template visibility and all accounts that have permissions to view this template.", responseObject=TemplatePermissionsResponse.class) +public class ListTemplatePermissionsCmd extends BaseListTemplateOrIsoPermissionsCmd { + protected String getResponseName() { + return "listtemplatepermissionsresponse"; + } + + @Override + public String getMediaType() { + return "template"; + } + + @Override + protected Logger getLogger() { + return Logger.getLogger(ListTemplatePermissionsCmd.class.getName()); + } + + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { + return !template.getFormat().equals(ImageFormat.ISO); + } +} diff --git a/api/src/com/cloud/api/commands/ListTemplatesCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListTemplatesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java index 6e1e0b4b754..a1464ccdc4e --- a/api/src/com/cloud/api/commands/ListTemplatesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java @@ -14,28 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.ArrayList; import java.util.List; import java.util.Set; +import com.cloud.storage.template.TemplateInfo; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.async.AsyncJob; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.Pair; -@Implementation(description="List all public, private, and privileged templates.", responseObject=TemplateResponse.class) +@APICommand(name = "listTemplates", description="List all public, private, and privileged templates.", responseObject=TemplateResponse.class) public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListTemplatesCmd.class.getName()); @@ -48,22 +50,22 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the template ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=TemplateResponse.class, + description="the template ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the template name") private String templateName; @Parameter(name=ApiConstants.TEMPLATE_FILTER, type=CommandType.STRING, required=true, description="possible values are \"featured\", \"self\", \"self-executable\", \"executable\", and \"community\"." + - "* featured-templates that are featured and are public" + - "* self-templates that have been registered/created by the owner" + - "* selfexecutable-templates that have been registered/created by the owner that can be used to deploy a new VM" + - "* executable-all templates that can be used to deploy a new VM* community-templates that are public.") + "* featured-templates that are featured and are public" + + "* self-templates that have been registered/created by the owner" + + "* selfexecutable-templates that have been registered/created by the owner that can be used to deploy a new VM" + + "* executable-all templates that can be used to deploy a new VM* community-templates that are public.") private String templateFilter; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list templates by zoneId") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="list templates by zoneId") private Long zoneId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -88,9 +90,9 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public boolean listInReadyState() { - + Account account = UserContext.current().getCaller(); // It is account specific if account is admin type and domainId and accountName are not null boolean isAccountSpecific = (account == null || isAdmin(account.getType())) && (getAccountName() != null) && (getDomainId() != null); @@ -109,11 +111,11 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + @Override public void execute(){ Set> templateZonePairSet = _mgr.listTemplates(this); diff --git a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/RegisterTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java index d33f5048feb..b3677b9d3a1 --- a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.net.URISyntaxException; import java.util.Collection; @@ -23,21 +23,23 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.UserContext; -@Implementation(description="Registers an existing template into the CloudStack cloud. ", responseObject=TemplateResponse.class) +@APICommand(name = "registerTemplate", description="Registers an existing template into the CloudStack cloud. ", responseObject=TemplateResponse.class) public class RegisterTemplateCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterTemplateCmd.class.getName()); @@ -68,13 +70,13 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the template") private String templateName; - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, required=true, description="the ID of the OS Type that best represents the OS of this template.") - @IdentityMapper(entityTableName="guest_os") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + required=true, description="the ID of the OS Type that best represents the OS of this template.") private Long osTypeId; @Parameter(name=ApiConstants.PASSWORD_ENABLED, type=CommandType.BOOLEAN, description="true if the template supports the password reset feature; default is false") private Boolean passwordEnabled; - + @Parameter(name=ApiConstants.SSHKEY_ENABLED, type=CommandType.BOOLEAN, description="true if the template supports the sshkey upload feature; default is false") private Boolean sshKeyEnabled; @@ -87,12 +89,12 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the template is hosted. Possible URL include http:// and https://") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone the template is to be hosted on") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone the template is to be hosted on") private Long zoneId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") private Long domainId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") @@ -103,11 +105,11 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Register template for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Register template for the project") private Long projectId; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; @@ -150,7 +152,7 @@ public class RegisterTemplateCmd extends BaseCmd { public Boolean isPasswordEnabled() { return passwordEnabled; } - + public Boolean isSshKeyEnabled() { return sshKeyEnabled; } @@ -181,22 +183,22 @@ public class RegisterTemplateCmd extends BaseCmd { public String getChecksum() { return checksum; - } + } public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -216,9 +218,9 @@ public class RegisterTemplateCmd extends BaseCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } + } @Override public void execute() throws ResourceAllocationException{ @@ -228,7 +230,7 @@ public class RegisterTemplateCmd extends BaseCmd { ListResponse response = new ListResponse(); List templateResponses = _responseGenerator.createTemplateResponses(template.getId(), zoneId, false); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register template"); diff --git a/api/src/com/cloud/api/commands/UpdateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/UpdateTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java index 47440e2b0d7..01ea200293e --- a/api/src/com/cloud/api/commands/UpdateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates attributes of a template.", responseObject=TemplateResponse.class) -public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { - public static final Logger s_logger = Logger.getLogger(UpdateTemplateCmd.class.getName()); +@APICommand(name = "updateTemplate", description="Updates attributes of a template.", responseObject=TemplateResponse.class) +public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd { + public static final Logger s_logger = Logger.getLogger(UpdateTemplateCmd.class.getName()); private static final String s_name = "updatetemplateresponse"; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + @Override public Boolean isBootable() { return null; @@ -42,17 +43,17 @@ public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @SuppressWarnings("unchecked") public TemplateResponse getResponse() { return null; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -62,7 +63,7 @@ public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualMachineTemplate result = _mgr.updateTemplate(this); diff --git a/api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java similarity index 50% rename from api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java index b71ed98ab4d..8f3e660bd1a 100644 --- a/api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java @@ -14,29 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; import org.apache.log4j.Logger; -import com.cloud.api.Implementation; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(responseObject=SuccessResponse.class, description="Updates a template visibility permissions. " + - "A public template is visible to all accounts within the same domain. " + - "A private template is visible only to the owner of the template. " + - "A priviledged template is a private template with account permissions added. " + - "Only accounts specified under the template permissions are visible to them.") -public class UpdateTemplatePermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd { +@APICommand(name = "updateTemplatePermissions", responseObject=SuccessResponse.class, description="Updates a template visibility permissions. " + + "A public template is visible to all accounts within the same domain. " + + "A private template is visible only to the owner of the template. " + + "A priviledged template is a private template with account permissions added. " + + "Only accounts specified under the template permissions are visible to them.") +public class UpdateTemplatePermissionsCmd extends BaseUpdateTemplateOrIsoPermissionsCmd { protected String getResponseName() { - return "updatetemplatepermissionsresponse"; + return "updatetemplatepermissionsresponse"; } - - protected Logger getLogger() { - return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName()); - } - + + protected Logger getLogger() { + return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName()); + } + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeployVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java index f67ee8f6003..e675c83dd6f 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.Collection; @@ -24,16 +24,21 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -44,6 +49,8 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.IpAddress; +import com.cloud.network.Network; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.template.VirtualMachineTemplate; @@ -51,7 +58,8 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) + +@APICommand(name = "deployVirtualMachine", description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) public class DeployVMCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); @@ -61,16 +69,18 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="availability zone for the virtual machine") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="availability zone for the virtual machine") private Long zoneId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the ID of the service offering for the virtual machine") + @ACL + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering for the virtual machine") private Long serviceOfferingId; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, required=true, description="the ID of the template for the virtual machine") + @ACL + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType=TemplateResponse.class, + required=true, description="the ID of the template for the virtual machine") private Long templateId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="host name for the virtual machine") @@ -83,18 +93,24 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the virtual machine. Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") private Long domainId; //Network information - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") + @ACL + @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=NetworkResponse.class, + description="list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") private List networkIds; //DataDisk information - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.LONG, description="the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") + @ACL + @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the ID of the disk offering for the virtual machine. If the template is of ISO format," + + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the " + + "offering for the data disk volume. If the templateId parameter passed is from a Template object," + + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is " + + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") private Long diskOfferingId; @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId") @@ -112,42 +128,49 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.SSH_KEYPAIR, type=CommandType.STRING, description="name of the ssh key pair used to login to the virtual machine") private String sshKeyPairName; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="destination Host ID to deploy the VM to - parameter available for root admin only") private Long hostId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter") + + @ACL + @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups id that going to be applied to the virtual machine. " + + "Should be passed only when vm is created from a zone with Basic Network support." + + " Mutually exclusive with securitygroupnames parameter") private List securityGroupIdList; - - @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter") + + @ACL + @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups names that going to be applied to the virtual machine." + + " Should be passed only when vm is created from a zone with Basic Network support. " + + "Mutually exclusive with securitygroupids parameter") private List securityGroupNameList; - - @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=204 - requests to use ip 10.10.10.11 in network id=204") + + @ACL(checkKeyAccess=true) + @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, entityType={Network.class, IpAddress.class}, + description = "ip to network mapping. Can't be specified with networkIds parameter." + + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid") private Map ipToNetworkList; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the ip address for default vm's network") private String ipAddress; - + @Parameter(name=ApiConstants.KEYBOARD, type=CommandType.STRING, description="an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us") private String keyboard; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="Deploy vm for the project") private Long projectId; - + @Parameter(name=ApiConstants.START_VM, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to true if not specified") private Boolean startVm; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "vm_instance"; - } - + public String getAccountName() { if (accountName == null) { return UserContext.current().getCaller().getAccountName(); @@ -174,7 +197,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { return group; } - public HypervisorType getHypervisor() { + public HypervisorType getHypervisor() { return HypervisorType.getType(hypervisor); } @@ -182,7 +205,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (securityGroupNameList != null && securityGroupIdList != null) { throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter"); } - + //transform group names to ids here if (securityGroupNameList != null) { List securityGroupIds = new ArrayList(); @@ -193,7 +216,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { securityGroupIds.add(groupId); } - } + } return securityGroupIds; } else { return securityGroupIdList; @@ -244,11 +267,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public Long getHostId() { return hostId; } - + public boolean getStartVm() { return startVm == null ? true : startVm; } - + private Map getIpToNetworkMap() { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); @@ -260,12 +283,22 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { Iterator iter = ipsCollection.iterator(); while (iter.hasNext()) { HashMap ips = (HashMap) iter.next(); - Long networkId = Long.valueOf(_responseGenerator.getIdentiyId("networks", ips.get("networkid"))); + Long networkId; + Network network = _networkService.getNetwork(ips.get("networkid")); + if (network != null) { + networkId = network.getId(); + } else { + try { + networkId = Long.parseLong(ips.get("networkid")); + } catch(NumberFormatException e) { + throw new InvalidParameterValueException("Unable to translate and find entity with networkId: " + ips.get("networkid")); + } + } String requestedIp = (String) ips.get("ip"); ipToNetworkMap.put(networkId, requestedIp); } } - + return ipToNetworkMap; } @@ -288,7 +321,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -320,7 +353,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Override public void execute(){ UserVm result; - + if (getStartVm()) { try { UserContext.current().setEventDetails("Vm Id: "+getEntityId()); @@ -334,7 +367,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); @@ -343,7 +376,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { result = _userVmService.getUserVm(getEntityId()); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); @@ -419,6 +452,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (vm != null) { setEntityId(vm.getId()); + setEntityUuid(vm.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); } @@ -432,7 +466,6 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } + } } - } diff --git a/api/src/com/cloud/api/commands/DestroyVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DestroyVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java index 1f7a2bf68a7..db830d1a188 100644 --- a/api/src/com/cloud/api/commands/DestroyVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,7 +30,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Destroys a virtual machine. Once destroyed, only the administrator can recover it.", responseObject=UserVmResponse.class) +@APICommand(name = "destroyVirtualMachine", description="Destroys a virtual machine. Once destroyed, only the administrator can recover it.", responseObject=UserVmResponse.class) public class DestroyVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroyVMCmd.class.getName()); @@ -45,8 +40,8 @@ public class DestroyVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -85,13 +80,13 @@ public class DestroyVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "destroying vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -99,11 +94,11 @@ public class DestroyVMCmd extends BaseAsyncCmd { UserContext.current().setEventDetails("Vm Id: "+getId()); UserVm result; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.destroyVm(this); + result = _bareMetalVmService.destroyVm(this); } else { - result = _userVmService.destroyVm(this); + result = _userVmService.destroyVm(this); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName("virtualmachine"); diff --git a/api/src/com/cloud/api/commands/GetVMPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java similarity index 66% rename from api/src/com/cloud/api/commands/GetVMPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java index a6a3c6d011c..cd3a5609d8c 100644 --- a/api/src/com/cloud/api/commands/GetVMPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java @@ -14,36 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.security.InvalidParameterException; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GetVMPasswordResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GetVMPasswordResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(responseObject=GetVMPasswordResponse.class, description="Returns an encrypted password for the VM") +@APICommand(name = "getVMPassword", responseObject=GetVMPasswordResponse.class, description="Returns an encrypted password for the VM") public class GetVMPasswordCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetVMPasswordCmd.class.getName()); private static final String s_name = "getvmpasswordresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class + , required=true, description="The ID of the virtual machine") private Long id; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -52,20 +52,20 @@ public class GetVMPasswordCmd extends BaseCmd { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override - public void execute() { - String passwd = _mgr.getVMPassword(this); - if (passwd == null || passwd.equals("")) - throw new InvalidParameterException("No password for VM with id '" + getId() + "' found."); - - this.setResponseObject(new GetVMPasswordResponse(getCommandName(), passwd)); - } - + + @Override + public void execute() { + String passwd = _mgr.getVMPassword(this); + if (passwd == null || passwd.equals("")) + throw new InvalidParameterException("No password for VM with id '" + getId() + "' found."); + + this.setResponseObject(new GetVMPasswordResponse(getCommandName(), passwd)); + } + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -76,9 +76,8 @@ public class GetVMPasswordCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/ListVMsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java old mode 100755 new mode 100644 similarity index 57% rename from api/src/com/cloud/api/commands/ListVMsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java index 2f6f9886563..b74c8e70f13 --- a/api/src/com/cloud/api/commands/ListVMsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.EnumSet; @@ -22,21 +22,29 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IsoVmResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.uservm.UserVm; -import com.cloud.utils.Pair; -@Implementation(description="List the virtual machines owned by the account.", responseObject=UserVmResponse.class) +@APICommand(name = "listVirtualMachines", description="List the virtual machines owned by the account.", responseObject=UserVmResponse.class) public class ListVMsCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListVMsCmd.class.getName()); @@ -46,60 +54,63 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.GROUP_ID, type=CommandType.LONG, description="the group ID") + @Parameter(name=ApiConstants.GROUP_ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + description="the group ID") private Long groupId; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the virtual machine") private String instanceName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the pod ID") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="state of the virtual machine") private String state; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the availability zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the availability zone ID") private Long zoneId; - - @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="list by network type; true if need to list vms using Virtual Network, false otherwise") + + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, + description="list by network type; true if need to list vms using Virtual Network, false otherwise") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType=NetworkResponse.class, + description="list by network id") private Long networkId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the target hypervisor for the template") private String hypervisor; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to") + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="the storage ID where vm's volumes belong to") private Long storageId; - @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, " + - "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]. If no parameter is passed in, the details will be defaulted to all" ) - private List viewDetails; + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, + description="comma separated list of host details requested, " + + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]." + + " If no parameter is passed in, the details will be defaulted to all" ) + private List viewDetails; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, description="list vms by template") + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType=TemplateResponse.class, + description="list vms by template") private Long templateId; - - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ISO_ID, type=CommandType.LONG, description="list vms by iso") + + @Parameter(name=ApiConstants.ISO_ID, type=CommandType.UUID, entityType=IsoVmResponse.class, + description="list vms by iso") private Long isoId; - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list vms by vpc") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list vms by vpc") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -132,7 +143,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Boolean getForVirtualNetwork() { return forVirtualNetwork; } @@ -140,15 +151,15 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - + public Long getNetworkId() { return networkId; } - + public String getHypervisor() { - return hypervisor; - } - + return hypervisor; + } + public Long getStorageId() { return storageId; } @@ -156,7 +167,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getTemplateId() { return templateId; } - + public Long getIsoId() { return isoId; } @@ -164,7 +175,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getVpcId(){ return vpcId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -184,34 +195,24 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { } return dv; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - @Override + @Override public void execute(){ - Pair, Integer> result = _userVmService.searchForUserVMs(this); - ListResponse response = new ListResponse(); - EnumSet details = getDetails(); - List vmResponses; - if (details.contains(VMDetails.all)){ // for all use optimized version - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.first().toArray(new UserVm[result.first().size()])); - } - else { - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.first().toArray(new UserVm[result.first().size()])); - } - response.setResponses(vmResponses, result.second()); + ListResponse response = _queryService.searchForUserVMs(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } - } diff --git a/api/src/com/cloud/api/commands/RebootVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/RebootVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java index 9d8a18c0450..45ebc287913 100644 --- a/api/src/com/cloud/api/commands/RebootVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -35,17 +34,17 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Reboots a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "rebootVirtualMachine", description="Reboots a virtual machine.", responseObject=UserVmResponse.class) public class RebootVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RebootVMCmd.class.getName()); private static final String s_name = "rebootvirtualmachineresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -84,25 +83,25 @@ public class RebootVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting user vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Vm Id: "+getId()); UserVm result; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.rebootVirtualMachine(this); + result = _bareMetalVmService.rebootVirtualMachine(this); } else { - result = _userVmService.rebootVirtualMachine(this); + result = _userVmService.rebootVirtualMachine(this); } - + if (result !=null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ResetVMPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java index 1c036c81b20..a4c2b3772e9 100644 --- a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -34,20 +33,20 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject=UserVmResponse.class, description="Resets the password for virtual machine. " + - "The virtual machine must be in a \"Stopped\" state and the template must already " + - "support this feature for this command to take effect. [async]") +@APICommand(name = "resetPasswordForVirtualMachine", responseObject=UserVmResponse.class, description="Resets the password for virtual machine. " + + "The virtual machine must be in a \"Stopped\" state and the template must already " + + "support this feature for this command to take effect. [async]") public class ResetVMPasswordCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ResetVMPasswordCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ResetVMPasswordCmd.class.getName()); + + private static final String s_name = "resetpasswordforvirtualmachineresponse"; - private static final String s_name = "resetpasswordforvirtualmachineresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; // unexposed parameter needed for serializing/deserializing the command @@ -75,9 +74,9 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; - } + public String getCommandName() { + return s_name; + } @Override public long getEntityOwnerId() { @@ -98,13 +97,13 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd { public String getEventDescription() { return "resetting password for vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java new file mode 100644 index 00000000000..9b2452e355d --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java @@ -0,0 +1,88 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.vm; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.uservm.UserVm; + +@APICommand(name = "restoreVirtualMachine", description="Restore a VM to original template or specific snapshot", responseObject=UserVmResponse.class, since="3.0.0") +public class RestoreVMCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(RestoreVMCmd.class); + private static final String s_name = "restorevmresponse"; + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="Virtual Machine ID") + private Long vmId; + + @Override + public String getEventType() { + return EventTypes.EVENT_VM_RESTORE; + } + + @Override + public String getEventDescription() { + return "Restore a VM to orignal template or specific snapshot"; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + UserVm result; + UserContext.current().setEventDetails("Vm Id: " + getVmId()); + result = _userVmService.restoreVM(this); + if (result != null) { + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + UserVm vm = _responseGenerator.findUserVmById(getVmId()); + if (vm == null) { + return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked + } + return vm.getAccountId(); + } + + public long getVmId() { + return vmId; + } +} diff --git a/api/src/com/cloud/api/commands/StartVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/StartVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java index c77213fd5f9..36199d13c24 100644 --- a/api/src/com/cloud/api/commands/StartVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +36,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.utils.exception.ExecutionException; -@Implementation(responseObject = UserVmResponse.class, description = "Starts a virtual machine.") +@APICommand(name = "startVirtualMachine", responseObject = UserVmResponse.class, description = "Starts a virtual machine.") public class StartVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StartVMCmd.class.getName()); @@ -49,12 +46,12 @@ public class StartVMCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=UserVmResponse.class, + required = true, description = "The ID of the virtual machine") private Long id; - - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only", since="3.0.1") + + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="destination Host ID to deploy the VM to - parameter available for root admin only", since="3.0.1") private Long hostId; // /////////////////////////////////////////////////// @@ -64,10 +61,10 @@ public class StartVMCmd extends BaseAsyncCmd { public Long getId() { return id; } - + public Long getHostId() { return hostId; - } + } // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// @@ -115,7 +112,7 @@ public class StartVMCmd extends BaseAsyncCmd { public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { try { UserContext.current().setEventDetails("Vm Id: " + getId()); - + UserVm result ; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { result = _bareMetalVmService.startVirtualMachine(this); diff --git a/api/src/com/cloud/api/commands/StopVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/StopVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java index eaa617a4c69..8e589060520 100644 --- a/api/src/com/cloud/api/commands/StopVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +29,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject = UserVmResponse.class, description = "Stops a virtual machine.") +@APICommand(name = "stopVirtualMachine", responseObject = UserVmResponse.class, description = "Stops a virtual machine.") public class StopVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopVMCmd.class.getName()); @@ -44,8 +39,9 @@ public class StopVMCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") + @ACL + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=UserVmResponse.class, + required = true, description = "The ID of the virtual machine") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM " + diff --git a/api/src/com/cloud/api/commands/UpdateVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UpdateVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index 462fe194a8a..7f1e7efdc1a 100644 --- a/api/src/com/cloud/api/commands/UpdateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -14,17 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; + +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; @@ -32,7 +33,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Updates properties of a virtual machine. The VM has to be stopped and restarted for the " + +@APICommand(name = "updateVirtualMachine", description="Updates properties of a virtual machine. The VM has to be stopped and restarted for the " + "new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. " + "Therefore, stop the VM manually before issuing this call.", responseObject=UserVmResponse.class) public class UpdateVMCmd extends BaseCmd{ @@ -52,17 +53,17 @@ public class UpdateVMCmd extends BaseCmd{ @Parameter(name=ApiConstants.HA_ENABLE, type=CommandType.BOOLEAN, description="true if high-availability is enabled for the virtual machine, false otherwise") private Boolean haEnable; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; - - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS type that best represents this VM.") + + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType=GuestOSResponse.class, + description="the ID of the OS type that best represents this VM.") private Long osTypeId; - + @Parameter(name=ApiConstants.USER_DATA, type=CommandType.STRING, description="an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.", length=2048) private String userData; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -83,7 +84,7 @@ public class UpdateVMCmd extends BaseCmd{ public Long getId() { return id; } - + public String getUserData() { return userData; } @@ -100,11 +101,11 @@ public class UpdateVMCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); diff --git a/api/src/com/cloud/api/commands/UpgradeVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/UpgradeVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java index 56ddb820cb2..f2c3882bd3c 100644 --- a/api/src/com/cloud/api/commands/UpgradeVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java @@ -14,26 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + - "The virtual machine must be in a \"Stopped\" state for " + - "this command to take effect.") +@APICommand(name = "changeServiceForVirtualMachine", responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + + "The virtual machine must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; @@ -42,12 +40,12 @@ public class UpgradeVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the service offering ID to apply to the virtual machine") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the virtual machine") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -72,9 +70,9 @@ public class UpgradeVMCmd extends BaseCmd { } public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -84,16 +82,16 @@ public class UpgradeVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } - + UserVm result = _userVmService.upgradeVirtualMachine(this); if (result != null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); diff --git a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/CreateVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java index a5cdcd757f2..9c2c6027ac9 100644 --- a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java @@ -14,21 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; import com.cloud.user.UserContext; import com.cloud.vm.InstanceGroup; -@Implementation(description = "Creates a vm group", responseObject = InstanceGroupResponse.class) +@APICommand(name = "createInstanceGroup", description = "Creates a vm group", responseObject = InstanceGroupResponse.class) public class CreateVMGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName()); @@ -41,15 +40,16 @@ public class CreateVMGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the instance group") private String groupName; - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the instance group. The account parameter must be used with the domainId parameter.") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, + description = "the account of the instance group. The account parameter must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of account owning the instance group") + @Parameter(name = ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description = "the domain ID of account owning the instance group") private Long domainId; - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "The project of the instance group") + @Parameter(name = ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectAccountResponse.class, + description = "The project of the instance group") private Long projectId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java index 18983fb20fa..47c2f764db6 100644 --- a/api/src/com/cloud/api/commands/DeleteVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java @@ -14,21 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; import com.cloud.vm.InstanceGroup; -@Implementation(description="Deletes a vm group", responseObject=SuccessResponse.class) +@APICommand(name = "deleteInstanceGroup", description="Deletes a vm group", responseObject=SuccessResponse.class) public class DeleteVMGroupCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVMGroupCmd.class.getName()); private static final String s_name = "deleteinstancegroupresponse"; @@ -37,8 +35,8 @@ public class DeleteVMGroupCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the instance group") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + required=true, description="the ID of the instance group") private Long id; ///////////////////////////////////////////////////// @@ -57,7 +55,7 @@ public class DeleteVMGroupCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { InstanceGroup group = _entityMgr.findById(InstanceGroup.class, getId()); @@ -67,7 +65,7 @@ public class DeleteVMGroupCmd extends BaseCmd{ return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ boolean result = _userVmService.deleteVmGroup(this); diff --git a/api/src/com/cloud/api/commands/ListVMGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java similarity index 60% rename from api/src/com/cloud/api/commands/ListVMGroupsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java index 34a5e195a3e..8a581b02e12 100644 --- a/api/src/com/cloud/api/commands/ListVMGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java @@ -14,24 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.vmgroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.utils.Pair; -import com.cloud.vm.InstanceGroup; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; -@Implementation(description="Lists vm groups", responseObject=InstanceGroupResponse.class) +@APICommand(name = "listInstanceGroups", description="Lists vm groups", responseObject=InstanceGroupResponse.class) public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListVMGroupsCmd.class.getName()); @@ -41,8 +35,8 @@ public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list instance groups by ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + description="list instance groups by ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list instance groups by name") @@ -65,22 +59,13 @@ public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } @Override public void execute(){ - Pair, Integer> groups = _mgr.searchForVmGroups(this); - ListResponse response = new ListResponse(); - List responses = new ArrayList(); - for (InstanceGroup group : groups.first()) { - InstanceGroupResponse groupResponse = _responseGenerator.createInstanceGroupResponse(group); - groupResponse.setObjectName("instancegroup"); - responses.add(groupResponse); - } - - response.setResponses(responses, groups.second()); + ListResponse response = _queryService.searchForVmGroups(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java index 27057d48e73..09313c0f797 100644 --- a/api/src/com/cloud/api/commands/UpdateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.InstanceGroupResponse; import com.cloud.user.Account; import com.cloud.vm.InstanceGroup; -@Implementation(description="Updates a vm group", responseObject=InstanceGroupResponse.class) +@APICommand(name = "updateInstanceGroup", description="Updates a vm group", responseObject=InstanceGroupResponse.class) public class UpdateVMGroupCmd extends BaseCmd{ private static final String s_name = "updateinstancegroupresponse"; @@ -38,8 +34,8 @@ public class UpdateVMGroupCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Instance group ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + required=true, description="Instance group ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="new instance group name") @@ -65,7 +61,7 @@ public class UpdateVMGroupCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { InstanceGroup group = _entityMgr.findById(InstanceGroup.class, getId()); diff --git a/api/src/com/cloud/api/commands/AttachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java old mode 100755 new mode 100644 similarity index 63% rename from api/src/com/cloud/api/commands/AttachVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java index bfd1a84865e..e48e4e43093 --- a/api/src/com/cloud/api/commands/AttachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Attaches a disk volume to a virtual machine.", responseObject=VolumeResponse.class) +@APICommand(name = "attachVolume", description="Attaches a disk volume to a virtual machine.", responseObject=VolumeResponse.class) public class AttachVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); private static final String s_name = "attachvolumeresponse"; ///////////////////////////////////////////////////// @@ -42,24 +42,24 @@ public class AttachVolumeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.DEVICE_ID, type=CommandType.LONG, description="the ID of the device to map the volume to within the guest OS. " + - "If no deviceId is passed in, the next available deviceId will be chosen. " + - "Possible values for a Linux OS are:" + - "* 1 - /dev/xvdb" + - "* 2 - /dev/xvdc" + - "* 4 - /dev/xvde" + - "* 5 - /dev/xvdf" + - "* 6 - /dev/xvdg" + - "* 7 - /dev/xvdh" + - "* 8 - /dev/xvdi" + - "* 9 - /dev/xvdj") + "If no deviceId is passed in, the next available deviceId will be chosen. " + + "Possible values for a Linux OS are:" + + "* 1 - /dev/xvdb" + + "* 2 - /dev/xvdc" + + "* 4 - /dev/xvde" + + "* 5 - /dev/xvdf" + + "* 6 - /dev/xvdg" + + "* 7 - /dev/xvdh" + + "* 8 - /dev/xvdi" + + "* 9 - /dev/xvdj") private Long deviceId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description=" the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description=" the ID of the virtual machine") private Long virtualMachineId; @@ -88,13 +88,13 @@ public class AttachVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -115,7 +115,7 @@ public class AttachVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching volume: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Volume Id: "+getId()+" VmId: "+getVirtualMachineId()); diff --git a/api/src/com/cloud/api/commands/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/CreateVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index d0585fe1547..04541b9fda7 100644 --- a/api/src/com/cloud/api/commands/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; +import com.cloud.storage.Snapshot; import com.cloud.storage.Volume; import com.cloud.user.UserContext; -@Implementation(responseObject=VolumeResponse.class, description="Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.") +@APICommand(name = "createVolume", responseObject=VolumeResponse.class, description="Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.") public class CreateVolumeCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); private static final String s_name = "createvolumeresponse"; ///////////////////////////////////////////////////// @@ -43,17 +43,18 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the disk volume. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project associated with the volume. Mutually exclusive with account parameter") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="the project associated with the volume. Mutually exclusive with account parameter") private Long projectId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the disk offering. If used with the account parameter returns the disk volume associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the disk offering. If used with the account parameter" + + " returns the disk volume associated with the account for the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.DISK_OFFERING_ID,required = false, type=CommandType.LONG, description="the ID of the disk offering. Either diskOfferingId or snapshotId must be passed in.") + @Parameter(name=ApiConstants.DISK_OFFERING_ID,required = false, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the ID of the disk offering. Either diskOfferingId or snapshotId must be passed in.") private Long diskOfferingId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the disk volume") @@ -62,22 +63,19 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="Arbitrary volume size") private Long size; - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.SNAPSHOT_ID, type=CommandType.LONG, description="the snapshot ID for the disk volume. Either diskOfferingId or snapshotId must be passed in.") + @Parameter(name=ApiConstants.SNAPSHOT_ID, type=CommandType.UUID, entityType=SnapshotResponse.class, + description="the snapshot ID for the disk volume. Either diskOfferingId or snapshotId must be passed in.") private Long snapshotId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the availability zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the ID of the availability zone") private Long zoneId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - public String getEntityTable() { - return "volumes"; - } + public String getAccountName() { return accountName; @@ -118,22 +116,22 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "volume"; + return "volume"; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -146,18 +144,19 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating volume: " + getVolumeName() + ((getSnapshotId() == null) ? "" : " from snapshot: " + getSnapshotId()); } - + @Override public void create() throws ResourceAllocationException{ Volume volume = _storageService.allocVolume(this); if (volume != null) { this.setEntityId(volume.getId()); + this.setEntityUuid(volume.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume"); - } + } } - + @Override public void execute(){ UserContext.current().setEventDetails("Volume Id: "+getEntityId()+((getSnapshotId() == null) ? "" : " from snapshot: " + getSnapshotId())); @@ -165,7 +164,18 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { if (volume != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(volume); //FIXME - have to be moved to ApiResponseHelper - response.setSnapshotId(getSnapshotId()); // if the volume was created from a snapshot, snapshotId will be set so we pass it back in the response + if (getSnapshotId() != null) { + Snapshot snap = _entityMgr.findById(Snapshot.class, getSnapshotId()); + if (snap != null) { + response.setSnapshotId(snap.getUuid()); // if the volume was + // created from a + // snapshot, + // snapshotId will + // be set so we pass + // it back in the + // response + } + } response.setResponseName(getCommandName()); this.setResponseObject(response); } else { diff --git a/api/src/com/cloud/api/commands/DeleteVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java index 6364e0bdf55..2b2e94cab6b 100644 --- a/api/src/com/cloud/api/commands/DeleteVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java @@ -14,33 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a detached disk volume.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVolume", description="Deletes a detached disk volume.", responseObject=SuccessResponse.class) public class DeleteVolumeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteVolumeCmd.class.getName()); private static final String s_name = "deletevolumeresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="The ID of the disk volume") private Long id; @@ -63,9 +63,9 @@ public class DeleteVolumeCmd extends BaseCmd { } public static String getResultObjectName() { - return "volume"; + return "volume"; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getId()); @@ -75,7 +75,7 @@ public class DeleteVolumeCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute() throws ConcurrentOperationException { UserContext.current().setEventDetails("Volume Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/DetachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/DetachVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java index 3a3557da8e9..c8ecddea699 --- a/api/src/com/cloud/api/commands/DetachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Volume; @@ -33,24 +29,24 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Detaches a disk volume from a virtual machine.", responseObject=VolumeResponse.class) +@APICommand(name = "detachVolume", description="Detaches a disk volume from a virtual machine.", responseObject=VolumeResponse.class) public class DetachVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DetachVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DetachVolumeCmd.class.getName()); private static final String s_name = "detachvolumeresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + description="the ID of the disk volume") private Long id; @Parameter(name=ApiConstants.DEVICE_ID, type=CommandType.LONG, description="the device ID on the virtual machine where volume is detached from") private Long deviceId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine where the volume is detached from") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine where the volume is detached from") private Long virtualMachineId; ///////////////////////////////////////////////////// @@ -77,17 +73,17 @@ public class DetachVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "volume"; + return "volume"; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -139,4 +135,4 @@ public class DetachVolumeCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach volume"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java old mode 100755 new mode 100644 similarity index 70% rename from api/src/com/cloud/api/commands/ExtractVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java index 2a9dbff9e70..43b25a83663 --- a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; import java.net.URISyntaxException; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -36,9 +37,9 @@ import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts volume", responseObject=ExtractResponse.class) +@APICommand(name = "extractVolume", description="Extracts volume", responseObject=ExtractResponse.class) public class ExtractVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractVolumeCmd.class.getName()); private static final String s_name = "extractvolumeresponse"; @@ -46,18 +47,18 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the volume") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the volume would be extracted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone where the volume is located") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the zone where the volume is located") private Long zoneId; - + @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; @@ -76,7 +77,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { public Long getZoneId() { return zoneId; } - + public String getMode() { return mode; } @@ -86,20 +87,20 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; - } - + public String getCommandName() { + return s_name; + } + public static String getStaticName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -122,7 +123,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Extraction job"; } - + @Override public void execute(){ try { @@ -133,15 +134,17 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { ExtractResponse response = new ExtractResponse(); response.setResponseName(getCommandName()); response.setObjectName("volume"); - response.setIdentityTableName("volumes"); - response.setId(id); - response.setName(_entityMgr.findById(Volume.class, id).getName()); - response.setZoneId(zoneId); - response.setZoneName(_entityMgr.findById(DataCenter.class, zoneId).getName()); + Volume vol = _entityMgr.findById(Volume.class, id); + response.setId(vol.getUuid()); + response.setName(vol.getName()); + DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId); + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); response.setMode(mode); - response.setUploadId(uploadId); + response.setUploadId(uploadInfo.getUuid()); response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(getEntityOwnerId()); + Account account = _entityMgr.findById(Account.class, getEntityOwnerId()); + response.setAccountId(account.getUuid()); response.setUrl(uploadInfo.getUploadUrl()); this.setResponseObject(response); } else { diff --git a/api/src/com/cloud/api/commands/ListVolumesCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java old mode 100755 new mode 100644 similarity index 60% rename from api/src/com/cloud/api/commands/ListVolumesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java index 7875c83aced..9ba4f346869 --- a/api/src/com/cloud/api/commands/ListVolumesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java @@ -14,61 +14,54 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; import com.cloud.async.AsyncJob; -import com.cloud.storage.Volume; -import com.cloud.utils.Pair; -@Implementation(description="Lists all volumes.", responseObject=VolumeResponse.class) -public class ListVolumesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVolumesCmd.class.getName()); - - private static final String s_name = "listvolumesresponse"; - +@APICommand(name = "listVolumes", description="Lists all volumes.", responseObject=VolumeResponse.class) +public class ListVolumesCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListVolumesCmd.class.getName()); + + private static final String s_name = "listvolumesresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="list volumes on specified host") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="list volumes on specified host") private Long hostId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + description="the ID of the disk volume") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the disk volume") private String volumeName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the pod id the disk volume belongs to") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the pod id the disk volume belongs to") private Long podId; @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the type of disk volume") private String type; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine") private Long virtualMachineId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the availability zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the ID of the availability zone") private Long zoneId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -101,7 +94,7 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -110,25 +103,15 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + @Override public void execute(){ - Pair, Integer> volumes = _storageService.searchForVolumes(this); - - ListResponse response = new ListResponse(); - List volResponses = new ArrayList(); - for (Volume volume : volumes.first()) { - VolumeResponse volResponse = _responseGenerator.createVolumeResponse(volume); - volResponse.setObjectName("volume"); - volResponses.add(volResponse); - } - - response.setResponses(volResponses, volumes.second()); + ListResponse response = _queryService.searchForVolumes(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/MigrateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java similarity index 57% rename from api/src/com/cloud/api/commands/MigrateVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java index 58f5d917ff2..30e672ada1b 100644 --- a/api/src/com/cloud/api/commands/MigrateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java @@ -14,38 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.storage.Volume; import com.cloud.user.Account; -@Implementation(description="Migrate volume", responseObject=VolumeResponse.class, since="3.0.0") +@APICommand(name = "migrateVolume", description="Migrate volume", responseObject=VolumeResponse.class, since="3.0.0") public class MigrateVolumeCmd extends BaseAsyncCmd { - private static final String s_name = "migratevolumeresponse"; - - ///////////////////////////////////////////////////// + private static final String s_name = "migratevolumeresponse"; + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the volume") private Long volumeId; - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, required=true, description="destination storage pool ID to migrate the volume to") + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + required=true, description="destination storage pool ID to migrate the volume to") private Long storageId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +55,7 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { } public Long getStoragePoolId() { - return storageId; + return storageId; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -65,10 +65,10 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { - Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume != null) { return volume.getAccountId(); } @@ -85,22 +85,22 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate volume Id: " + getVolumeId() + " to storage pool Id: "+ getStoragePoolId(); } - - + + @Override public void execute(){ - Volume result; - try { - result = _storageService.migrateVolume(getVolumeId(), getStoragePoolId()); - if (result != null) { - VolumeResponse response = _responseGenerator.createVolumeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - } catch (ConcurrentOperationException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate volume: "); - } - + Volume result; + try { + result = _storageService.migrateVolume(getVolumeId(), getStoragePoolId()); + if (result != null) { + VolumeResponse response = _responseGenerator.createVolumeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + } catch (ConcurrentOperationException e) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate volume: "); + } + } } diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java new file mode 100644 index 00000000000..e42bf3565cc --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java @@ -0,0 +1,153 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.volume; + +import org.apache.cloudstack.api.response.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.projects.Project; +import com.cloud.storage.Volume; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + + +@APICommand(name="resizeVolume", description="Resizes a volume", responseObject=VolumeResponse.class) +public class ResizeVolumeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(ResizeVolumeCmd.class.getName()); + + private static final String s_name = "resizevolumeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, entityType=VolumeResponse.class, type=CommandType.UUID, description="the ID of the disk volume") + private Long id; + + @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, required=false, description="New volume size in G") + private Long size; + + @Parameter(name=ApiConstants.SHRINK_OK, type=CommandType.BOOLEAN, required=false, description="Verify OK to Shrink") + private boolean shrinkOk; + + @Parameter(name=ApiConstants.DISK_OFFERING_ID, entityType=DiskOfferingResponse.class, type=CommandType.UUID, required=false, description="new disk offering id") + private Long newDiskOfferingId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getEntityId() { + return id; + } + + public Long getSize() { + return size; + } + + public boolean getShrinkOk() { + return shrinkOk; + } + + public Long getNewDiskOfferingId() { + return newDiskOfferingId; + } + + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.Volume; + } + + public static String getResultObjectName() { + return "volume"; + } + + @Override + public long getEntityOwnerId() { + + Volume volume = _entityMgr.findById(Volume.class, getEntityId()); + if (volume == null) { + throw new InvalidParameterValueException("Unable to find volume by id=" + id); + } + + Account account = _accountService.getAccount(volume.getAccountId()); + //Can resize volumes for enabled projects/accounts only + if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + if (project.getState() != Project.State.Active) { + throw new PermissionDeniedException("Can't add resources to project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active"); + } + } else if (account.getState() == Account.State.disabled) { + throw new PermissionDeniedException("The owner of volume " + id + " is disabled: " + account); + } + + return volume.getAccountId(); + } + + + @Override + public String getEventType() { + return EventTypes.EVENT_VOLUME_RESIZE; + } + + @Override + public String getEventDescription() { + return "Volume Id: " + getEntityId() + " to size " + getSize() + "G" ; + } + + @Override + public void execute(){ + UserContext.current().setEventDetails("Volume Id: " + getEntityId() + " to size " + getSize() + "G"); + Volume volume = _storageService.resizeVolume(this); + if (volume != null) { + VolumeResponse response = _responseGenerator.createVolumeResponse(volume); + //FIXME - have to be moved to ApiResponseHelper + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to resize volume"); + } + } +} diff --git a/api/src/com/cloud/api/commands/UploadVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java old mode 100755 new mode 100644 similarity index 61% rename from api/src/com/cloud/api/commands/UploadVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java index 299b04df386..4167ffd6460 --- a/api/src/com/cloud/api/commands/UploadVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java @@ -14,134 +14,131 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +package org.apache.cloudstack.api.command.user.volume; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.storage.Volume; -import com.cloud.user.UserContext; - -@Implementation(description="Uploads a data disk.", responseObject=VolumeResponse.class) -public class UploadVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UploadVolumeCmd.class.getName()); - private static final String s_name = "uploadvolumeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, required=true, description="the format for the volume. Possible values include QCOW2, OVA, and VHD.") - private String format; - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the volume") - private String volumeName; - - @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the volume is hosted. Possible URL include http:// and https://") - private String url; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone the volume is to be hosted on") - private Long zoneId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") - private Long domainId; - - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") - private String accountName; - - @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this volume") - private String checksum; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getFormat() { - return format; - } - - public String getVolumeName() { - return volumeName; - } - - public String getUrl() { - return url; - } - - public Long getZoneId() { - return zoneId; - } - - public Long getDomainId() { - return domainId; - } - - public String getAccountName() { - return accountName; - } - - public String getChecksum() { - return checksum; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, - InsufficientCapacityException, ServerApiException, - ConcurrentOperationException, ResourceAllocationException, - NetworkRuleConflictException { - - Volume volume = _storageService.uploadVolume(this); - if (volume != null){ - VolumeResponse response = _responseGenerator.createVolumeResponse(volume); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload volume"); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - Long accountId = finalyzeAccountId(accountName, domainId, null, true); - if (accountId == null) { - return UserContext.current().getCaller().getId(); - } - - return accountId; - } - - @Override - public String getEventDescription() { - return "uploading volume: " + getVolumeName() + " in the zone " + getZoneId(); - } - - @Override - public String getEventType() { - return EventTypes.EVENT_VOLUME_UPLOAD; - } - -} +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.storage.Volume; +import com.cloud.user.UserContext; + +@APICommand(name = "uploadVolume", description="Uploads a data disk.", responseObject=VolumeResponse.class) +public class UploadVolumeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UploadVolumeCmd.class.getName()); + private static final String s_name = "uploadvolumeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, required=true, description="the format for the volume. Possible values include QCOW2, OVA, and VHD.") + private String format; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the volume") + private String volumeName; + + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the volume is hosted. Possible URL include http:// and https://") + private String url; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone the volume is to be hosted on") + private Long zoneId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") + private Long domainId; + + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") + private String accountName; + + @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this volume") + private String checksum; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getFormat() { + return format; + } + + public String getVolumeName() { + return volumeName; + } + + public String getUrl() { + return url; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getDomainId() { + return domainId; + } + + public String getAccountName() { + return accountName; + } + + public String getChecksum() { + return checksum; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, + InsufficientCapacityException, ServerApiException, + ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + + Volume volume = _storageService.uploadVolume(this); + if (volume != null){ + VolumeResponse response = _responseGenerator.createVolumeResponse(volume); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload volume"); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, null, true); + if (accountId == null) { + return UserContext.current().getCaller().getId(); + } + + return accountId; + } + + @Override + public String getEventDescription() { + return "uploading volume: " + getVolumeName() + " in the zone " + getZoneId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_VOLUME_UPLOAD; + } + +} diff --git a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/CreateStaticRouteCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java index bf287e97200..96de56a5be5 100644 --- a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StaticRouteResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -36,16 +36,15 @@ import com.cloud.network.vpc.StaticRoute; import com.cloud.network.vpc.VpcGateway; import com.cloud.user.UserContext; -@Implementation(description="Creates a static route", responseObject=StaticRouteResponse.class) +@APICommand(name = "createStaticRoute", description="Creates a static route", responseObject=StaticRouteResponse.class) public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ private static final String s_name = "createstaticrouteresponse"; public static final Logger s_logger = Logger.getLogger(CreateStaticRouteCmd.class.getName()); - - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, required=true, - description="the gateway id we are creating static route for") + + @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + required=true, description="the gateway id we are creating static route for") private Long gatewayId; - + @Parameter(name = ApiConstants.CIDR, required = true, type = CommandType.STRING, description = "static route cidr") private String cidr; @@ -68,6 +67,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ try { StaticRoute result = _vpcService.createStaticRoute(getGatewayId(), getCidr()); setEntityId(result.getId()); + setEntityUuid(result.getUuid()); } catch (NetworkRuleConflictException ex) { s_logger.info("Network rule conflict: " + ex.getMessage()); s_logger.trace("Network rule conflict: ", ex); @@ -75,10 +75,6 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } } - @Override - public String getEntityTable() { - return "static_routes"; - } @Override public String getEventType() { @@ -100,7 +96,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ // State is different after the route is applied, so get new object here route = _entityMgr.findById(StaticRoute.class, getEntityId()); - StaticRouteResponse routeResponse = new StaticRouteResponse(); + StaticRouteResponse routeResponse = new StaticRouteResponse(); if (route != null) { routeResponse = _responseGenerator.createStaticRouteResponse(route); setResponseObject(routeResponse); @@ -113,7 +109,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } } } - + @Override public String getCommandName() { return s_name; @@ -127,7 +123,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -141,7 +137,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/CreateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/CreateVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index 35b526dc5af..8a2e1f641fb 100644 --- a/api/src/com/cloud/api/commands/CreateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,56 +37,55 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.UserContext; -@Implementation(description="Creates a VPC", responseObject=VpcResponse.class) +@APICommand(name = "createVPC", description="Creates a VPC", responseObject=VpcResponse.class) public class CreateVPCCmd extends BaseAsyncCreateCmd{ public static final Logger s_logger = Logger.getLogger(CreateVPCCmd.class.getName()); private static final String s_name = "createvpcresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the VPC. " + - "Must be used with the domainId parameter.") + "Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the VPC. " + - "If used with the account parameter returns the VPC associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the VPC. " + + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="create VPC for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="create VPC for the project") private Long projectId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the availability zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the availability zone") private Long zoneId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of " + "the VPC") private String displayText; - + @Parameter(name=ApiConstants.CIDR, type=CommandType.STRING, required=true, description="the cidr of the VPC. All VPC " + - "guest networks' cidrs should be within this CIDR") + "guest networks' cidrs should be within this CIDR") private String cidr; - - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.LONG, required=true, description="the ID of the VPC offering") + + @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class, + required=true, description="the ID of the VPC offering") private Long vpcOffering; - - @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, + + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="VPC network domain. All networks inside the VPC will belong to this domain") private String networkDomain; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getAccountName() { return accountName; } @@ -103,7 +105,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public String getCidr() { return cidr; } - + public String getDisplayText() { return displayText; } @@ -111,7 +113,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public Long getVpcOffering() { return vpcOffering; } - + public String getNetworkDomain() { return networkDomain; } @@ -122,11 +124,12 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ getCidr(), getNetworkDomain()); if (vpc != null) { this.setEntityId(vpc.getId()); + this.setEntityUuid(vpc.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC"); } } - + @Override public void execute() { Vpc vpc = null; @@ -139,13 +142,13 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } - + if (vpc != null) { VpcResponse response = _responseGenerator.createVpcResponse(vpc); response.setResponseName(getCommandName()); @@ -155,11 +158,6 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ } } - @Override - public String getEntityTable() { - return "vpc"; - } - @Override public String getEventType() { @@ -171,7 +169,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public String getEventDescription() { return "creating VPC. Id: " + getEntityId(); } - + @Override public String getCommandName() { return s_name; @@ -183,7 +181,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } } diff --git a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java index fa3c04dd257..c9e4463db14 100644 --- a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.StaticRoute; import com.cloud.user.UserContext; -@Implementation(description="Deletes a static route", responseObject=SuccessResponse.class) +@APICommand(name = "deleteStaticRoute", description="Deletes a static route", responseObject=SuccessResponse.class) public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteStaticRouteCmd.class.getName()); private static final String s_name = "deletestaticrouteresponse"; @@ -42,13 +39,13 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="static_routes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the static route") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StaticRouteResponse.class, + required=true, description="the ID of the static route") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +54,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +62,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_STATIC_ROUTE_DELETE; @@ -75,7 +72,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getEventDescription() { return ("Deleting static route id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +85,12 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Route Id: " + id); boolean result = _vpcService.revokeStaticRoute(id); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +98,8 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete static route"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -116,7 +113,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ } return route.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/DeleteVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeleteVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java index 21b84020b99..ed4e754f736 100644 --- a/api/src/com/cloud/api/commands/DeleteVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; - -@Implementation(description="Deletes a VPC", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVPC", description="Deletes a VPC", responseObject=SuccessResponse.class) public class DeleteVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVPCCmd.class.getName()); private static final String s_name = "deletevpcresponse"; @@ -42,11 +37,10 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the VPC") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcResponse.class, + required=true, description="the ID of the VPC") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +49,6 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -79,13 +72,13 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC"); - } + } }catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java index 389df5e3880..08da25df279 100644 --- a/api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import com.cloud.network.vpc.PrivateGateway; import com.cloud.utils.Pair; -@Implementation(description="List private gateways", responseObject=PrivateGatewayResponse.class) +@APICommand(name = "listPrivateGateways", description="List private gateways", responseObject=PrivateGatewayResponse.class) public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCmd{ public static final Logger s_logger = Logger.getLogger(ListPrivateGatewaysCmd.class.getName()); @@ -40,23 +40,23 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list private gateway by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + description="list private gateway by id") private Long id; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="list gateways by ip address") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="list gateways by vlan") private String vlan; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list gateways by vpc") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list gateways by vpc") private Long vpcId; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list gateways by state") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -69,15 +69,15 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm public String getIpAddress() { return ipAddress; } - + public Long getVpcId() { return vpcId; } - + public Long getId() { return id; } - + public String getState() { return state; } @@ -89,7 +89,7 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm public String getCommandName() { return s_name; } - + @Override public void execute() { Pair, Integer> gateways = _vpcService.listPrivateGateway(this); @@ -101,7 +101,7 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm } response.setResponses(projectResponses, gateways.second()); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListStaticRoutesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java index 93b533e6f6f..e9fada0a314 100644 --- a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java @@ -14,37 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; import com.cloud.network.vpc.StaticRoute; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.response.VpcResponse; -@Implementation(description="Lists all static routes", responseObject=StaticRouteResponse.class) +@APICommand(name = "listStaticRoutes", description="Lists all static routes", responseObject=StaticRouteResponse.class) public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { private static final String s_name = "liststaticroutesresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="static_routes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list static route by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StaticRouteResponse.class, + description="list static route by id") private Long id; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list static routes by vpc id") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list static routes by vpc id") private Long vpcId; - - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, description="list static routes by gateway id") + + @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + description="list static routes by gateway id") private Long gatewayId; public Long getId() { @@ -58,7 +59,7 @@ public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { public Long getGatewayId() { return gatewayId; } - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -66,20 +67,20 @@ public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> result = _vpcService.listStaticRoutes(this); ListResponse response = new ListResponse(); List routeResponses = new ArrayList(); - + for (StaticRoute route : result.first()) { StaticRouteResponse ruleData = _responseGenerator.createStaticRouteResponse(route); routeResponses.add(ruleData); } response.setResponses(routeResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java index 397c04a5ce2..f776302d3c1 100644 --- a/api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java @@ -14,52 +14,51 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.network.vpc.VpcOffering; -@Implementation(description="Lists VPC offerings", responseObject=VpcOfferingResponse.class) +@APICommand(name = "listVPCOfferings", description="Lists VPC offerings", responseObject=VpcOfferingResponse.class) public class ListVPCOfferingsCmd extends BaseListCmd{ public static final Logger s_logger = Logger.getLogger(ListVPCOfferingsCmd.class.getName()); private static final String _name = "listvpcofferingsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list VPC offerings by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class, + description="list VPC offerings by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list VPC offerings by name") private String vpcOffName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list VPC offerings by display text") private String displayText; - + @Parameter(name=ApiConstants.IS_DEFAULT, type=CommandType.BOOLEAN, description="true if need to list only default " + - "VPC offerings. Default value is false") + "VPC offerings. Default value is false") private Boolean isDefault; - - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, + + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list VPC offerings supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list VPC offerings by state") private String state; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -82,11 +81,11 @@ public class ListVPCOfferingsCmd extends BaseListCmd{ public List getSupportedServices() { return supportedServices; } - + public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -107,7 +106,7 @@ public class ListVPCOfferingsCmd extends BaseListCmd{ this.setResponseObject(response); } - + @Override public String getCommandName() { return _name; diff --git a/api/src/com/cloud/api/commands/ListVPCsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListVPCsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java index 6f9acc16fec..6d3c8bd06c7 100644 --- a/api/src/com/cloud/api/commands/ListVPCsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java @@ -14,77 +14,79 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; import com.cloud.network.vpc.Vpc; -@Implementation(description="Lists VPCs", responseObject=VpcResponse.class) +@APICommand(name = "listVPCs", description="Lists VPCs", responseObject=VpcResponse.class) public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public static final Logger s_logger = Logger.getLogger(ListVPCsCmd.class.getName()); private static final String s_name = "listvpcsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list VPC by id") + //////////////////////////////////////////////////// + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list VPC by id") private Long id; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list by zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="list by zone") private Long zoneId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list by name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="List by display text of " + "the VPC") private String displayText; - + @Parameter(name=ApiConstants.CIDR, type=CommandType.STRING, description="list by cidr of the VPC. All VPC " + "guest networks' cidrs should be within this CIDR") private String cidr; - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.LONG, description="list by ID of the VPC offering") + + @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class + , description="list by ID of the VPC offering") private Long VpcOffId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="list by account associated with the VPC. " + "Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="list by domain ID associated with the VPC. " + + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list by domain ID associated with the VPC. " + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; - - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, + + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list VPC supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list VPCs by state") private String state; - + @Parameter(name=ApiConstants.RESTART_REQUIRED, type=CommandType.BOOLEAN, description="list VPCs by restartRequired option") private Boolean restartRequired; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getAccountName() { return accountName; } @@ -104,7 +106,7 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public String getCidr() { return cidr; } - + public String getDisplayText() { return displayText; } @@ -112,23 +114,23 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public Long getVpcOffId() { return VpcOffId; } - + public Long getId() { return id; } - + public List getSupportedServices() { return supportedServices; } - + public String getState() { return state; } - + public Boolean getRestartRequired() { return restartRequired; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -136,8 +138,8 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ @Override public void execute() { List vpcs = _vpcService.listVpcs(getId(), getVpcName(), getDisplayText(), - getSupportedServices(), getCidr(), getVpcOffId(), getState(), getAccountName(), getDomainId(), - this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getZoneId(), this.isRecursive(), + getSupportedServices(), getCidr(), getVpcOffId(), getState(), getAccountName(), getDomainId(), + this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getZoneId(), this.isRecursive(), this.listAll(), getRestartRequired(), getTags(), getProjectId()); ListResponse response = new ListResponse(); List offeringResponses = new ArrayList(); diff --git a/api/src/com/cloud/api/commands/RestartVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/RestartVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java index bbb5cddbd63..4a23e6e6595 100644 --- a/api/src/com/cloud/api/commands/RestartVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,7 +29,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Restarts a VPC", responseObject=VpcResponse.class) +@APICommand(name = "restartVPC", description="Restarts a VPC", responseObject=VpcResponse.class) public class RestartVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(RestartVPCCmd.class.getName()); private static final String _name = "restartvpcresponse"; @@ -42,20 +37,20 @@ public class RestartVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="the id of the VPC") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -64,7 +59,7 @@ public class RestartVPCCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { Vpc vpc = _entityMgr.findById(Vpc.class, getId()); @@ -84,13 +79,13 @@ public class RestartVPCCmd extends BaseAsyncCmd{ this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart VPC"); - } + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); diff --git a/api/src/com/cloud/api/commands/UpdateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java index 0331be66bc4..2dc64dba267 100644 --- a/api/src/com/cloud/api/commands/UpdateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.event.EventTypes; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Updates a VPC", responseObject=VpcResponse.class) +@APICommand(name = "updateVPC", description="Updates a VPC", responseObject=VpcResponse.class) public class UpdateVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(UpdateVPCCmd.class.getName()); private static final String _name = "updatevpcresponse"; @@ -38,14 +37,14 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="the id of the VPC") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the VPC") private String displayText; @@ -53,19 +52,19 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcName() { return vpcName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -74,7 +73,7 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { Vpc vpc = _entityMgr.findById(Vpc.class, getId()); diff --git a/api/src/com/cloud/api/commands/AddVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java similarity index 52% rename from api/src/com/cloud/api/commands/AddVpnUserCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java index 10dc11a6e43..f2d19a7cce6 100644 --- a/api/src/com/cloud/api/commands/AddVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; import com.cloud.network.VpnUser; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds vpn users", responseObject=VpnUsersResponse.class) +@APICommand(name = "addVpnUser", description="Adds vpn users", responseObject=VpnUsersResponse.class) public class AddVpnUserCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddVpnUserCmd.class.getName()); @@ -43,108 +44,109 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="username for the vpn user") private String userName; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="password for the username") private String password; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the vpn user. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="add vpn user to the specific project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="add vpn user to the specific project") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } - public Long getDomainId() { - return domainId; - } + public Long getDomainId() { + return domainId; + } + + public String getUserName() { + return userName; + } + + public String getPassword() { + return password; + } + + public Long getProjectId() { + return projectId; + } - public String getUserName() { - return userName; - } - - public String getPassword() { - return password; - } - - public Long getProjectId() { - return projectId; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - - public String getEntityTable() { - return "vpn_users"; + + + @Override + public String getEventDescription() { + return "Add Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); } - @Override - public String getEventDescription() { - return "Add Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); - } - - @Override - public String getEventType() { - return EventTypes.EVENT_VPN_USER_ADD; - } + @Override + public String getEventType() { + return EventTypes.EVENT_VPN_USER_ADD; + } @Override public void execute(){ - VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); - Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); - if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); - } - - VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getId()); - vpnResponse.setUserName(vpnUser.getUsername()); - vpnResponse.setAccountName(account.getAccountName()); - - vpnResponse.setDomainId(account.getDomainId()); - vpnResponse.setDomainName(_entityMgr.findById(Domain.class, account.getDomainId()).getName()); - - vpnResponse.setResponseName(getCommandName()); - vpnResponse.setObjectName("vpnuser"); - this.setResponseObject(vpnResponse); + VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); + Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); + if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); + } + + VpnUsersResponse vpnResponse = new VpnUsersResponse(); + vpnResponse.setId(vpnUser.getUuid()); + vpnResponse.setUserName(vpnUser.getUsername()); + vpnResponse.setAccountName(account.getAccountName()); + + Domain domain = _entityMgr.findById(Domain.class, account.getDomainId()); + if (domain != null) { + vpnResponse.setDomainId(domain.getUuid()); + vpnResponse.setDomainName(domain.getName()); + } + + vpnResponse.setResponseName(getCommandName()); + vpnResponse.setObjectName("vpnuser"); + this.setResponseObject(vpnResponse); } @Override public void create() { Account owner = _accountService.getAccount(getEntityOwnerId()); - + VpnUser vpnUser = _ravService.addVpnUser(owner.getId(), userName, password); if (vpnUser == null) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); } setEntityId(vpnUser.getId()); - } + setEntityUuid(vpnUser.getUuid()); + } } diff --git a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java index 6787d1fb78f..b517af883c3 100644 --- a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java @@ -14,19 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; @@ -34,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.RemoteAccessVpn; -@Implementation(description="Creates a l2tp/ipsec remote access vpn", responseObject=RemoteAccessVpnResponse.class) +@APICommand(name = "createRemoteAccessVpn", description="Creates a l2tp/ipsec remote access vpn", responseObject=RemoteAccessVpnResponse.class) public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateRemoteAccessVpnCmd.class.getName()); @@ -43,61 +39,57 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; @Parameter(name="iprange", type=CommandType.STRING, required=false, description="the range of ip addresses to allocate to vpn clients. The first ip in the range will be taken by the vpn server") private String ipRange; - + @Deprecated @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the VPN. Must be used with domainId.") private String accountName; @Deprecated - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "user_ip_address"; - } - public Long getPublicIpId() { - return publicIpId; - } - - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - - public String getIpRange() { - return ipRange; - } - - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } - - public Boolean getOpenFirewall() { - if (openFirewall != null) { - return openFirewall; - } else { - return true; - } + return publicIpId; } - + + public String getAccountName() { + return accountName; + } + + public Long getDomainId() { + return domainId; + } + + public String getIpRange() { + return ipRange; + } + + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } + + public Boolean getOpenFirewall() { + if (openFirewall != null) { + return openFirewall; + } else { + return true; + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -108,48 +100,53 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; - } - public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getPublicIpId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + + throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; } - + @Override public void create() { try { RemoteAccessVpn vpn = _ravService.createRemoteAccessVpn(publicIpId, ipRange, getOpenFirewall(), getNetworkId()); if (vpn != null) { this.setEntityId(vpn.getServerAddressId()); + // find uuid for server ip address + IpAddress ipAddr = _entityMgr.findById(IpAddress.class, vpn.getServerAddressId()); + if (ipAddr != null) { + this.setEntityUuid(ipAddr.getUuid()); + } } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create remote access vpn"); } @@ -176,8 +173,8 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; diff --git a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java index 61af0fa01b1..3dc334d0e2a 100644 --- a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java @@ -14,31 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.vpc.Vpc; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "createVpnConnection", description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnConnectionCmd.class.getName()); @@ -47,26 +39,23 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.S2S_VPN_GATEWAY_ID, type=CommandType.LONG, required=true, description="id of the vpn gateway") + @Parameter(name=ApiConstants.S2S_VPN_GATEWAY_ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + required=true, description="id of the vpn gateway") private Long vpnGatewayId; - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.S2S_CUSTOMER_GATEWAY_ID, type=CommandType.LONG, required=true, description="id of the customer gateway") + @Parameter(name=ApiConstants.S2S_CUSTOMER_GATEWAY_ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of the customer gateway") private Long customerGatewayId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_vpn_connection"; - } - + public Long getVpnGatewayId() { return vpnGatewayId; } - + public Long getCustomerGatewayId() { return customerGatewayId; } @@ -103,6 +92,7 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { Site2SiteVpnConnection conn = _s2sVpnService.createVpnConnection(this); if (conn != null) { this.setEntityId(conn.getId()); + this.setEntityUuid(conn.getUuid()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create site to site vpn connection"); } @@ -129,8 +119,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; diff --git a/api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java index 9754f1c0f2c..bde98b0b44b 100644 --- a/api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "createVpnCustomerGateway", description="Creates site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnCustomerGatewayCmd.class.getName()); @@ -60,7 +59,7 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.IKE_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 1 VPN connection to the customer gateway, in seconds") private Long ikeLifetime; - + @Parameter(name=ApiConstants.ESP_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 2 VPN connection to the customer gateway, in seconds") private Long espLifetime; @@ -69,20 +68,17 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the gateway. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the gateway. " + - "If used with the account parameter returns the gateway associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the gateway. If used with the account parameter returns the " + + "gateway associated with the account for the specified domain.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_customer_gateway"; - } - + public String getName() { return name; } @@ -137,8 +133,8 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { accountId = UserContext.current().getCaller().getId(); @@ -146,16 +142,16 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { return accountId; } - @Override - public String getEventDescription() { - return "Create site-to-site VPN customer gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN customer gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_CREATE; - } - @Override public void execute(){ Site2SiteCustomerGateway result = _s2sVpnService.createCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java index 445c52a4734..4b405541a90 100644 --- a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java @@ -14,45 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.vpc.Vpc; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Creates site to site vpn local gateway", responseObject=Site2SiteVpnGatewayResponse.class) +@APICommand(name = "createVpnGateway", description="Creates site to site vpn local gateway", responseObject=Site2SiteVpnGatewayResponse.class) public class CreateVpnGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnGatewayCmd.class.getName()); - + private static final String s_name = "createvpngatewayresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn gateway") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + required=true, description="public ip address id of the vpn gateway") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_vpn_gateway"; - } - public Long getVpcId() { return vpcId; } @@ -95,7 +89,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPN gateway"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; diff --git a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java index 899142b357f..a634a0a7c5a 100644 --- a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.RemoteAccessVpn; import com.cloud.user.UserContext; - -@Implementation(description="Destroys a l2tp/ipsec remote access vpn", responseObject=SuccessResponse.class) + +@APICommand(name = "deleteRemoteAccessVpn", description="Destroys a l2tp/ipsec remote access vpn", responseObject=SuccessResponse.class) public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteRemoteAccessVpnCmd.class.getName()); @@ -39,54 +40,53 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; - + // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType=AccountResponse.class, expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - if (ownerId == null) { - RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); - if(vpnEntity != null) - return vpnEntity.getAccountId(); - - throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); - } - return ownerId; + @Override + public long getEntityOwnerId() { + if (ownerId == null) { + RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); + if(vpnEntity != null) + return vpnEntity.getAccountId(); + + throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); + } + return ownerId; } - @Override - public String getEventDescription() { - return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; - } + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; + } @Override public void execute() throws ResourceUnavailableException { _ravService.destroyRemoteAccessVpn(publicIpId, UserContext.current().getCaller()); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -96,5 +96,5 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _ravService.getRemoteAccessVpn(publicIpId).getNetworkId(); } - + } diff --git a/api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java index afcd562fbda..23a7793ef88 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java @@ -14,25 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Delete site to site vpn connection", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnConnection", description="Delete site to site vpn connection", responseObject=SuccessResponse.class) public class DeleteVpnConnectionCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnConnectionCmd.class.getName()); @@ -41,18 +36,15 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + required=true, description="id of vpn connection") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_vpn_connection"; - } - + public Long getId() { return id; } @@ -67,8 +59,8 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteVpnConnection conn = _entityMgr.findById(Site2SiteVpnConnection.class, getId()); if (conn != null) { return conn.getAccountId(); @@ -76,16 +68,16 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN connection for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN connection for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CONNECTION_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CONNECTION_DELETE; - } - @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java index df853234dd2..181ee3bbc68 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; import com.cloud.user.Account; -@Implementation(description="Delete site to site vpn customer gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnCustomerGateway", description="Delete site to site vpn customer gateway", responseObject=SuccessResponse.class) public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnCustomerGatewayCmd.class.getName()); @@ -39,18 +35,15 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_customer_gateway"; - } - + public Long getId() { return id; } @@ -65,8 +58,8 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteCustomerGateway gw = _entityMgr.findById(Site2SiteCustomerGateway.class, getId()); if (gw != null) { return gw.getAccountId(); @@ -74,16 +67,16 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN customer gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN customer gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_DELETE; - } - @Override public void execute(){ boolean result = _s2sVpnService.deleteCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java index b29f193ac71..9ac27d07664 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.user.Account; -@Implementation(description="Delete site to site vpn gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnGateway", description="Delete site to site vpn gateway", responseObject=SuccessResponse.class) public class DeleteVpnGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnGatewayCmd.class.getName()); @@ -39,18 +35,15 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_vpn_gateway"; - } - + public Long getId() { return id; } @@ -65,8 +58,8 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteVpnGateway gw = _entityMgr.findById(Site2SiteVpnGateway.class, getId()); if (gw != null) { return gw.getAccountId(); @@ -74,16 +67,16 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE; - } - @Override public void execute(){ boolean result = false; diff --git a/api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java index 9dd16448086..4b6a2058bee 100644 --- a/api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import com.cloud.network.RemoteAccessVpn; import com.cloud.utils.Pair; -@Implementation(description="Lists remote access vpns", responseObject=RemoteAccessVpnResponse.class) +@APICommand(name = "listRemoteAccessVpns", description="Lists remote access vpns", responseObject=RemoteAccessVpnResponse.class) public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListRemoteAccessVpnsCmd.class.getName()); @@ -40,16 +40,15 @@ public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesC ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getPublicIpId() { return publicIpId; } diff --git a/api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java index c7d5523d7b2..56f8aa547e8 100644 --- a/api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.utils.Pair; -@Implementation(description="Lists site to site vpn connection gateways", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "listVpnConnections", description="Lists site to site vpn connection gateways", responseObject=Site2SiteVpnConnectionResponse.class) public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnConnectionsCmd.class.getName()); @@ -40,20 +40,19 @@ public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + description="id of the vpn connection") private Long id; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="id of vpc") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="id of vpc") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -80,11 +79,11 @@ public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd if (conn == null) { continue; } - Site2SiteVpnConnectionResponse site2SiteVpnConnectonRes = _responseGenerator.createSite2SiteVpnConnectionResponse(conn); - site2SiteVpnConnectonRes.setObjectName("vpnconnection"); + Site2SiteVpnConnectionResponse site2SiteVpnConnectonRes = _responseGenerator.createSite2SiteVpnConnectionResponse(conn); + site2SiteVpnConnectonRes.setObjectName("vpnconnection"); connResponses.add(site2SiteVpnConnectonRes); } - + response.setResponses(connResponses, conns.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java index 51fde93976e..0e4209ba873 100644 --- a/api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.network.Site2SiteCustomerGateway; import com.cloud.utils.Pair; -@Implementation(description="Lists site to site vpn customer gateways", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "listVpnCustomerGateways", description="Lists site to site vpn customer gateways", responseObject=Site2SiteCustomerGatewayResponse.class) public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnCustomerGatewaysCmd.class.getName()); @@ -41,15 +40,15 @@ public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourc //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + description="id of the customer gateway") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -72,11 +71,11 @@ public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourc if (gw == null) { continue; } - Site2SiteCustomerGatewayResponse site2SiteCustomerGatewayRes = _responseGenerator.createSite2SiteCustomerGatewayResponse(gw); - site2SiteCustomerGatewayRes.setObjectName("vpncustomergateway"); + Site2SiteCustomerGatewayResponse site2SiteCustomerGatewayRes = _responseGenerator.createSite2SiteCustomerGatewayResponse(gw); + site2SiteCustomerGatewayRes.setObjectName("vpncustomergateway"); gwResponses.add(site2SiteCustomerGatewayRes); } - + response.setResponses(gwResponses, gws.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java index ec0c054fdb7..63f70e3efe0 100644 --- a/api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java @@ -14,41 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - +package org.apache.cloudstack.api.command.user.vpn; + import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.utils.Pair; -@Implementation(description="Lists site 2 site vpn gateways", responseObject=Site2SiteVpnGatewayResponse.class) -public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger (ListVpnGatewaysCmd.class.getName()); - - private static final String s_name = "listvpngatewaysresponse"; - +@APICommand(name = "listVpnGateways", description="Lists site 2 site vpn gateways", responseObject=Site2SiteVpnGatewayResponse.class) +public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger (ListVpnGatewaysCmd.class.getName()); + + private static final String s_name = "listvpngatewaysresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the vpn gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + description="id of the vpn gateway") private Long id; - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="id of vpc") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, description="id of vpc") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -66,8 +65,8 @@ public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; + public String getCommandName() { + return s_name; } @Override @@ -79,13 +78,13 @@ public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { if (gw == null) { continue; } - Site2SiteVpnGatewayResponse site2SiteVpnGatewayRes = _responseGenerator.createSite2SiteVpnGatewayResponse(gw); - site2SiteVpnGatewayRes.setObjectName("vpngateway"); + Site2SiteVpnGatewayResponse site2SiteVpnGatewayRes = _responseGenerator.createSite2SiteVpnGatewayResponse(gw); + site2SiteVpnGatewayRes.setObjectName("vpngateway"); gwResponses.add(site2SiteVpnGatewayRes); } - + response.setResponses(gwResponses, gws.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); - } -} + } +} diff --git a/api/src/com/cloud/api/commands/ListVpnUsersCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/ListVpnUsersCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java index 9280ed59f0a..fb12f65faa5 100644 --- a/api/src/com/cloud/api/commands/ListVpnUsersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; import com.cloud.network.VpnUser; import com.cloud.utils.Pair; -@Implementation(description="Lists vpn users", responseObject=VpnUsersResponse.class) +@APICommand(name = "listVpnUsers", description="Lists vpn users", responseObject=VpnUsersResponse.class) public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnUsersCmd.class.getName()); @@ -40,13 +39,13 @@ public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpn_users") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the vpn user") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpnUsersResponse.class, + description="The uuid of the Vpn user") private Long id; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, description="the username of the vpn user.") private String userName; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -67,7 +66,7 @@ public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ Pair, Integer> vpnUsers = _ravService.searchForVpnUsers(this); diff --git a/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/RemoveVpnUserCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java index 151b3512273..bdad7e31dd9 100644 --- a/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Removes vpn user", responseObject=SuccessResponse.class) +@APICommand(name = "removeVpnUser", description="Removes vpn user", responseObject=SuccessResponse.class) public class RemoveVpnUserCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveVpnUserCmd.class.getName()); @@ -41,69 +42,68 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="username for the vpn user") private String userName; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the vpn user. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="remove vpn user from the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="remove vpn user from the project") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } - public Long getDomainId() { - return domainId; - } + public Long getDomainId() { + return domainId; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } + + public Long getProjecId() { + return projectId; + } - public Long getProjecId() { - return projectId; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - @Override - public String getEventDescription() { - return "Remove Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); - } + @Override + public String getEventDescription() { + return "Remove Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); + } - - @Override - public String getEventType() { - return EventTypes.EVENT_VPN_USER_REMOVE; - } + @Override + public String getEventType() { + return EventTypes.EVENT_VPN_USER_REMOVE; + } @Override public void execute(){ @@ -112,10 +112,10 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { if (!result) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove vpn user"); } - + if (!_ravService.applyVpnUsers(owner.getId(), userName)) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply vpn user removal"); - } + } SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java index a2ceedbabdd..ed28ea5610f 100644 --- a/api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Reset site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "resetVpnConnection", description="Reset site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class ResetVpnConnectionCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ResetVpnConnectionCmd.class.getName()); @@ -41,33 +37,31 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + required=true, description="id of vpn connection") private Long id; - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for connection. Must be used with domainId.") + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for connection. " + + "Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for connection. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for connection. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_vpn_connection"; - } - + public Long getDomainId() { return domainId; } - + public Long getAccountId() { return getEntityOwnerId(); } - + public Long getId() { return id; } @@ -82,8 +76,8 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { return UserContext.current().getCaller().getId(); @@ -91,16 +85,16 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Reset site-to-site VPN connection for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Reset site-to-site VPN connection for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CONNECTION_RESET; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CONNECTION_RESET; - } - @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java index 491c1f6e49b..7564129c38f 100644 --- a/api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java @@ -14,24 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Update site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "updateVpnCustomerGateway", description="Update site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateVpnCustomerGatewayCmd.class.getName()); @@ -40,13 +35,13 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=false, description="name of this customer gateway") private String name; - + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="public ip address id of the customer gateway") private String gatewayIp; @@ -64,7 +59,7 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.IKE_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 1 VPN connection to the customer gateway, in seconds") private Long ikeLifetime; - + @Parameter(name=ApiConstants.ESP_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 2 VPN connection to the customer gateway, in seconds") private Long espLifetime; @@ -73,24 +68,20 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the gateway. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the gateway. " + - "If used with the account parameter returns the gateway associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the gateway. If used with the account parameter returns the " + + "gateway associated with the account for the specified domain.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getEntityTable() { - return "s2s_customer_gateway"; - } - - public Long getId() { + public Long getId() { return id; } - + public String getName() { return name; } @@ -137,8 +128,8 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { accountId = UserContext.current().getCaller().getId(); @@ -146,16 +137,16 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { return accountId; } - @Override - public String getEventDescription() { - return "Update site-to-site VPN customer gateway"; - } + @Override + public String getEventDescription() { + return "Update site-to-site VPN customer gateway"; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_UPDATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_UPDATE; - } - @Override public void execute(){ Site2SiteCustomerGateway result = _s2sVpnService.updateCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/ListZonesByCmd.java b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListZonesByCmd.java rename to api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java index f3016e98cff..5f5f9e7bda0 --- a/api/src/com/cloud/api/commands/ListZonesByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.zone; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; -@Implementation(description="Lists zones", responseObject=ZoneResponse.class) +@APICommand(name = "listZones", description="Lists zones", responseObject=ZoneResponse.class) public class ListZonesByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListZonesByCmd.class.getName()); @@ -39,24 +39,26 @@ public class ListZonesByCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description= "the ID of the zone") private Long id; - @Parameter(name=ApiConstants.AVAILABLE, type=CommandType.BOOLEAN, description="true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false.") + @Parameter(name=ApiConstants.AVAILABLE, type=CommandType.BOOLEAN, + description="true if you want to retrieve all available Zones. False if you only want to return the Zones" + + " from which you have at least one VM. Default is false.") private Boolean available; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain associated with the zone") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the domain associated with the zone") private Long domainId; - + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the zones") private Boolean showCapacities; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -64,19 +66,19 @@ public class ListZonesByCmd extends BaseListCmd { public Boolean isAvailable() { return available; } - + public Long getDomainId(){ - return domainId; + return domainId; } public Boolean getShowCapacities() { - return showCapacities; - } - + return showCapacities; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; diff --git a/api/src/com/cloud/api/response/AccountResponse.java b/api/src/org/apache/cloudstack/api/response/AccountResponse.java old mode 100755 new mode 100644 similarity index 93% rename from api/src/com/cloud/api/response/AccountResponse.java rename to api/src/org/apache/cloudstack/api/response/AccountResponse.java index dd69024dfbe..51d3352c647 --- a/api/src/com/cloud/api/response/AccountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AccountResponse.java @@ -14,20 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; +import com.cloud.user.Account; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") +@EntityReference(value = Account.class) public class AccountResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the account") - private IdentityProxy id = new IdentityProxy("account"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the account") private String name; @@ -36,13 +40,13 @@ public class AccountResponse extends BaseResponse { private Short accountType; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="id of the Domain the account belongs too") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="name of the Domain the account belongs too") private String domainName; - + @SerializedName(ApiConstants.DEFAULT_ZONE_ID) @Param(description="the default zone of the account") - private IdentityProxy defaultZoneId = new IdentityProxy("data_center"); + private String defaultZoneId; @SerializedName(ApiConstants.RECEIVED_BYTES) @Param(description="the total number of network traffic bytes received") private Long bytesReceived; @@ -100,7 +104,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("vmrunning") @Param(description="the total number of virtual machines running for this account") private Integer vmRunning; - + @SerializedName("projectlimit") @Param(description="the total number of projects the account can own", since="3.0.1") private String projectLimit; @@ -109,7 +113,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("projectavailable") @Param(description="the total number of projects available for administration by this account", since="3.0.1") private String projectAvailable; - + @SerializedName("networklimit") @Param(description="the total number of networks the account can own", since="3.0.1") private String networkLimit; @@ -118,7 +122,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("networkavailable") @Param(description="the total number of networks available to be created for this account", since="3.0.1") private String networkAvailable; - + @SerializedName("vpclimit") @Param(description="the total number of vpcs the account can own", since="3.0.5") private String vpcLimit; @@ -127,25 +131,31 @@ public class AccountResponse extends BaseResponse { @SerializedName("vpcavailable") @Param(description="the total number of vpcs available to be created for this account", since="3.0.5") private String vpcAvailable; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the account") private String state; @SerializedName(ApiConstants.IS_CLEANUP_REQUIRED) @Param(description="true if the account requires cleanup") private Boolean cleanupRequired; - + @SerializedName("user") @Param(description="the list of users associated with account", responseObject = UserResponse.class) private List users; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; - + @SerializedName(ApiConstants.ACCOUNT_DETAILS) @Param(description="details for the account") private Map details; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -156,8 +166,8 @@ public class AccountResponse extends BaseResponse { this.accountType = accountType; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -247,7 +257,7 @@ public class AccountResponse extends BaseResponse { public void setCleanupRequired(Boolean cleanupRequired) { this.cleanupRequired = cleanupRequired; } - + public void setUsers(List users) { this.users = users; } @@ -255,9 +265,9 @@ public class AccountResponse extends BaseResponse { public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } public void setProjectLimit(String projectLimit) { @@ -283,8 +293,8 @@ public class AccountResponse extends BaseResponse { public void setNetworkAvailable(String networkAvailable) { this.networkAvailable = networkAvailable; } - - public void setDefaultZone(Long defaultZoneId) { - this.defaultZoneId.setValue(defaultZoneId); + + public void setDefaultZone(String defaultZoneId) { + this.defaultZoneId = defaultZoneId; } } diff --git a/api/src/com/cloud/api/response/AlertResponse.java b/api/src/org/apache/cloudstack/api/response/AlertResponse.java similarity index 87% rename from api/src/com/cloud/api/response/AlertResponse.java rename to api/src/org/apache/cloudstack/api/response/AlertResponse.java index c54919e542e..f01a3e9c1f3 100644 --- a/api/src/com/cloud/api/response/AlertResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AlertResponse.java @@ -14,20 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.alert.Alert; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Alert.class) @SuppressWarnings("unused") public class AlertResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the alert") - private IdentityProxy id = new IdentityProxy("alert"); + private String id; @SerializedName(ApiConstants.TYPE) @Param(description="One of the following alert types: " + "MEMORY = 0, CPU = 1, STORAGE = 2, STORAGE_ALLOCATED = 3, PUBLIC_IP = 4, PRIVATE_IP = 5, HOST = 6, USERVM = 7, " + @@ -45,8 +47,8 @@ public class AlertResponse extends BaseResponse { @SerializedName(ApiConstants.SENT) @Param(description="the date and time the alert was sent") private Date lastSent; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setAlertType(Short alertType) { diff --git a/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java b/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java new file mode 100644 index 00000000000..1a47cd2a3d2 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java @@ -0,0 +1,110 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import java.util.Date; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.ResponseObject; +import com.cloud.async.AsyncJob; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value=AsyncJob.class) +@SuppressWarnings("unused") +public class AsyncJobResponse extends BaseResponse { + + @SerializedName("accountid") @Param(description="the account that executed the async command") + private String accountId; + + @SerializedName(ApiConstants.USER_ID) @Param(description="the user that executed the async command") + private String userId; + + @SerializedName("cmd") @Param(description="the async command executed") + private String cmd; + + @SerializedName("jobstatus") @Param(description="the current job status-should be 0 for PENDING") + private Integer jobStatus; + + @SerializedName("jobprocstatus") @Param(description="the progress information of the PENDING job") + private Integer jobProcStatus; + + @SerializedName("jobresultcode") @Param(description="the result code for the job") + private Integer jobResultCode; + + @SerializedName("jobresulttype") @Param(description="the result type") + private String jobResultType; + + @SerializedName("jobresult") @Param(description="the result reason") + private ResponseObject jobResult; + + @SerializedName("jobinstancetype") @Param(description="the instance/entity object related to the job") + private String jobInstanceType; + + @SerializedName("jobinstanceid") @Param(description="the unique ID of the instance/entity object related to the job") + private String jobInstanceId; + + @SerializedName(ApiConstants.CREATED) @Param(description=" the created date of the job") + private Date created; + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public void setCmd(String cmd) { + this.cmd = cmd; + } + + @Override + public void setJobStatus(Integer jobStatus) { + this.jobStatus = jobStatus; + } + + public void setJobProcStatus(Integer jobProcStatus) { + this.jobProcStatus = jobProcStatus; + } + + public void setJobResultCode(Integer jobResultCode) { + this.jobResultCode = jobResultCode; + } + + public void setJobResultType(String jobResultType) { + this.jobResultType = jobResultType; + } + + public void setJobResult(ResponseObject jobResult) { + this.jobResult = jobResult; + } + + public void setJobInstanceType(String jobInstanceType) { + this.jobInstanceType = jobInstanceType; + } + + public void setJobInstanceId(String jobInstanceId) { + this.jobInstanceId = jobInstanceId; + } + + public void setCreated(Date created) { + this.created = created; + } +} diff --git a/api/src/com/cloud/api/response/AutoScalePolicyResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java similarity index 82% rename from api/src/com/cloud/api/response/AutoScalePolicyResponse.java rename to api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java index 2fa3ad312fc..424a4fa446a 100644 --- a/api/src/com/cloud/api/response/AutoScalePolicyResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java @@ -1,33 +1,36 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.as.AutoScalePolicy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; import java.util.List; +@EntityReference(value=AutoScalePolicy.class) public class AutoScalePolicyResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the autoscale policy ID") - private IdentityProxy id = new IdentityProxy("autoscale_policies"); + private String id; @SerializedName(ApiConstants.ACTION) @Param(description = "the action to be executed if all the conditions evaluate to true for the specified duration.") @@ -49,19 +52,25 @@ public class AutoScalePolicyResponse extends BaseResponse implements ControlledE private String accountName; @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id autoscale policy") - private IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the autoscale policy") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the autoscale policy") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the autoscale policy") private String domainName; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setDuration(Integer duration) { @@ -85,9 +94,11 @@ public class AutoScalePolicyResponse extends BaseResponse implements ControlledE this.accountName = accountName; } + + @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -96,8 +107,8 @@ public class AutoScalePolicyResponse extends BaseResponse implements ControlledE } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/AutoScaleVmGroupResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java similarity index 81% rename from api/src/com/cloud/api/response/AutoScaleVmGroupResponse.java rename to api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java index d0d249d6f71..dc0e0155d5f 100644 --- a/api/src/com/cloud/api/response/AutoScaleVmGroupResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java @@ -1,41 +1,44 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.as.AutoScaleVmGroup; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; import java.util.List; +@EntityReference(value=AutoScaleVmGroup.class) public class AutoScaleVmGroupResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the autoscale vm group ID") - private IdentityProxy id = new IdentityProxy("autoscale_vmgroups"); + private String id; @SerializedName(ApiConstants.LBID) @Param(description = "the load balancer rule ID") - private IdentityProxy loadBalancerId = new IdentityProxy("firewall_rules"); + private String loadBalancerId; @SerializedName(ApiConstants.VMPROFILE_ID) @Param(description = "the autoscale profile that contains information about the vms in the vm group.") - private IdentityProxy profileId = new IdentityProxy("autoscale_vmprofiles"); + private String profileId; @SerializedName(ApiConstants.MIN_MEMBERS) @Param(description = "the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.") @@ -65,13 +68,13 @@ public class AutoScaleVmGroupResponse extends BaseResponse implements Controlled private String accountName; @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id vm profile") - private IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vm profile") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the vm profile") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the vm profile") private String domainName; @@ -80,16 +83,23 @@ public class AutoScaleVmGroupResponse extends BaseResponse implements Controlled } - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; } - public void setLoadBalancerId(Long loadBalancerId) { - this.loadBalancerId.setValue(loadBalancerId); + + public void setId(String id) { + this.id = id; } - public void setProfileId(Long profileId) { - this.profileId.setValue(profileId); + public void setLoadBalancerId(String loadBalancerId) { + this.loadBalancerId = loadBalancerId; + } + + public void setProfileId(String profileId) { + this.profileId = profileId; } public void setMinMembers(int minMembers) { @@ -121,9 +131,10 @@ public class AutoScaleVmGroupResponse extends BaseResponse implements Controlled this.accountName = accountName; } + @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -132,8 +143,8 @@ public class AutoScaleVmGroupResponse extends BaseResponse implements Controlled } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/AutoScaleVmProfileResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java similarity index 77% rename from api/src/com/cloud/api/response/AutoScaleVmProfileResponse.java rename to api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java index 08d95261715..0ae216706d0 100644 --- a/api/src/com/cloud/api/response/AutoScaleVmProfileResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java @@ -1,51 +1,54 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.response; +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; import java.util.HashMap; import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.Parameter; +import com.cloud.network.as.AutoScaleVmProfile; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.Parameter; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.google.gson.annotations.SerializedName; +@EntityReference(value=AutoScaleVmProfile.class) public class AutoScaleVmProfileResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the autoscale vm profile ID") - private IdentityProxy id = new IdentityProxy("autoscale_vmprofiles"); + private String id; /* Parameters related to deploy virtual machine */ @SerializedName(ApiConstants.ZONE_ID) @Param(description = "the availability zone to be used while deploying a virtual machine") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description = "the service offering to be used while deploying a virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description = "the template to be used while deploying a virtual machine") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName(ApiConstants.OTHER_DEPLOY_PARAMS) @Param(description = "parameters other than zoneId/serviceOfferringId/templateId to be used while deploying a virtual machine") @@ -63,7 +66,7 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll @SerializedName(ApiConstants.AUTOSCALE_USER_ID) @Param(description = "the ID of the user used to launch and destroy the VMs") - private IdentityProxy autoscaleUserId = new IdentityProxy("user"); + private String autoscaleUserId; @Parameter(name = ApiConstants.CS_URL, type = CommandType.STRING, description = "the API URL including port of the CloudStack Management Server example: http://server.cloud.com:8080/client/api?") private String csUrl; @@ -74,7 +77,7 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll @SerializedName(ApiConstants.PROJECT_ID) @Param(description = "the project id vm profile") - private IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description = "the project name of the vm profile") @@ -82,7 +85,7 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the vm profile") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain name of the vm profile") @@ -92,20 +95,27 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll } - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setId(String id) { + this.id = id; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setOtherDeployParams(String otherDeployParams) { @@ -127,8 +137,8 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -137,8 +147,8 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -146,8 +156,8 @@ public class AutoScaleVmProfileResponse extends BaseResponse implements Controll this.projectName = projectName; } - public void setAutoscaleUserId(Long autoscaleUserId) { - this.autoscaleUserId.setValue(autoscaleUserId); + public void setAutoscaleUserId(String autoscaleUserId) { + this.autoscaleUserId = autoscaleUserId; } public void setDestroyVmGraceperiod(Integer destroyVmGraceperiod) { diff --git a/api/src/com/cloud/api/response/CapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java similarity index 84% rename from api/src/com/cloud/api/response/CapabilitiesResponse.java rename to api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java index 4d98e173469..20d160dd2d5 100644 --- a/api/src/com/cloud/api/response/CapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class CapabilitiesResponse extends BaseResponse { @@ -27,21 +28,21 @@ public class CapabilitiesResponse extends BaseResponse { @SerializedName("cloudstackversion") @Param(description="version of the cloud stack") private String cloudStackVersion; - + @SerializedName("userpublictemplateenabled") @Param(description="true if user and domain admins can set templates to be shared, false otherwise") private boolean userPublicTemplateEnabled; - + @SerializedName("supportELB") @Param(description="true if region supports elastic load balancer on basic zones") private String supportELB; - + @SerializedName(ApiConstants.PROJECT_INVITE_REQUIRED) @Param(description="If invitation confirmation is required when add account to project") private Boolean projectInviteRequired; - + @SerializedName(ApiConstants.ALLOW_USER_CREATE_PROJECTS) @Param(description="true if regular user is allowed to create projects") private Boolean allowUsersCreateProjects; - + @SerializedName(ApiConstants.CUSTOM_DISK_OFF_MAX_SIZE) @Param(description="maximum size that can be specified when " + - "create disk from disk offering with custom size") + "create disk from disk offering with custom size") private Long diskOffMaxSize; @@ -61,13 +62,13 @@ public class CapabilitiesResponse extends BaseResponse { this.supportELB = supportELB; } - public void setProjectInviteRequired(Boolean projectInviteRequired) { - this.projectInviteRequired = projectInviteRequired; - } + public void setProjectInviteRequired(Boolean projectInviteRequired) { + this.projectInviteRequired = projectInviteRequired; + } - public void setAllowUsersCreateProjects(Boolean allowUsersCreateProjects) { - this.allowUsersCreateProjects = allowUsersCreateProjects; - } + public void setAllowUsersCreateProjects(Boolean allowUsersCreateProjects) { + this.allowUsersCreateProjects = allowUsersCreateProjects; + } public void setDiskOffMaxSize(Long diskOffMaxSize) { this.diskOffMaxSize = diskOffMaxSize; diff --git a/api/src/com/cloud/api/response/CapabilityResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilityResponse.java similarity index 92% rename from api/src/com/cloud/api/response/CapabilityResponse.java rename to api/src/org/apache/cloudstack/api/response/CapabilityResponse.java index 0281c180452..5fe3072fe87 100644 --- a/api/src/com/cloud/api/response/CapabilityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilityResponse.java @@ -14,17 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CapabilityResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the capability name") private String name; - + @SerializedName(ApiConstants.VALUE) @Param(description="the capability value") private String value; diff --git a/api/src/com/cloud/api/response/CapacityResponse.java b/api/src/org/apache/cloudstack/api/response/CapacityResponse.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/response/CapacityResponse.java rename to api/src/org/apache/cloudstack/api/response/CapacityResponse.java index d38d9ad0746..2c98dc9d6ca --- a/api/src/com/cloud/api/response/CapacityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapacityResponse.java @@ -14,31 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CapacityResponse extends BaseResponse { @SerializedName(ApiConstants.TYPE) @Param(description="the capacity type") private Short capacityType; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name") private String zoneName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name") private String podName; - + @SerializedName(ApiConstants.CLUSTER_ID) @Param(description="the Cluster ID") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the Cluster name") private String clusterName; @@ -60,12 +60,12 @@ public class CapacityResponse extends BaseResponse { this.capacityType = capacityType; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -76,12 +76,12 @@ public class CapacityResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -92,23 +92,23 @@ public class CapacityResponse extends BaseResponse { this.podName = podName; } - public Long getClusterId() { - return clusterId.getValue(); - } + public String getClusterId() { + return clusterId; + } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); - } + public void setClusterId(String clusterId) { + this.clusterId = clusterId; + } - public String getClusterName() { - return clusterName; - } + public String getClusterName() { + return clusterName; + } - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } - public Long getCapacityUsed() { + public Long getCapacityUsed() { return capacityUsed; } diff --git a/api/src/com/cloud/api/response/CloudIdentifierResponse.java b/api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java similarity index 83% rename from api/src/com/cloud/api/response/CloudIdentifierResponse.java rename to api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java index 11d2b0be7d8..d6d2fa70138 100644 --- a/api/src/com/cloud/api/response/CloudIdentifierResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CloudIdentifierResponse extends BaseResponse { - + @SerializedName(ApiConstants.USER_ID) @Param(description="the user ID for the cloud identifier") - private IdentityProxy userId = new IdentityProxy("user"); - + private String userId; + @SerializedName("cloudidentifier") @Param(description="the cloud identifier") private String cloudIdentifier; - + @SerializedName("signature") @Param(description="the signed response for the cloud identifier") private String signature; - - public Long getUserId() { - return userId.getValue(); + + public String getUserId() { + return userId; } - public void setUserId(Long userId) { - this.userId.setValue(userId); + public void setUserId(String userId) { + this.userId = userId; } - + public String getCloudIdentifier() { return cloudIdentifier; } @@ -47,7 +47,7 @@ public class CloudIdentifierResponse extends BaseResponse { public void setCloudIdentifier(String cloudIdentifier) { this.cloudIdentifier = cloudIdentifier; } - + public String getSignature() { return signature; } diff --git a/api/src/com/cloud/api/response/ClusterResponse.java b/api/src/org/apache/cloudstack/api/response/ClusterResponse.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/response/ClusterResponse.java rename to api/src/org/apache/cloudstack/api/response/ClusterResponse.java index 329f1f0e784..e436c9987e9 --- a/api/src/com/cloud/api/response/ClusterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ClusterResponse.java @@ -14,58 +14,60 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.org.Cluster; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = Cluster.class) public class ClusterResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the cluster ID") - private IdentityProxy id = new IdentityProxy("cluster"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the cluster name") private String name; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the cluster") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the cluster") private String podName; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the cluster") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the cluster") private String zoneName; @SerializedName("hypervisortype") @Param(description="the hypervisor type of the cluster") private String hypervisorType; - + @SerializedName("clustertype") @Param(description="the type of the cluster") private String clusterType; - + @SerializedName("allocationstate") @Param(description="the allocation state of the cluster") private String allocationState; - + @SerializedName("managedstate") @Param(description="whether this cluster is managed by cloudstack") private String managedState; - + @SerializedName("capacity") @Param(description="the capacity of the Cluster", responseObject = CapacityResponse.class) private List capacitites; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -76,12 +78,12 @@ public class ClusterResponse extends BaseResponse { this.name = name; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -92,12 +94,12 @@ public class ClusterResponse extends BaseResponse { this.podName = podName; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -107,29 +109,29 @@ public class ClusterResponse extends BaseResponse { public void setZoneName(String zoneName) { this.zoneName = zoneName; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String clusterType) { - this.clusterType = clusterType; + this.clusterType = clusterType; } - + public String getHypervisorType() { - return this.hypervisorType; + return this.hypervisorType; } - + public void setHypervisorType(String hypervisorType) { - this.hypervisorType = hypervisorType; + this.hypervisorType = hypervisorType; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } public String getManagedState() { @@ -140,11 +142,11 @@ public class ClusterResponse extends BaseResponse { this.managedState = managedState; } - public List getCapacitites() { - return capacitites; - } + public List getCapacitites() { + return capacitites; + } - public void setCapacitites(ArrayList arrayList) { - this.capacitites = arrayList; - } + public void setCapacitites(ArrayList arrayList) { + this.capacitites = arrayList; + } } diff --git a/api/src/com/cloud/api/response/ConditionResponse.java b/api/src/org/apache/cloudstack/api/response/ConditionResponse.java similarity index 80% rename from api/src/com/cloud/api/response/ConditionResponse.java rename to api/src/org/apache/cloudstack/api/response/ConditionResponse.java index a68e17935e0..f398f0aaed5 100644 --- a/api/src/com/cloud/api/response/ConditionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ConditionResponse.java @@ -15,20 +15,23 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.as.Condition; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Condition.class) @SuppressWarnings("unused") public class ConditionResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName("id") @Param(description = "the id of the Condition") - private final IdentityProxy id = new IdentityProxy("conditions"); + private String id; @SerializedName(value = ApiConstants.THRESHOLD) @Param(description = "Threshold Value for the counter.") @@ -44,7 +47,7 @@ public class ConditionResponse extends BaseResponse implements ControlledEntityR @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain id of the Condition owner") - private final IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain name of the owner.") @@ -52,11 +55,11 @@ public class ConditionResponse extends BaseResponse implements ControlledEntityR @SerializedName(ApiConstants.ZONE_ID) @Param(description = "zone id of counter") - private final IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.PROJECT_ID) @Param(description = "the project id of the Condition.") - private final IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description = "the project name of the Condition") @@ -70,8 +73,14 @@ public class ConditionResponse extends BaseResponse implements ControlledEntityR // ///////////////// Setters /////////////////////// // /////////////////////////////////////////////////// - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; + } + + @Override + public String getObjectId() { + return this.id; } public void setThreshold(long threshold) { @@ -92,12 +101,12 @@ public class ConditionResponse extends BaseResponse implements ControlledEntityR } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } @Override @@ -106,8 +115,8 @@ public class ConditionResponse extends BaseResponse implements ControlledEntityR } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/ConfigurationResponse.java b/api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java similarity index 93% rename from api/src/com/cloud/api/response/ConfigurationResponse.java rename to api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java index bcfac826cb6..ded0fb5fb39 100644 --- a/api/src/com/cloud/api/response/ConfigurationResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ConfigurationResponse extends BaseResponse { @SerializedName(ApiConstants.CATEGORY) @Param(description="the category of the configuration") diff --git a/api/src/com/cloud/api/response/ControlledEntityResponse.java b/api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java similarity index 87% rename from api/src/com/cloud/api/response/ControlledEntityResponse.java rename to api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java index ab4a367a21d..598ef082253 100644 --- a/api/src/com/cloud/api/response/ControlledEntityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java @@ -14,17 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; public interface ControlledEntityResponse { public void setAccountName(String accountName); - - public void setProjectId(Long projectId); - + + public void setProjectId(String projectId); + public void setProjectName(String projectName); - public void setDomainId(Long domainId); - + public void setDomainId(String domainId); + public void setDomainName(String domainName); } diff --git a/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java b/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java new file mode 100644 index 00000000000..116863256a9 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +public interface ControlledViewEntityResponse { + + public void setAccountName(String accountName); + + public void setProjectId(String projectId); + + public void setProjectName(String projectName); + + public void setDomainId(String domainId); + + public void setDomainName(String domainName); +} + diff --git a/api/src/com/cloud/api/response/CounterResponse.java b/api/src/org/apache/cloudstack/api/response/CounterResponse.java similarity index 79% rename from api/src/com/cloud/api/response/CounterResponse.java rename to api/src/org/apache/cloudstack/api/response/CounterResponse.java index c005f13824e..4dc44e767bf 100644 --- a/api/src/com/cloud/api/response/CounterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CounterResponse.java @@ -15,18 +15,22 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.network.as.Counter; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") +@EntityReference(value=Counter.class) public class CounterResponse extends BaseResponse { @SerializedName("id") @Param(description = "the id of the Counter") - private final IdentityProxy id = new IdentityProxy("counter"); + private String id; @SerializedName(value = ApiConstants.NAME) @Param(description = "Name of the counter.") @@ -42,10 +46,16 @@ public class CounterResponse extends BaseResponse { @SerializedName(ApiConstants.ZONE_ID) @Param(description = "zone id of counter") - private final IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setName(String name) { diff --git a/api/src/com/cloud/api/response/CreateCmdResponse.java b/api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java similarity index 65% rename from api/src/com/cloud/api/response/CreateCmdResponse.java rename to api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java index 5fa3b38ab31..e4c6c60c5ba 100644 --- a/api/src/com/cloud/api/response/CreateCmdResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java @@ -14,25 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CreateCmdResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - private IdentityProxy id = new IdentityProxy(); + private String id; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); - } - - public void setIdEntityTable(String entityTable) { - this.id.setTableName(entityTable); + public void setId(String id) { + this.id = id; } } diff --git a/api/src/com/cloud/api/response/CustomCertificateResponse.java b/api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java similarity index 81% rename from api/src/com/cloud/api/response/CustomCertificateResponse.java rename to api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java index 0738c33e271..f45b0c8e49b 100644 --- a/api/src/com/cloud/api/response/CustomCertificateResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CustomCertificateResponse extends BaseResponse { @SerializedName("message") @Param(description="message of the certificate upload operation") private String message; - public String getResultMessage() { - return message; - } + public String getResultMessage() { + return message; + } - public void setResultMessage(String msg) { - this.message = msg; - } + public void setResultMessage(String msg) { + this.message = msg; + } } diff --git a/api/src/com/cloud/api/response/DiskOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java similarity index 86% rename from api/src/com/cloud/api/response/DiskOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java index 9b37431df94..de3daf587ad 100644 --- a/api/src/com/cloud/api/response/DiskOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java @@ -14,21 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.DiskOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=DiskOffering.class) public class DiskOfferingResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="unique ID of the disk offering") - private IdentityProxy id = new IdentityProxy("disk_offering"); + private String id; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID this disk offering belongs to. Ignore this information as it is not currently applicable.") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name this disk offering belongs to. Ignore this information as it is not currently applicable.") private String domain; @@ -47,27 +50,27 @@ public class DiskOfferingResponse extends BaseResponse { @SerializedName("iscustomized") @Param(description="true if disk offering uses custom size, false otherwise") private Boolean customized; - + @SerializedName(ApiConstants.TAGS) @Param(description="the tags for the disk offering") private String tags; @SerializedName("storagetype") @Param(description="the storage type for this disk offering") private String storageType; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomain() { diff --git a/api/src/com/cloud/api/response/DomainResponse.java b/api/src/org/apache/cloudstack/api/response/DomainResponse.java similarity index 78% rename from api/src/com/cloud/api/response/DomainResponse.java rename to api/src/org/apache/cloudstack/api/response/DomainResponse.java index 52ba884ff55..c74e7c98d2f 100644 --- a/api/src/com/cloud/api/response/DomainResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DomainResponse.java @@ -14,16 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.domain.Domain; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@EntityReference(value = Domain.class) public class DomainResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the domain") - private IdentityProxy id = new IdentityProxy("domain"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the domain") private String domainName; @@ -32,26 +35,26 @@ public class DomainResponse extends BaseResponse { private Integer level; @SerializedName("parentdomainid") @Param(description="the domain ID of the parent domain") - private IdentityProxy parentDomainId = new IdentityProxy("domain"); + private String parentDomainId; @SerializedName("parentdomainname") @Param(description="the domain name of the parent domain") private String parentDomainName; @SerializedName("haschild") @Param(description="whether the domain has one or more sub-domains") private boolean hasChild; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; @SerializedName(ApiConstants.PATH) @Param(description="the path of the domain") private String path; - - public Long getId() { - return id.getValue(); + + public String getId() { + return this.id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getDomainName() { @@ -70,12 +73,12 @@ public class DomainResponse extends BaseResponse { this.level = level; } - public Long getParentDomainId() { - return parentDomainId.getValue(); + public String getParentDomainId() { + return parentDomainId; } - public void setParentDomainId(Long parentDomainId) { - this.parentDomainId.setValue(parentDomainId); + public void setParentDomainId(String parentDomainId) { + this.parentDomainId = parentDomainId; } public String getParentDomainName() { @@ -98,12 +101,12 @@ public class DomainResponse extends BaseResponse { this.networkDomain = networkDomain; } - public String getPath() { - return path; - } + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } - public void setPath(String path) { - this.path = path; - } - } diff --git a/api/src/com/cloud/api/response/DomainRouterResponse.java b/api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java similarity index 78% rename from api/src/com/cloud/api/response/DomainRouterResponse.java rename to api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java index d710aadb2e7..cf2f3f41f56 100644 --- a/api/src/com/cloud/api/response/DomainRouterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java @@ -14,27 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; + +import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.cloud.vm.VirtualMachine.State; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachine.class) @SuppressWarnings("unused") -public class DomainRouterResponse extends BaseResponse implements ControlledEntityResponse{ +public class DomainRouterResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the router") - private IdentityProxy id = new IdentityProxy("vm_instance"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID for the router") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name for the router") - private String zoneName; + private String zoneName; @SerializedName(ApiConstants.DNS1) @Param(description="the first DNS for the router") private String dns1; @@ -52,10 +57,10 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti private String name; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID for the router") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName(ApiConstants.HOST_ID) @Param(description="the host ID for the router") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the hostname for the router") private String hostName; @@ -68,9 +73,9 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.LINK_LOCAL_MAC_NETMASK) @Param(description="the link local netmask for the router") private String linkLocalNetmask; - + @SerializedName(ApiConstants.LINK_LOCAL_NETWORK_ID) @Param(description="the ID of the corresponding link local network") - private IdentityProxy linkLocalNetworkId = new IdentityProxy("networks"); + private String linkLocalNetworkId; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address for the router") private String publicIp; @@ -80,9 +85,9 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName("publicnetmask") @Param(description="the public netmask for the router") private String publicNetmask; - + @SerializedName("publicnetworkid") @Param(description="the ID of the corresponding public network") - private IdentityProxy publicNetworkId = new IdentityProxy("networks"); + private String publicNetworkId; @SerializedName("guestipaddress") @Param(description="the guest IP address for the router") private String guestIpAddress; @@ -92,12 +97,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName("guestnetmask") @Param(description="the guest netmask for the router") private String guestNetmask; - + @SerializedName("guestnetworkid") @Param(description="the ID of the corresponding guest network") - private IdentityProxy guestNetworkId = new IdentityProxy("networks"); + private String guestNetworkId; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="the template ID for the router") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName(ApiConstants.CREATED) @Param(description="the date and time the router was created") private Date created; @@ -107,59 +112,67 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the router") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID associated with the router") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain associated with the router") private String domainName; - + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; - + @SerializedName("isredundantrouter") @Param(description="if this router is an redundant virtual router") private boolean isRedundantRouter; - + @SerializedName("redundantstate") @Param(description="the state of redundant virtual router") private String redundantState; - + @SerializedName("templateversion") @Param(description="the version of template") private String templateVersion; - + @SerializedName("scriptsversion") @Param(description="the version of scripts") private String scriptsVersion; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the network belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - - @SerializedName("nic") @Param(description="the list of nics associated with the router", + private String vpcId; + + @SerializedName("nic") @Param(description="the list of nics associated with the router", responseObject = NicResponse.class, since="4.0") - private List nics; - + private Set nics; + + public DomainRouterResponse(){ + nics = new HashSet(); + } + + + @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { @@ -186,12 +199,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.name = name; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { @@ -222,8 +235,8 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.guestNetmask = guestNetmask; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setCreated(Date created) { @@ -240,8 +253,8 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -249,18 +262,18 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.domainName = domainName; } - public void setPublicNetworkId(Long publicNetworkId) { - this.publicNetworkId.setValue(publicNetworkId); + public void setPublicNetworkId(String publicNetworkId) { + this.publicNetworkId = publicNetworkId; } - public void setGuestNetworkId(Long guestNetworkId) { - this.guestNetworkId.setValue(guestNetworkId); + public void setGuestNetworkId(String guestNetworkId) { + this.guestNetworkId = guestNetworkId; } public void setLinkLocalIp(String linkLocalIp) { this.linkLocalIp = linkLocalIp; } - + public void setLinkLocalMacAddress(String linkLocalMacAddress) { this.linkLocalMacAddress = linkLocalMacAddress; } @@ -269,12 +282,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.linkLocalNetmask = linkLocalNetmask; } - public void setLinkLocalNetworkId(Long linkLocalNetworkId) { - this.linkLocalNetworkId.setValue(linkLocalNetworkId); + public void setLinkLocalNetworkId(String linkLocalNetworkId) { + this.linkLocalNetworkId = linkLocalNetworkId; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -292,33 +305,37 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti public String getTemplateVersion() { return this.templateVersion; } - + public void setTemplateVersion(String templateVersion) { this.templateVersion = templateVersion; } - + public String getScriptsVersion() { return this.scriptsVersion; } - + public void setScriptsVersion(String scriptsVersion) { this.scriptsVersion = scriptsVersion; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - - public void setNics(List nics) { + + public void setNics(Set nics) { this.nics = nics; } + + public void addNic(NicResponse nic) { + this.nics.add(nic); + } } diff --git a/api/src/com/cloud/api/response/EventResponse.java b/api/src/org/apache/cloudstack/api/response/EventResponse.java similarity index 83% rename from api/src/com/cloud/api/response/EventResponse.java rename to api/src/org/apache/cloudstack/api/response/EventResponse.java index 61292214fee..b2148db5da1 100644 --- a/api/src/com/cloud/api/response/EventResponse.java +++ b/api/src/org/apache/cloudstack/api/response/EventResponse.java @@ -14,20 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.event.Event; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Event.class) @SuppressWarnings("unused") -public class EventResponse extends BaseResponse implements ControlledEntityResponse{ +public class EventResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of the event") - private IdentityProxy id = new IdentityProxy("event"); + private String id; @SerializedName(ApiConstants.USERNAME) @Param(description="the name of the user who performed the action (can be different from the account if an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)") private String username; @@ -43,15 +45,15 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name for the account that owns the object being acted on in the event (e.g. the owner of the virtual machine, ip address, or security group)") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the id of the account's domain") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the account's domain") private String domainName; @@ -63,10 +65,10 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo private Event.State state; @SerializedName("parentid") @Param(description="whether the event is parented") - private IdentityProxy parentId = new IdentityProxy("event"); + private String parentId; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setUsername(String username) { @@ -91,8 +93,8 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -108,13 +110,13 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo this.state = state; } - public void setParentId(Long parentId) { - this.parentId.setValue(parentId); + public void setParentId(String parentId) { + this.parentId = parentId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/EventTypeResponse.java b/api/src/org/apache/cloudstack/api/response/EventTypeResponse.java similarity index 89% rename from api/src/com/cloud/api/response/EventTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/EventTypeResponse.java index 9f6f84f4840..4dcc44179a6 100644 --- a/api/src/com/cloud/api/response/EventTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/EventTypeResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class EventTypeResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="Event Type") diff --git a/api/src/com/cloud/api/response/ExceptionResponse.java b/api/src/org/apache/cloudstack/api/response/ExceptionResponse.java similarity index 84% rename from api/src/com/cloud/api/response/ExceptionResponse.java rename to api/src/org/apache/cloudstack/api/response/ExceptionResponse.java index 9ff2cf12437..5f8e642140a 100644 --- a/api/src/com/cloud/api/response/ExceptionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExceptionResponse.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.ArrayList; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ExceptionResponse extends BaseResponse { @SerializedName("uuidList") @Param(description="List of uuids associated with this error") - private ArrayList idList = new ArrayList(); + private ArrayList idList; @SerializedName("errorcode") @Param(description="numeric code associated with this error") private Integer errorCode; @SerializedName("cserrorcode") @Param(description="cloudstack exception error code associated with this error") - private Integer csErrorCode; - + private Integer csErrorCode; + @SerializedName("errortext") @Param(description="the text associated with this error") private String errorText = "Command failed due to Internal Server Error"; @@ -52,12 +52,12 @@ public class ExceptionResponse extends BaseResponse { this.errorText = errorText; } - public void addProxyObject(String tableName, Long id, String idFieldName) { - idList.add(new IdentityProxy(tableName, id, idFieldName)); + public void addProxyObject(String id) { + idList.add(id); return; } - public ArrayList getIdProxyList() { + public ArrayList getIdProxyList() { return idList; } diff --git a/server/src/com/cloud/server/api/response/ExternalFirewallResponse.java b/api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java similarity index 85% rename from server/src/com/cloud/server/api/response/ExternalFirewallResponse.java rename to api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java index 728db4b8c01..30fe86f88da 100644 --- a/server/src/com/cloud/server/api/response/ExternalFirewallResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java @@ -14,133 +14,132 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class ExternalFirewallResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external firewall") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; - + @SerializedName(ApiConstants.USERNAME) @Param(description="the username that's used to log in to the external firewall") private String username; - + @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the external firewall") private String publicInterface; - + @SerializedName(ApiConstants.USAGE_INTERFACE) @Param(description="the usage interface of the external firewall") private String usageInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the external firewall") private String privateInterface; - + @SerializedName(ApiConstants.PUBLIC_ZONE) @Param(description="the public security zone of the external firewall") private String publicZone; - + @SerializedName(ApiConstants.PRIVATE_ZONE) @Param(description="the private security zone of the external firewall") private String privateZone; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external firewall") private String numRetries; - + @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getUsername() { return username; } - + public void setUsername(String username) { this.username = username; } - + public String getPublicInterface() { return publicInterface; } - + public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } - + public String getUsageInterface() { return usageInterface; } - + public void setUsageInterface(String usageInterface) { this.usageInterface = usageInterface; } - + public String getPrivateInterface() { return privateInterface; } - + public void setPrivateInterface(String privateInterface) { this.privateInterface = privateInterface; } - + public String getPublicZone() { return publicZone; } - + public void setPublicZone(String publicZone) { this.publicZone = publicZone; } - + public String getPrivateZone() { return privateZone; } - + public void setPrivateZone(String privateZone) { this.privateZone = privateZone; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } - + public String getTimeout() { return timeout; } - + public void setTimeout(String timeout) { this.timeout = timeout; } diff --git a/server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java b/api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java similarity index 81% rename from server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java rename to api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java index 5eb7a96a134..6f80c1084f8 100644 --- a/server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java @@ -14,89 +14,88 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class ExternalLoadBalancerResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external load balancer") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external load balancer") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external load balancer") private String ipAddress; - + @SerializedName(ApiConstants.USERNAME) @Param(description="the username that's used to log in to the external load balancer") private String username; - + @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the external load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the external load balancer") private String privateInterface; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external load balancer") private String numRetries; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getUsername() { return username; } - + public void setUsername(String username) { this.username = username; } - + public String getPublicInterface() { return publicInterface; } - + public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } - + public String getPrivateInterface() { return privateInterface; } - + public void setPrivateInterface(String privateInterface) { this.privateInterface = privateInterface; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } diff --git a/api/src/com/cloud/api/response/ExtractResponse.java b/api/src/org/apache/cloudstack/api/response/ExtractResponse.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/response/ExtractResponse.java rename to api/src/org/apache/cloudstack/api/response/ExtractResponse.java index b285b454cc1..5d415e94349 --- a/api/src/com/cloud/api/response/ExtractResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExtractResponse.java @@ -14,85 +14,82 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ExtractResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of extracted object") - private IdentityProxy id = new IdentityProxy("vm_template"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the extracted object") private String name; - + @SerializedName("extractId") @Param(description="the upload id of extracted object") - private IdentityProxy uploadId = new IdentityProxy("async_job"); - + private String uploadId; + @SerializedName("uploadpercentage") @Param(description="the percentage of the entity uploaded to the specified location") private Integer uploadPercent; - + @SerializedName("status") @Param(description="the status of the extraction") private String status; - + @SerializedName("accountid") @Param(description="the account id to which the extracted object belongs") - private IdentityProxy accountId = new IdentityProxy("account"); - + private String accountId; + @SerializedName("resultstring") @Param(includeInApiDoc=false) - private String resultString; + private String resultString; @SerializedName(ApiConstants.CREATED) @Param(description="the time and date the object was created") private Date createdDate; @SerializedName(ApiConstants.STATE) @Param(description="the state of the extracted object") private String state; - + @SerializedName("storagetype") @Param(description="type of the storage") private String storageType; @SerializedName("storage") private String storage; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone ID the object was extracted from") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="zone name the object was extracted from") private String zoneName; @SerializedName("extractMode") @Param(description="the mode of extraction - upload or download") private String mode; - + @SerializedName(ApiConstants.URL) @Param(description="if mode = upload then url of the uploaded entity. if mode = download the url from which the entity can be downloaded") - private String url; - - public ExtractResponse(){ + private String url; + + public ExtractResponse(){ } - - public ExtractResponse(Long typeId, String typeName, long accountId, - String state, Long uploadId) { - this.id.setValue(typeId); + + public ExtractResponse(String typeId, String typeName, String accountId, + String state, String uploadId) { + this.id = typeId; this.name = typeName; - this.accountId.setValue(accountId); + this.accountId = accountId; this.state = state; - this.uploadId.setValue(uploadId); + this.uploadId = uploadId; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(long id) { - this.id.setValue(id); - } - - public void setIdentityTableName(String tableName) { - this.id.setTableName(tableName); + public void setId(String id) { + this.id = id; } + public String getName() { return name; } @@ -101,12 +98,12 @@ public class ExtractResponse extends BaseResponse { this.name = name; } - public Long getUploadId() { - return uploadId.getValue(); + public String getUploadId() { + return uploadId; } - public void setUploadId(Long uploadId) { - this.uploadId.setValue(uploadId); + public void setUploadId(String uploadId) { + this.uploadId = uploadId; } public Integer getUploadPercent() { @@ -125,12 +122,12 @@ public class ExtractResponse extends BaseResponse { this.status = status; } - public Long getAccountId() { - return accountId.getValue(); + public String getAccountId() { + return accountId; } - public void setAccountId(long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } public String getResultString() { @@ -173,12 +170,12 @@ public class ExtractResponse extends BaseResponse { this.storage = storage; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { diff --git a/api/src/com/cloud/api/response/FirewallResponse.java b/api/src/org/apache/cloudstack/api/response/FirewallResponse.java similarity index 93% rename from api/src/com/cloud/api/response/FirewallResponse.java rename to api/src/org/apache/cloudstack/api/response/FirewallResponse.java index bcb78e2f8f6..27992569e78 100644 --- a/api/src/com/cloud/api/response/FirewallResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FirewallResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the firewall rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the firewall rule") private String protocol; @@ -36,19 +36,19 @@ public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.END_PORT) @Param(description = "the ending port of firewall rule's port range") private String endPort; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the firewall rule") private Long publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the firewall rule") private String publicIpAddress; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.ICMP_TYPE) @Param(description= "type of the icmp message being sent") private Integer icmpType; @@ -58,8 +58,8 @@ public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setProtocol(String protocol) { diff --git a/api/src/com/cloud/api/response/FirewallRuleResponse.java b/api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java similarity index 75% rename from api/src/com/cloud/api/response/FirewallRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java index 252ad0dafe6..0009658c2a7 100644 --- a/api/src/com/cloud/api/response/FirewallRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.rules.FirewallRule; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=FirewallRule.class) @SuppressWarnings("unused") -public class FirewallRuleResponse extends BaseResponse{ +public class FirewallRuleResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the port forwarding rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PRIVATE_START_PORT) @Param(description = "the starting port of port forwarding rule's private port range") private String privateStartPort; @@ -44,35 +47,41 @@ public class FirewallRuleResponse extends BaseResponse{ private String publicEndPort; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="the VM ID for the port forwarding rule") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("virtualmachinename") @Param(description="the VM name for the port forwarding rule") private String virtualMachineName; @SerializedName("virtualmachinedisplayname") @Param(description="the VM display name for the port forwarding rule") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the port forwarding rule") - private IdentityProxy publicIpAddressId = new IdentityProxy("user_ip_address"); + private String publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the port forwarding rule") private String publicIpAddress; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) private List tags; - - public Long getId() { - return id.getValue(); + + + @Override + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getPrivateStartPort() { @@ -89,8 +98,8 @@ public class FirewallRuleResponse extends BaseResponse{ public void setPrivateEndPort(String privatePort) { this.privateEndPort = privatePort; - } - + } + public String getProtocol() { return protocol; } @@ -106,7 +115,7 @@ public class FirewallRuleResponse extends BaseResponse{ public String getPublicEndPort() { return publicEndPort; } - + public void setPublicStartPort(String publicPort) { this.publicStartPort = publicPort; } @@ -115,12 +124,12 @@ public class FirewallRuleResponse extends BaseResponse{ this.publicEndPort = publicPort; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { @@ -131,21 +140,21 @@ public class FirewallRuleResponse extends BaseResponse{ this.virtualMachineName = virtualMachineName; } - public String getVirtualMachineDisplayName() { - return virtualMachineDisplayName; - } + public String getVirtualMachineDisplayName() { + return virtualMachineDisplayName; + } - public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { - this.virtualMachineDisplayName = virtualMachineDisplayName; - } + public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { + this.virtualMachineDisplayName = virtualMachineDisplayName; + } - public String getPublicIpAddress() { - return publicIpAddress; - } + public String getPublicIpAddress() { + return publicIpAddress; + } - public void setPublicIpAddress(String publicIpAddress) { - this.publicIpAddress = publicIpAddress; - } + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } public String getState() { return state; @@ -155,14 +164,14 @@ public class FirewallRuleResponse extends BaseResponse{ this.state = state; } - public Long getPublicIpAddressId() { - return publicIpAddressId.getValue(); + public String getPublicIpAddressId() { + return publicIpAddressId; } - public void setPublicIpAddressId(Long publicIpAddressId) { - this.publicIpAddressId.setValue(publicIpAddressId); + public void setPublicIpAddressId(String publicIpAddressId) { + this.publicIpAddressId = publicIpAddressId; } - + public String getCidrList() { return cidrList; } @@ -170,7 +179,7 @@ public class FirewallRuleResponse extends BaseResponse{ public void setCidrList(String cidrs) { this.cidrList = cidrs; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/GetVMPasswordResponse.java b/api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java similarity index 58% rename from api/src/com/cloud/api/response/GetVMPasswordResponse.java rename to api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java index 41f1b6d3d53..8147df3fae1 100644 --- a/api/src/com/cloud/api/response/GetVMPasswordResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java @@ -14,30 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class GetVMPasswordResponse extends BaseResponse { - - @SerializedName("encryptedpassword") @Param(description="The encrypted password of the VM") - private String encryptedPassword; - - public GetVMPasswordResponse() {} - - public GetVMPasswordResponse(String responseName, String encryptedPassword) { - setResponseName(responseName); - setObjectName("password"); - setEncryptedPassword(encryptedPassword); - } - public String getEncryptedPassword() { - return encryptedPassword; - } + @SerializedName("encryptedpassword") @Param(description="The encrypted password of the VM") + private String encryptedPassword; + + public GetVMPasswordResponse() {} + + public GetVMPasswordResponse(String responseName, String encryptedPassword) { + setResponseName(responseName); + setObjectName("password"); + setEncryptedPassword(encryptedPassword); + } + + public String getEncryptedPassword() { + return encryptedPassword; + } + + public void setEncryptedPassword(String encryptedPassword) { + this.encryptedPassword = encryptedPassword; + } - public void setEncryptedPassword(String encryptedPassword) { - this.encryptedPassword = encryptedPassword; - } - } diff --git a/api/src/com/cloud/api/response/GuestOSCategoryResponse.java b/api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java similarity index 74% rename from api/src/com/cloud/api/response/GuestOSCategoryResponse.java rename to api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java index 9e98f3e2e3e..a14ce59f968 100644 --- a/api/src/com/cloud/api/response/GuestOSCategoryResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java @@ -14,26 +14,29 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.GuestOsCategory; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=GuestOsCategory.class) public class GuestOSCategoryResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the OS category") - private IdentityProxy id = new IdentityProxy("guest_os_category"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the OS category") - private String name; + private String name; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { diff --git a/api/src/com/cloud/api/response/GuestOSResponse.java b/api/src/org/apache/cloudstack/api/response/GuestOSResponse.java similarity index 71% rename from api/src/com/cloud/api/response/GuestOSResponse.java rename to api/src/org/apache/cloudstack/api/response/GuestOSResponse.java index 8efa8d8f4eb..0bc5dd2956e 100644 --- a/api/src/com/cloud/api/response/GuestOSResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GuestOSResponse.java @@ -14,37 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.GuestOS; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=GuestOS.class) public class GuestOSResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the OS type") - private IdentityProxy id = new IdentityProxy("guest_os"); + private String id; @SerializedName(ApiConstants.OS_CATEGORY_ID) @Param(description="the ID of the OS category") - private IdentityProxy osCategoryId = new IdentityProxy("guest_os_category"); + private String osCategoryId; @SerializedName(ApiConstants.DESCRIPTION) @Param(description="the name/description of the OS type") private String description; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getOsCategoryId() { - return osCategoryId.getValue(); + public String getOsCategoryId() { + return osCategoryId; } - public void setOsCategoryId(Long osCategoryId) { - this.osCategoryId.setValue(osCategoryId); + public void setOsCategoryId(String osCategoryId) { + this.osCategoryId = osCategoryId; } public String getDescription() { diff --git a/api/src/com/cloud/api/response/HostResponse.java b/api/src/org/apache/cloudstack/api/response/HostResponse.java old mode 100755 new mode 100644 similarity index 89% rename from api/src/com/cloud/api/response/HostResponse.java rename to api/src/org/apache/cloudstack/api/response/HostResponse.java index 52c96fb0482..35b07dda83d --- a/api/src/com/cloud/api/response/HostResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HostResponse.java @@ -14,21 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host; import com.cloud.host.Status; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Host.class) public class HostResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the host") - private IdentityProxy id = new IdentityProxy("host"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the host") private String name; @@ -43,7 +45,7 @@ public class HostResponse extends BaseResponse { private Host.Type hostType; @SerializedName("oscategoryid") @Param(description="the OS category ID of the host") - private IdentityProxy osCategoryId = new IdentityProxy("guest_os_category"); + private String osCategoryId; @SerializedName("oscategoryname") @Param(description="the OS category name of the host") private String osCategoryName; @@ -52,13 +54,13 @@ public class HostResponse extends BaseResponse { private String ipAddress; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the host") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the host") private String zoneName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the host") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the host") private String podName; @@ -118,7 +120,7 @@ public class HostResponse extends BaseResponse { private Long managementServerId; @SerializedName("clusterid") @Param(description="the cluster ID of the host") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the cluster name of the host") private String clusterName; @@ -158,16 +160,16 @@ public class HostResponse extends BaseResponse { @Override - public Long getObjectId() { - return getId(); - } - - public Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -186,8 +188,8 @@ public class HostResponse extends BaseResponse { this.hostType = hostType; } - public void setOsCategoryId(Long osCategoryId) { - this.osCategoryId.setValue(osCategoryId); + public void setOsCategoryId(String osCategoryId) { + this.osCategoryId = osCategoryId; } public void setOsCategoryName(String osCategoryName) { @@ -198,16 +200,16 @@ public class HostResponse extends BaseResponse { this.ipAddress = ipAddress; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public void setPodName(String podName) { @@ -217,7 +219,7 @@ public class HostResponse extends BaseResponse { public void setVersion(String version) { this.version = version; } - + public void setHypervisor(HypervisorType hypervisor) { this.hypervisor = hypervisor; } @@ -225,7 +227,7 @@ public class HostResponse extends BaseResponse { public void setCpuNumber(Integer cpuNumber) { this.cpuNumber = cpuNumber; } - + public void setCpuSpeed(Long cpuSpeed) { this.cpuSpeed = cpuSpeed; } @@ -286,8 +288,8 @@ public class HostResponse extends BaseResponse { this.managementServerId = managementServerId; } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); + public void setClusterId(String clusterId) { + this.clusterId = clusterId; } public void setClusterName(String clusterName) { @@ -314,6 +316,11 @@ public class HostResponse extends BaseResponse { this.events = events; } + + public String getHostTags() { + return hostTags; + } + public void setHostTags(String hostTags) { this.hostTags = hostTags; } @@ -321,11 +328,11 @@ public class HostResponse extends BaseResponse { public void setHasEnoughCapacity(Boolean hasEnoughCapacity) { this.hasEnoughCapacity = hasEnoughCapacity; } - + public void setSuitableForMigration(Boolean suitableForMigration) { this.suitableForMigration = suitableForMigration; - } + } public String getResourceState() { return resourceState; @@ -347,22 +354,6 @@ public class HostResponse extends BaseResponse { this.hypervisorVersion = hypervisorVersion; } - public void setOsCategoryId(IdentityProxy osCategoryId) { - this.osCategoryId = osCategoryId; - } - - public void setZoneId(IdentityProxy zoneId) { - this.zoneId = zoneId; - } - - public void setPodId(IdentityProxy podId) { - this.podId = podId; - } - - public void setClusterId(IdentityProxy clusterId) { - this.clusterId = clusterId; - } - public void setHaHost(Boolean haHost) { this.haHost = haHost; } diff --git a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java similarity index 85% rename from api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java rename to api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java index 4c3ea44c6c2..44e0513e32c 100644 --- a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java @@ -14,17 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.hypervisor.HypervisorCapabilities; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=HypervisorCapabilities.class) public class HypervisorCapabilitiesResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the hypervisor capabilities row") - private IdentityProxy id = new IdentityProxy("hypervisor_capabilities"); + private String id; @SerializedName(ApiConstants.HYPERVISOR_VERSION) @Param(description="the hypervisor version") private String hypervisorVersion; @@ -38,17 +41,13 @@ public class HypervisorCapabilitiesResponse extends BaseResponse { @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is supported") private boolean isSecurityGroupEnabled; - @Override - public Long getObjectId() { - return getId(); + + public String getId() { + return id; } - public Long getId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } diff --git a/api/src/com/cloud/api/response/HypervisorResponse.java b/api/src/org/apache/cloudstack/api/response/HypervisorResponse.java similarity index 89% rename from api/src/com/cloud/api/response/HypervisorResponse.java rename to api/src/org/apache/cloudstack/api/response/HypervisorResponse.java index c3ce693f647..3828539746b 100644 --- a/api/src/com/cloud/api/response/HypervisorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HypervisorResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class HypervisorResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="Hypervisor name") diff --git a/api/src/com/cloud/api/response/IPAddressResponse.java b/api/src/org/apache/cloudstack/api/response/IPAddressResponse.java similarity index 76% rename from api/src/com/cloud/api/response/IPAddressResponse.java rename to api/src/org/apache/cloudstack/api/response/IPAddressResponse.java index ea5b793b7fb..4d18aef5569 100644 --- a/api/src/com/cloud/api/response/IPAddressResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IPAddressResponse.java @@ -14,21 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.IpAddress; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=IpAddress.class) @SuppressWarnings("unused") public class IPAddressResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="public IP address id") - private IdentityProxy id = new IdentityProxy("user_ip_address"); - + private String id; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="public IP address") private String ipAddress; @@ -36,7 +39,7 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR private Date allocated; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the zone the public IP address belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the public IP address belongs to") private String zoneName; @@ -46,15 +49,15 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account the public IP address is associated with") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID the public IP address is associated with") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain the public IP address is associated with") private String domainName; @@ -63,66 +66,71 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR private Boolean forVirtualNetwork; @SerializedName(ApiConstants.VLAN_ID) @Param(description="the ID of the VLAN associated with the IP address." + - " This parameter is visible to ROOT admins only") - private IdentityProxy vlanId = new IdentityProxy("vlan"); + " This parameter is visible to ROOT admins only") + private String vlanId; @SerializedName("vlanname") @Param(description="the VLAN associated with the IP address") private String vlanName; @SerializedName("isstaticnat") @Param(description="true if this ip is for static nat, false otherwise") private Boolean staticNat; - + @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="true if this ip is system ip (was allocated as a part of deployVm or createLbRule)") private Boolean isSystem; - + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="virutal machine id the ip address is assigned to (not null only for static nat Ip)") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); - + private String virtualMachineId; + @SerializedName("virtualmachinename") @Param(description="virutal machine name the ip address is assigned to (not null only for static nat Ip)") private String virtualMachineName; - + @SerializedName("virtualmachinedisplayname") @Param(description="virutal machine display name the ip address is assigned to (not null only for static nat Ip)") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_ID) @Param(description="the ID of the Network associated with the IP address") - private IdentityProxy associatedNetworkId = new IdentityProxy("networks"); - + private String associatedNetworkId; + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_NAME) @Param(description="the name of the Network associated with the IP address") private String associatedNetworkName; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the ID of the Network where ip belongs to") - private IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName(ApiConstants.STATE) @Param(description="State of the ip address. Can be: Allocatin, Allocated and Releasing") private String state; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.PURPOSE) @Param(description="purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value") private String purpose; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the ip belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with ip address", responseObject = ResourceTagResponse.class) private List tags; -/* +/* @SerializedName(ApiConstants.JOB_ID) @Param(description="shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume") private IdentityProxy jobId = new IdentityProxy("async_job"); -*/ +*/ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } + @Override + public String getObjectId() { + return this.getId(); + } + public void setAllocated(Date allocated) { this.allocated = allocated; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { @@ -139,10 +147,10 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; @@ -152,28 +160,28 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR this.forVirtualNetwork = forVirtualNetwork; } - public void setVlanId(Long vlanId) { - this.vlanId.setValue(vlanId); + public void setVlanId(String vlanId) { + this.vlanId = vlanId; } public void setVlanName(String vlanName) { this.vlanName = vlanName; } - public void setStaticNat(Boolean staticNat) { - this.staticNat = staticNat; - } - - public void setAssociatedNetworkId(Long networkId) { - this.associatedNetworkId.setValue(networkId); + public void setStaticNat(Boolean staticNat) { + this.staticNat = staticNat; } - public void setNetworkId(Long networkId) { - this.networkId.setValue(networkId); + public void setAssociatedNetworkId(String networkId) { + this.associatedNetworkId = networkId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setNetworkId(String networkId) { + this.networkId = networkId; + } + + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVirtualMachineName(String virtualMachineName) { @@ -184,49 +192,45 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR this.virtualMachineDisplayName = virtualMachineDisplayName; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setState(String state) { this.state = state; } - @Override - public Long getObjectId() { - return getId(); - } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public void setIsSystem(Boolean isSystem) { - this.isSystem = isSystem; - } + public void setIsSystem(Boolean isSystem) { + this.isSystem = isSystem; + } public void setPurpose(String purpose) { this.purpose = purpose; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/InstanceGroupResponse.java b/api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java similarity index 80% rename from api/src/com/cloud/api/response/InstanceGroupResponse.java rename to api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java index 3b1e3585934..24706ab09fc 100644 --- a/api/src/com/cloud/api/response/InstanceGroupResponse.java +++ b/api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.vm.InstanceGroup; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") -public class InstanceGroupResponse extends BaseResponse implements ControlledEntityResponse{ +@EntityReference(value = InstanceGroup.class) +public class InstanceGroupResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the instance group") - private IdentityProxy id = new IdentityProxy("instance_group"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the instance group") private String name; @@ -36,21 +39,21 @@ public class InstanceGroupResponse extends BaseResponse implements ControlledEnt @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the instance group") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the group") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the group") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the instance group") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the instance group") private String domainName; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -67,18 +70,18 @@ public class InstanceGroupResponse extends BaseResponse implements ControlledEnt } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/IpForwardingRuleResponse.java b/api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java similarity index 76% rename from api/src/com/cloud/api/response/IpForwardingRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java index 2017a3feac8..93c86c31332 100644 --- a/api/src/com/cloud/api/response/IpForwardingRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java @@ -14,50 +14,50 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class IpForwardingRuleResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the port forwarding rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the port forwarding rule") private String protocol; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="the VM ID for the port forwarding rule") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("virtualmachinename") @Param(description="the VM name for the port forwarding rule") private String virtualMachineName; @SerializedName("virtualmachinedisplayname") @Param(description="the VM display name for the port forwarding rule") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the port forwarding rule") private Long publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the port forwarding rule") private String publicIpAddress; - + @SerializedName(ApiConstants.START_PORT) @Param(description="the start port of the rule") private Integer startPort; - + @SerializedName(ApiConstants.END_PORT) @Param(description="the end port of the rule") private Integer endPort; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the ip forwarding rule") private String state; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getProtocol() { @@ -68,12 +68,12 @@ public class IpForwardingRuleResponse extends BaseResponse { this.protocol = protocol; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { @@ -84,21 +84,21 @@ public class IpForwardingRuleResponse extends BaseResponse { this.virtualMachineName = virtualMachineName; } - public String getVirtualMachineDisplayName() { - return virtualMachineDisplayName; - } + public String getVirtualMachineDisplayName() { + return virtualMachineDisplayName; + } - public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { - this.virtualMachineDisplayName = virtualMachineDisplayName; - } + public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { + this.virtualMachineDisplayName = virtualMachineDisplayName; + } - public String getPublicIpAddress() { - return publicIpAddress; - } + public String getPublicIpAddress() { + return publicIpAddress; + } - public void setPublicIpAddress(String publicIpAddress) { - this.publicIpAddress = publicIpAddress; - } + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } public String getState() { return state; diff --git a/api/src/com/cloud/api/response/IsoVmResponse.java b/api/src/org/apache/cloudstack/api/response/IsoVmResponse.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/response/IsoVmResponse.java rename to api/src/org/apache/cloudstack/api/response/IsoVmResponse.java index 29a898a2789..a667e50c5f9 --- a/api/src/com/cloud/api/response/IsoVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IsoVmResponse.java @@ -14,15 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class IsoVmResponse extends BaseResponse { @SerializedName("id") @Param(description="the ISO ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName("name") @Param(description="the ISO name") private String name; @@ -37,13 +37,13 @@ public class IsoVmResponse extends BaseResponse { private Boolean featured; @SerializedName("ostypeid") @Param(description="the ID of the OS type for this template.") - private IdentityProxy osTypeId = new IdentityProxy("guest_os"); + private String osTypeId; @SerializedName("ostypename") @Param(description="the name of the OS type for this template.") private String osTypeName; @SerializedName("virtualmachineid") @Param(description="id of the virtual machine") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("vmname") @Param(description="name of the virtual machine") private String virtualMachineName; @@ -54,13 +54,18 @@ public class IsoVmResponse extends BaseResponse { @SerializedName("vmstate") @Param(description="state of the virtual machine") private String virtualMachineState; - - public Long getOsTypeId() { - return osTypeId.getValue(); + + @Override + public String getObjectId() { + return this.getId(); } - public void setOsTypeId(Long osTypeId) { - this.osTypeId.setValue(osTypeId); + public String getOsTypeId() { + return osTypeId; + } + + public void setOsTypeId(String osTypeId) { + this.osTypeId = osTypeId; } public String getOsTypeName() { @@ -71,12 +76,12 @@ public class IsoVmResponse extends BaseResponse { this.osTypeName = osTypeName; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -111,12 +116,12 @@ public class IsoVmResponse extends BaseResponse { this.featured = featured; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { diff --git a/api/src/com/cloud/api/response/LBStickinessPolicyResponse.java b/api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java similarity index 90% rename from api/src/com/cloud/api/response/LBStickinessPolicyResponse.java rename to api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java index 0d1212d705f..0eb4d58d50b 100644 --- a/api/src/com/cloud/api/response/LBStickinessPolicyResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java @@ -14,13 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.network.rules.StickinessPolicy; import com.cloud.serializer.Param; import com.cloud.utils.Pair; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; import java.util.List; import java.util.Map; @@ -29,8 +29,8 @@ import java.util.HashMap; public class LBStickinessPolicyResponse extends BaseResponse { @SerializedName("id") @Param(description = "the LB Stickiness policy ID") - private IdentityProxy id = new IdentityProxy("load_balancer_stickiness_policies"); - + private String id; + @SerializedName("name") @Param(description = "the name of the Stickiness policy") private String name; @@ -54,13 +54,13 @@ public class LBStickinessPolicyResponse extends BaseResponse { @SerializedName("params") @Param(description = "the params of the policy") private Map params; - + public Map getParams() { return params; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -82,7 +82,7 @@ public class LBStickinessPolicyResponse extends BaseResponse { public String getMethodName() { return methodName; } - + public String getState() { return state; } @@ -99,12 +99,12 @@ public class LBStickinessPolicyResponse extends BaseResponse { if (stickinesspolicy.isRevoke()) { this.setState("Revoked"); } - if (stickinesspolicy.getId() != 0) - setId(stickinesspolicy.getId()); + if (stickinesspolicy.getUuid() != null ) + setId(stickinesspolicy.getUuid()); - /* Get the param and values from the database and fill the response object - * The following loop is to - * 1) convert from List of Pair to Map + /* Get the param and values from the database and fill the response object + * The following loop is to + * 1) convert from List of Pair to Map * 2) combine all params with name with ":" , currently we have one param called "domain" that can appear multiple times. * */ @@ -118,7 +118,7 @@ public class LBStickinessPolicyResponse extends BaseResponse { { sb.append(":").append(tempParamList.get(key)); } - + tempParamList.put(key,sb.toString()); } diff --git a/api/src/com/cloud/api/response/LBStickinessResponse.java b/api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java similarity index 83% rename from api/src/com/cloud/api/response/LBStickinessResponse.java rename to api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java index 278fdf3bc03..7887e7c430a 100644 --- a/api/src/com/cloud/api/response/LBStickinessResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.rules.StickinessPolicy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; import java.util.List; +@EntityReference(value=StickinessPolicy.class) public class LBStickinessResponse extends BaseResponse { @SerializedName("lbruleid") @Param(description = "the LB rule ID") - private IdentityProxy lbRuleId = new IdentityProxy("firewall_rules"); + private String lbRuleId; @SerializedName("name") @Param(description = "the name of the Stickiness policy") @@ -39,10 +42,10 @@ public class LBStickinessResponse extends BaseResponse { @SerializedName("account") @Param(description = "the account of the Stickiness policy") private String accountName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the Stickiness policy") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description = "the domain of the Stickiness policy") @@ -51,17 +54,17 @@ public class LBStickinessResponse extends BaseResponse { @SerializedName("state") @Param(description = "the state of the policy") private String state; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description = "the id of the zone the Stickiness policy belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName("stickinesspolicy") @Param(description = "the list of stickinesspolicies", responseObject = LBStickinessPolicyResponse.class) private List stickinessPolicies; - public void setlbRuleId(Long lbRuleId) { - this.lbRuleId.setValue(lbRuleId); + public void setlbRuleId(String lbRuleId) { + this.lbRuleId = lbRuleId; } public void setRules(List policies) { @@ -79,11 +82,11 @@ public class LBStickinessResponse extends BaseResponse { public List getStickinessPolicies() { return stickinessPolicies; } - + public String getDescription() { return description; } - + public void setDescription(String description) { this.description = description; } @@ -96,14 +99,14 @@ public class LBStickinessResponse extends BaseResponse { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getDomainName() { return domainName; } diff --git a/api/src/com/cloud/api/response/LDAPConfigResponse.java b/api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java similarity index 95% rename from api/src/com/cloud/api/response/LDAPConfigResponse.java rename to api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java index 3e56c9566a3..e851e38e2bd 100644 --- a/api/src/com/cloud/api/response/LDAPConfigResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class LDAPConfigResponse extends BaseResponse { @@ -98,6 +99,6 @@ public class LDAPConfigResponse extends BaseResponse { public void setBindPassword(String bindPassword) { this.bindPassword = bindPassword; } - + } diff --git a/api/src/com/cloud/api/response/LDAPRemoveResponse.java b/api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java similarity index 81% rename from api/src/com/cloud/api/response/LDAPRemoveResponse.java rename to api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java index b3cdd9c4da0..0feec5bc5b5 100644 --- a/api/src/com/cloud/api/response/LDAPRemoveResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java @@ -14,15 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class LDAPRemoveResponse extends BaseResponse { - public LDAPRemoveResponse(){ - super(); - } + public LDAPRemoveResponse(){ + super(); + } } diff --git a/api/src/com/cloud/api/response/ListResponse.java b/api/src/org/apache/cloudstack/api/response/ListResponse.java similarity index 91% rename from api/src/com/cloud/api/response/ListResponse.java rename to api/src/org/apache/cloudstack/api/response/ListResponse.java index ebba4020ccb..3f28887f95e 100644 --- a/api/src/com/cloud/api/response/ListResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ListResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ResponseObject; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.ResponseObject; public class ListResponse extends BaseResponse { List responses; @@ -31,22 +32,22 @@ public class ListResponse extends BaseResponse { public void setResponses(List responses) { this.responses = responses; } - + public void setResponses(List responses, Integer count) { this.responses = responses; this.count = count; } - + public Integer getCount() { if (count != null) { return count; } - + if (responses != null) { return responses.size(); } - + return null; } } diff --git a/api/src/com/cloud/api/response/LoadBalancerResponse.java b/api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java similarity index 82% rename from api/src/com/cloud/api/response/LoadBalancerResponse.java rename to api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java index 016bccc7188..bd5efdba1e4 100644 --- a/api/src/com/cloud/api/response/LoadBalancerResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class LoadBalancerResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the load balancer rule ID") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description = "the name of the load balancer") @@ -39,7 +39,7 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description = "the public ip address id") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); + private String publicIpId; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description = "the public ip address") @@ -56,23 +56,23 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ALGORITHM) @Param(description = "the load balancer algorithm (source, roundrobin, leastconn)") private String algorithm; - + @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account of the load balancer rule") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the load balancer") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the load balancer") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the load balancer rule") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain of the load balancer rule") @@ -84,13 +84,13 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ZONE_ID) @Param(description = "the id of the zone the rule belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with load balancer", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -125,8 +125,9 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -137,26 +138,26 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti this.state = state; } - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } - + } diff --git a/api/src/com/cloud/api/response/NetworkACLResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java similarity index 92% rename from api/src/com/cloud/api/response/NetworkACLResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java index 10f312b7631..e16a1a5a434 100644 --- a/api/src/com/cloud/api/response/NetworkACLResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class NetworkACLResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the ACL") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the ACL") private String protocol; @@ -39,25 +39,25 @@ public class NetworkACLResponse extends BaseResponse { @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type for the ACL") private String trafficType; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.ICMP_TYPE) @Param(description= "type of the icmp message being sent") private Integer icmpType; @SerializedName(ApiConstants.ICMP_CODE) @Param(description = "error code for this icmp message") private Integer icmpCode; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the network ACLs", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setProtocol(String protocol) { @@ -91,7 +91,7 @@ public class NetworkACLResponse extends BaseResponse { public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/server/src/com/cloud/server/api/response/NetworkDeviceResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java similarity index 70% rename from server/src/com/cloud/server/api/response/NetworkDeviceResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java index 3cf76de1ab7..dc67b53e1ed 100644 --- a/server/src/com/cloud/server/api/response/NetworkDeviceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class NetworkDeviceResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "the ID of the network device") - private IdentityProxy id = new IdentityProxy("host"); + @SerializedName(ApiConstants.ID) + @Param(description = "the ID of the network device") + private String id; - public Long getId() { - return id.getValue(); - } + public String getId() { + return id; + } - public void setId(Long id) { - this.id.setValue(id); - } + public void setId(String id) { + this.id = id; + } } diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java similarity index 85% rename from api/src/com/cloud/api/response/NetworkOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java index 4b8abf921fa..5c1479105f8 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java @@ -14,72 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.NetworkOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=NetworkOffering.class) @SuppressWarnings("unused") -public class NetworkOfferingResponse extends BaseResponse{ +public class NetworkOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the network offering") - private final IdentityProxy id = new IdentityProxy("network_offerings"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the network offering") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the network offering.") private String displayText; - + @SerializedName(ApiConstants.TAGS) @Param(description="the tags for the network offering") private String tags; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date this network offering was created") private Date created; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") private String trafficType; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if network offering is default, false otherwise") private Boolean isDefault; - + @SerializedName(ApiConstants.SPECIFY_VLAN) @Param(description="true if network offering supports vlans, false otherwise") private Boolean specifyVlan; - + @SerializedName(ApiConstants.CONSERVE_MODE) @Param(description="true if network offering is ip conserve mode enabled") private Boolean conserveMode; @SerializedName(ApiConstants.SPECIFY_IP_RANGES) @Param(description="true if network offering supports specifying ip ranges, false otherwise") private Boolean specifyIpRanges; - + @SerializedName(ApiConstants.AVAILABILITY) @Param(description="availability of the network offering") private String availability; - + @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") private String state; - + @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="guest type of the network offering, can be Shared or Isolated") private String guestIpType; - + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering used by virtual router provider") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); - + private String serviceOfferingId; + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.FOR_VPC) @Param(description="true if network offering can be used by VPC networks only") private Boolean forVpc; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -89,7 +92,7 @@ public class NetworkOfferingResponse extends BaseResponse{ public void setDisplayText(String displayText) { this.displayText = displayText; } - + public void setTags(String tags) { this.tags = tags; } @@ -134,17 +137,14 @@ public class NetworkOfferingResponse extends BaseResponse{ this.guestIpType = type; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } - public void setServiceOfferingId(IdentityProxy serviceOfferingId) { - this.serviceOfferingId = serviceOfferingId; - } - - public void setSpecifyIpRanges(Boolean specifyIpRanges) { - this.specifyIpRanges = specifyIpRanges; - } + public void setSpecifyIpRanges(Boolean specifyIpRanges) { + this.specifyIpRanges = specifyIpRanges; + } public void setForVpc(Boolean forVpc) { this.forVpc = forVpc; diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkResponse.java similarity index 79% rename from api/src/com/cloud/api/response/NetworkResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkResponse.java index 0917cfafdef..64cc9531901 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkResponse.java @@ -14,134 +14,138 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Network; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.projects.ProjectAccount; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value = {Network.class, ProjectAccount.class}) public class NetworkResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.ID) @Param(description="the id of the network") - private IdentityProxy id = new IdentityProxy("networks"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the network") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the displaytext of the network") private String displaytext; - + @SerializedName("broadcastdomaintype") @Param(description="Broadcast domain type of the network") private String broadcastDomainType; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type of the network") private String trafficType; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the network's gateway") private String gateway; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the network's netmask") private String netmask; - + @SerializedName(ApiConstants.CIDR) @Param(description="the cidr the network") private String cidr; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the network") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the network belongs to") private String zoneName; - + @SerializedName("networkofferingid") @Param(description="network offering id the network is created from") - private IdentityProxy networkOfferingId = new IdentityProxy("network_offerings"); - + private String networkOfferingId; + @SerializedName("networkofferingname") @Param(description="name of the network offering the network is created from") private String networkOfferingName; - + @SerializedName("networkofferingdisplaytext") @Param(description="display text of the network offering the network is created from") private String networkOfferingDisplayText; - + @SerializedName("networkofferingavailability") @Param(description="availability of the network offering the network is created from") private String networkOfferingAvailability; - + @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="true if network is system, false otherwise") private Boolean isSystem; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the network") private String state; @SerializedName("related") @Param(description="related to what other network configuration") - private IdentityProxy related = new IdentityProxy("networks"); - + private String related; + @SerializedName("broadcasturi") @Param(description="broadcast uri of the network. This parameter is visible to ROOT admins only") private String broadcastUri; - + @SerializedName(ApiConstants.DNS1) @Param(description="the first DNS for the network") private String dns1; - + @SerializedName(ApiConstants.DNS2) @Param(description="the second DNS for the network") private String dns2; - + @SerializedName(ApiConstants.TYPE) @Param(description="the type of the network") private String type; - + @SerializedName(ApiConstants.VLAN) @Param(description="The vlan of the network. This parameter is visible to ROOT admins only") private String vlan; - + @SerializedName(ApiConstants.ACL_TYPE) @Param(description="acl type - access type to the network") private String aclType; - + @SerializedName(ApiConstants.SUBDOMAIN_ACCESS) @Param(description="true if users from subdomains can access the domain level network") private Boolean subdomainAccess; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the network") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the network owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the network owner") private String domain; - + @SerializedName("isdefault") @Param(description="true if network is default, false otherwise") private Boolean isDefault; - + @SerializedName("service") @Param(description="the list of services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network id") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.RESTART_REQUIRED) @Param(description="true network requires restart") private Boolean restartRequired; - + @SerializedName(ApiConstants.SPECIFY_IP_RANGES) @Param(description="true if network supports specifying ip ranges, false otherwise") private Boolean specifyIpRanges; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the network belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.CAN_USE_FOR_DEPLOY) @Param(description="list networks available for vm deployment") private Boolean canUseForDeploy; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with network", responseObject = ResourceTagResponse.class) private List tags; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -163,21 +167,21 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setNetmask(String netmask) { this.netmask = netmask; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - public void setNetworkOfferingId(Long networkOfferingId) { - this.networkOfferingId.setValue(networkOfferingId); + public void setNetworkOfferingId(String networkOfferingId) { + this.networkOfferingId = networkOfferingId; } public void setState(String state) { this.state = state; } - public void setRelated(Long related) { - this.related.setValue(related); + public void setRelated(String related) { + this.related = related; } public void setBroadcastUri(String broadcastUri) { @@ -200,8 +204,9 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setNetworkOfferingName(String networkOfferingName) { @@ -224,14 +229,14 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.isSystem = isSystem; } - public void setDomainName(String domain) { - this.domain = domain; - } + public void setDomainName(String domain) { + this.domain = domain; + } public void setNetworkOfferingAvailability(String networkOfferingAvailability) { this.networkOfferingAvailability = networkOfferingAvailability; } - + public void setServices(List services) { this.services = services; } @@ -243,10 +248,10 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -254,42 +259,42 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.projectName = projectName; } - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public void setAclType(String aclType) { - this.aclType = aclType; - } - - public void setSubdomainAccess(Boolean subdomainAccess) { - this.subdomainAccess = subdomainAccess; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - public void setCidr(String cidr) { - this.cidr = cidr; - } - - public void setRestartRequired(Boolean restartRequired) { - this.restartRequired = restartRequired; - } - - public void setSpecifyIpRanges(Boolean specifyIpRanges) { - this.specifyIpRanges = specifyIpRanges; - } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + public void setAclType(String aclType) { + this.aclType = aclType; } - + + public void setSubdomainAccess(Boolean subdomainAccess) { + this.subdomainAccess = subdomainAccess; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setCidr(String cidr) { + this.cidr = cidr; + } + + public void setRestartRequired(Boolean restartRequired) { + this.restartRequired = restartRequired; + } + + public void setSpecifyIpRanges(Boolean specifyIpRanges) { + this.specifyIpRanges = specifyIpRanges; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + public void setCanUseForDeploy(Boolean canUseForDeploy) { this.canUseForDeploy = canUseForDeploy; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/NicResponse.java b/api/src/org/apache/cloudstack/api/response/NicResponse.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/response/NicResponse.java rename to api/src/org/apache/cloudstack/api/response/NicResponse.java index 69d5c31f66c..a6ca5b8232d --- a/api/src/com/cloud/api/response/NicResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NicResponse.java @@ -14,62 +14,63 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class NicResponse extends BaseResponse { - + @SerializedName("id") @Param(description="the ID of the nic") - private final IdentityProxy id = new IdentityProxy("nics"); + private String id; @SerializedName("networkid") @Param(description="the ID of the corresponding network") - private final IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName("networkname") @Param(description="the name of the corresponding network") private String networkName ; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the nic") private String netmask; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the nic") private String gateway; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the ip address of the nic") private String ipaddress; - + @SerializedName("isolationuri") @Param(description="the isolation uri of the nic") private String isolationUri; - + @SerializedName("broadcasturi") @Param(description="the broadcast uri of the nic") private String broadcastUri; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type of the nic") private String trafficType; - + @SerializedName(ApiConstants.TYPE) @Param(description="the type of the nic") private String type; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if nic is default, false otherwise") private Boolean isDefault; @SerializedName("macaddress") @Param(description="true if nic is default, false otherwise") private String macAddress; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public void setNetworkid(Long networkid) { - this.networkId.setValue(networkid); + + public void setNetworkid(String networkid) { + this.networkId = networkid; } public void setNetworkName(String networkname) { @@ -108,15 +109,16 @@ public class NicResponse extends BaseResponse { this.isDefault = isDefault; } - public void setMacAddress(String macAddress) { - this.macAddress = macAddress; - } + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); + String oid = this.getId(); + result = prime * result + ((oid== null) ? 0 : oid.hashCode()); return result; } @@ -129,12 +131,13 @@ public class NicResponse extends BaseResponse { if (getClass() != obj.getClass()) return false; NicResponse other = (NicResponse) obj; - if (id == null) { - if (other.id != null) + String oid = this.getId(); + if (oid == null) { + if (other.getId() != null) return false; - } else if (!id.equals(other.id)) + } else if (!oid.equals(other.getId())) return false; return true; } - + } diff --git a/api/src/com/cloud/api/response/PhysicalNetworkResponse.java b/api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java similarity index 82% rename from api/src/com/cloud/api/response/PhysicalNetworkResponse.java rename to api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java index 72f10755371..78257b1bd0f 100644 --- a/api/src/com/cloud/api/response/PhysicalNetworkResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java @@ -14,39 +14,42 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetwork; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetwork.class) @SuppressWarnings("unused") -public class PhysicalNetworkResponse extends BaseResponse{ - +public class PhysicalNetworkResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) @Param(description="the uuid of the physical network") private String id; - + @SerializedName(ApiConstants.NAME) @Param(description="name of the physical network") private String name; - + @SerializedName(ApiConstants.BROADCAST_DOMAIN_RANGE) @Param(description="Broadcast domain range of the physical network") private String broadcastDomainRange; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the physical network") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.STATE) @Param(description="state of the physical network") private String state; @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the physical network") private String vlan; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the physical network owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.TAGS) @Param(description="comma separated tag") private String tags; @@ -56,41 +59,48 @@ public class PhysicalNetworkResponse extends BaseResponse{ @SerializedName(ApiConstants.NETWORK_SPEED) @Param(description="the speed of the physical network") private String networkSpeed; + + @Override + public String getObjectId() { + return this.id; + + } + public void setId(String uuid) { this.id = uuid; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setState(String state) { this.state = state; } - - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + + public void setDomainId(String domainId) { + this.domainId = domainId; } - + public void setVlan(String vlan) { this.vlan = vlan; } - + public void setTags(List tags) { if (tags == null || tags.size() == 0) { return; } - + StringBuilder buf = new StringBuilder(); for (String tag : tags) { buf.append(tag).append(","); } - + this.tags = buf.delete(buf.length()-1, buf.length()).toString(); } - + public void setBroadcastDomainRange(String broadcastDomainRange) { this.broadcastDomainRange = broadcastDomainRange; } @@ -103,16 +113,16 @@ public class PhysicalNetworkResponse extends BaseResponse{ if (isolationMethods == null || isolationMethods.size() == 0) { return; } - + StringBuilder buf = new StringBuilder(); for (String isolationMethod : isolationMethods) { buf.append(isolationMethod).append(","); } - + this.isolationMethods = buf.delete(buf.length()-1, buf.length()).toString(); } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/api/src/com/cloud/api/response/PodResponse.java b/api/src/org/apache/cloudstack/api/response/PodResponse.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/response/PodResponse.java rename to api/src/org/apache/cloudstack/api/response/PodResponse.java index df4a70f0970..71192796b25 --- a/api/src/com/cloud/api/response/PodResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PodResponse.java @@ -14,24 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.dc.Pod; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = Pod.class) public class PodResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the Pod") - private IdentityProxy id = new IdentityProxy("host_pod_ref"); + private String id; @SerializedName("name") @Param(description="the name of the Pod") private String name; @SerializedName("zoneid") @Param(description="the Zone ID of the Pod") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the Pod") private String zoneName; @@ -47,19 +51,19 @@ public class PodResponse extends BaseResponse { @SerializedName("endip") @Param(description="the ending IP for the Pod") private String endIp; - + @SerializedName("allocationstate") @Param(description="the allocation state of the Pod") - private String allocationState; + private String allocationState; @SerializedName("capacity") @Param(description="the capacity of the Pod", responseObject = CapacityResponse.class) private List capacitites; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -70,12 +74,12 @@ public class PodResponse extends BaseResponse { this.name = name; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -117,20 +121,20 @@ public class PodResponse extends BaseResponse { public void setEndIp(String endIp) { this.endIp = endIp; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - public List getCapacitites() { - return capacitites; - } + public List getCapacitites() { + return capacitites; + } - public void setCapacitites(List capacitites) { - this.capacitites = capacitites; - } + public void setCapacitites(List capacitites) { + this.capacitites = capacitites; + } } diff --git a/api/src/com/cloud/api/response/PrivateGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java similarity index 76% rename from api/src/com/cloud/api/response/PrivateGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java index e901a70933f..37c96ff6a17 100644 --- a/api/src/com/cloud/api/response/PrivateGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java @@ -14,66 +14,74 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; -import com.cloud.api.ApiConstants; +package org.apache.cloudstack.api.response; +import com.cloud.network.vpc.VpcGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VpcGateway.class) @SuppressWarnings("unused") public class PrivateGatewayResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.ID) @Param(description="the id of the private gateway") - private IdentityProxy id = new IdentityProxy("vpc_gateways"); - + private String id; + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway") private String gateway; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the private gateway's netmask") private String netmask; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the private gateway's ip address") private String address; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the private gateway") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the private gateway belongs to") private String zoneName; - + @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the private gateway") private String vlan; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the private gateaway belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - + private String vpcId; + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network id") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the private gateway") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the private gateway") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the private gateway") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the private gateway") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the private gateway") private String domainName; - + @SerializedName(ApiConstants.STATE) @Param(description="State of the gateway, can be Creating, Ready, Deleting") private String state; - - - public void setId(Long id) { - this.id.setValue(id); + + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setGateway(String gateway) { @@ -83,9 +91,9 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn public void setNetmask(String netmask) { this.netmask = netmask; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setVlan(String vlan) { @@ -95,37 +103,37 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn public void setZoneName(String zoneName) { this.zoneName = zoneName; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } public void setAddress(String address) { this.address = address; } - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/ProjectAccountResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java similarity index 81% rename from api/src/com/cloud/api/response/ProjectAccountResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java index e613466634a..134841caf31 100644 --- a/api/src/com/cloud/api/response/ProjectAccountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.projects.ProjectAccount; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=ProjectAccount.class) @SuppressWarnings("unused") -public class ProjectAccountResponse extends BaseResponse implements ControlledEntityResponse { +public class ProjectAccountResponse extends BaseResponse implements ControlledViewEntityResponse { @SerializedName(ApiConstants.PROJECT_ID) @Param(description = "project id") - private IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description = "project name") @@ -35,7 +38,7 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description = "the id of the account") - private IdentityProxy id = new IdentityProxy("account"); + private String accountId; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the name of the account") @@ -51,7 +54,7 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "id of the Domain the account belongs too") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "name of the Domain the account belongs too") @@ -61,16 +64,16 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @Param(description = "the list of users associated with account", responseObject = UserResponse.class) private List users; - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } public void setProjectName(String projectName) { this.projectName = projectName; } - public void setId(Long id) { - this.id.setValue(id); + public void setAccountId(String id) { + this.accountId = id; } public void setAccountName(String accountName) { @@ -81,8 +84,8 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn this.accountType = accountType; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { diff --git a/api/src/com/cloud/api/response/ProjectInvitationResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java similarity index 79% rename from api/src/com/cloud/api/response/ProjectInvitationResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java index abb47a7a664..0c9ce685bcc 100644 --- a/api/src/com/cloud/api/response/ProjectInvitationResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java @@ -14,53 +14,56 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.projects.ProjectInvitation; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=ProjectInvitation.class) @SuppressWarnings("unused") -public class ProjectInvitationResponse extends BaseResponse implements ControlledEntityResponse{ +public class ProjectInvitationResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the invitation") - private IdentityProxy id = new IdentityProxy("project_invitations"); - + private String id; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the id of the project") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the name of the project") private String projectName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id the project belongs to") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name where the project belongs to") private String domainName; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name of the project's owner") private String accountName; - + @SerializedName(ApiConstants.EMAIL) @Param(description="the email the invitation was sent to") private String email; - + @SerializedName(ApiConstants.STATE) @Param(description="the invitation state") private String invitationState; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } public void setProjectName(String projectName) { this.projectName = projectName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domain) { diff --git a/api/src/com/cloud/api/response/ProjectResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectResponse.java similarity index 77% rename from api/src/com/cloud/api/response/ProjectResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectResponse.java index 2735980a6e4..7ecda234814 100644 --- a/api/src/com/cloud/api/response/ProjectResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectResponse.java @@ -14,45 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; +import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.projects.Project; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Project.class) @SuppressWarnings("unused") -public class ProjectResponse extends BaseResponse{ - +public class ProjectResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) @Param(description="the id of the project") - private IdentityProxy id = new IdentityProxy("projects"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the project") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the displaytext of the project") private String displaytext; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id the project belongs to") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name where the project belongs to") private String domain; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name of the project's owner") private String ownerName; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the project") private String state; - - @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) - private List tags; - - public void setId(Long id) { - this.id.setValue(id); + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) + private List tags = new ArrayList(); + + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -63,8 +67,8 @@ public class ProjectResponse extends BaseResponse{ this.displaytext = displaytext; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomain(String domain) { @@ -78,8 +82,12 @@ public class ProjectResponse extends BaseResponse{ public void setState(String state) { this.state = state; } - + public void setTags(List tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/ProviderResponse.java b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java similarity index 76% rename from api/src/com/cloud/api/response/ProviderResponse.java rename to api/src/org/apache/cloudstack/api/response/ProviderResponse.java index d8a5eb6bd62..b83c2348390 100644 --- a/api/src/com/cloud/api/response/ProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java @@ -14,39 +14,42 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetworkServiceProvider; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetworkServiceProvider.class) @SuppressWarnings("unused") public class ProviderResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the provider name") private String name; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.DEST_PHYSICAL_NETWORK_ID) @Param(description="the destination physical network") - private IdentityProxy destinationPhysicalNetworkId = new IdentityProxy("physical_network"); - + private String destinationPhysicalNetworkId; + @SerializedName(ApiConstants.STATE) @Param(description="state of the network provider") private String state; @SerializedName(ApiConstants.ID) @Param(description="uuid of the network provider") private String id; - + @SerializedName(ApiConstants.SERVICE_LIST) @Param(description="services for this provider") private List services; - + @SerializedName(ApiConstants.CAN_ENABLE_INDIVIDUAL_SERVICE) @Param(description="true if individual services can be enabled/disabled") private Boolean canEnableIndividualServices; - + public void setName(String name) { this.name = name; } @@ -54,27 +57,27 @@ public class ProviderResponse extends BaseResponse { public String getName() { return name; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); - } - - public void setDestinationPhysicalNetworkId(long destPhysicalNetworkId) { - this.destinationPhysicalNetworkId.setValue(destPhysicalNetworkId); + public String getphysicalNetworkId() { + return physicalNetworkId; } - public long getDestinationPhysicalNetworkId() { - return destinationPhysicalNetworkId.getValue(); + public void setDestinationPhysicalNetworkId(String destPhysicalNetworkId) { + this.destinationPhysicalNetworkId = destPhysicalNetworkId; + } + + public String getDestinationPhysicalNetworkId() { + return destinationPhysicalNetworkId; } public void setState(String state) { this.state = state; } - + public String getState() { return this.state; } @@ -82,24 +85,24 @@ public class ProviderResponse extends BaseResponse { public void setId(String uuid) { this.id = uuid; } - + public String getId() { return this.id; } - + public void setServices(List services) { this.services = services; } - + public List getServices() { return services; } - + public Boolean getCanEnableIndividualServices() { return canEnableIndividualServices; } public void setCanEnableIndividualServices(Boolean canEnableIndividualServices) { this.canEnableIndividualServices = canEnableIndividualServices; - } + } } diff --git a/api/src/com/cloud/api/response/RegisterResponse.java b/api/src/org/apache/cloudstack/api/response/RegisterResponse.java similarity index 94% rename from api/src/com/cloud/api/response/RegisterResponse.java rename to api/src/org/apache/cloudstack/api/response/RegisterResponse.java index 6f9f3404b31..eee924940fb 100644 --- a/api/src/com/cloud/api/response/RegisterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RegisterResponse.java @@ -14,10 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class RegisterResponse extends BaseResponse { @SerializedName("apikey") @Param(description="the api key of the registered user") diff --git a/api/src/com/cloud/api/response/RemoteAccessVpnResponse.java b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java similarity index 68% rename from api/src/com/cloud/api/response/RemoteAccessVpnResponse.java rename to api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java index c6fe4d43fb6..3fd7d7a668b 100644 --- a/api/src/com/cloud/api/response/RemoteAccessVpnResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java @@ -14,22 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.RemoteAccessVpn; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=RemoteAccessVpn.class) @SuppressWarnings("unused") public class RemoteAccessVpnResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description="the public ip address of the vpn server") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); - + private String publicIpId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public ip address of the vpn server") private String publicIp; - + @SerializedName("iprange") @Param(description="the range of ips to allocate to the clients") private String ipRange; @@ -38,62 +41,63 @@ public class RemoteAccessVpnResponse extends BaseResponse implements ControlledE @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account of the remote access vpn") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the account of the remote access vpn") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the account of the remote access vpn") - private String domainName; - + private String domainName; + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; - public void setPublicIp(String publicIp) { - this.publicIp = publicIp; - } + public void setPublicIp(String publicIp) { + this.publicIp = publicIp; + } - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } - public void setPresharedKey(String presharedKey) { - this.presharedKey = presharedKey; - } + public void setPresharedKey(String presharedKey) { + this.presharedKey = presharedKey; + } - public void setAccountName(String accountName) { - this.accountName = accountName; - } + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } - public void setDomainName(String name) { - this.domainName = name; - } + public void setDomainName(String name) { + this.domainName = name; + } public void setState(String state) { this.state = state; } - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + } diff --git a/api/src/com/cloud/api/response/ResourceCountResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java similarity index 85% rename from api/src/com/cloud/api/response/ResourceCountResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java index 73fe44fe92d..7a291945f76 100644 --- a/api/src/com/cloud/api/response/ResourceCountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class ResourceCountResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account for which resource count's are updated") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id for which resource count's are updated") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name for which resource count's are updated") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID for which resource count's are updated") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name for which resource count's are updated") private String domainName; @@ -51,8 +51,8 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -67,15 +67,15 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt public void setResourceCount(Long resourceCount) { this.resourceCount = resourceCount; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + } diff --git a/api/src/com/cloud/api/response/ResourceLimitResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java similarity index 83% rename from api/src/com/cloud/api/response/ResourceLimitResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java index f41feca554a..c01e12f2e23 100644 --- a/api/src/com/cloud/api/response/ResourceLimitResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.configuration.ResourceLimit; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = ResourceLimit.class) @SuppressWarnings("unused") public class ResourceLimitResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account of the resource limit") private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the resource limit") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the resource limit") private String domainName; @@ -37,33 +40,33 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt @SerializedName("max") @Param(description="the maximum number of the resource. A -1 means the resource currently has no limit.") private Long max; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the resource limit") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the resource limit") private String projectName; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - + @Override public void setProjectName(String projectName) { this.projectName = projectName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + public void setResourceType(String resourceType) { this.resourceType = resourceType; } @@ -73,7 +76,7 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } } diff --git a/api/src/com/cloud/api/response/ResourceTagResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java similarity index 82% rename from api/src/com/cloud/api/response/ResourceTagResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java index 13566a73732..30bcbfd38a2 100644 --- a/api/src/com/cloud/api/response/ResourceTagResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java @@ -14,45 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") -public class ResourceTagResponse extends BaseResponse implements ControlledEntityResponse{ +public class ResourceTagResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.KEY) @Param(description="tag key name") private String key; - + @SerializedName(ApiConstants.VALUE) @Param(description="tag value") private String value; - + @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type") private String resourceType; - + @SerializedName(ApiConstants.RESOURCE_ID) @Param(description="id of the resource") - private String id; - + private String resourceId; + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the tag") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id the tag belongs to") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name where tag belongs to") private String projectName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the tag") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the tag") private String domainName; - + @SerializedName(ApiConstants.CUSTOMER) @Param(description="customer associated with the tag") private String customer; @@ -68,32 +68,35 @@ public class ResourceTagResponse extends BaseResponse implements ControlledEntit this.resourceType = resourceType; } - public void setId(String id) { - this.id = id; + public void setResourceId(String id) { + this.resourceId = id; } - + + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } - + + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } - + @Override public void setProjectName(String projectName) { this.projectName = projectName; - } - + } + public void setCustomer(String customer) { this.customer = customer; } diff --git a/api/src/com/cloud/api/response/S3Response.java b/api/src/org/apache/cloudstack/api/response/S3Response.java similarity index 95% rename from api/src/com/cloud/api/response/S3Response.java rename to api/src/org/apache/cloudstack/api/response/S3Response.java index 1efbe23b05e..4dab2175a3a 100644 --- a/api/src/com/cloud/api/response/S3Response.java +++ b/api/src/org/apache/cloudstack/api/response/S3Response.java @@ -16,19 +16,19 @@ * specific language governing permissions and limitations * under the License. */ -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; -import static com.cloud.api.ApiConstants.*; +import static org.apache.cloudstack.api.ApiConstants.*; public class S3Response extends BaseResponse { @SerializedName(ID) @Param(description = "The ID of the S3 configuration") - private IdentityProxy id = new IdentityProxy("s3"); + private String id; @SerializedName(S3_ACCESS_KEY) @Param(description = "The S3 access key") @@ -133,12 +133,12 @@ public class S3Response extends BaseResponse { } @Override - public Long getObjectId() { - return this.id.getValue(); + public String getObjectId() { + return this.id; } - public void setObjectId(Long id) { - this.id.setValue(id); + public void setObjectId(String id) { + this.id = id; } public String getAccessKey() { diff --git a/api/src/com/cloud/api/response/SSHKeyPairResponse.java b/api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java similarity index 63% rename from api/src/com/cloud/api/response/SSHKeyPairResponse.java rename to api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java index c955335f633..606636382a1 100644 --- a/api/src/com/cloud/api/response/SSHKeyPairResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java @@ -14,56 +14,58 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SSHKeyPairResponse extends BaseResponse { - + @SerializedName(ApiConstants.NAME) @Param(description="Name of the keypair") private String name; @SerializedName("fingerprint") @Param(description="Fingerprint of the public key") private String fingerprint; - + + @SerializedName("privatekey") @Param(description="Private key") private String privateKey; public SSHKeyPairResponse() {} - + public SSHKeyPairResponse(String name, String fingerprint) { - this(name, fingerprint, null); + this(name, fingerprint, null); } - + public SSHKeyPairResponse(String name, String fingerprint, String privateKey) { - this.name = name; - this.fingerprint = fingerprint; - this.privateKey = privateKey; + this.name = name; + this.fingerprint = fingerprint; + this.privateKey = privateKey; } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getFingerprint() { - return fingerprint; - } + public void setName(String name) { + this.name = name; + } - public void setFingerprint(String fingerprint) { - this.fingerprint = fingerprint; - } + public String getFingerprint() { + return fingerprint; + } - public String getPrivateKey() { - return privateKey; - } + public void setFingerprint(String fingerprint) { + this.fingerprint = fingerprint; + } + + public String getPrivateKey() { + return privateKey; + } + + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } - } diff --git a/api/src/com/cloud/api/response/SecurityGroupResponse.java b/api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java similarity index 68% rename from api/src/com/cloud/api/response/SecurityGroupResponse.java rename to api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java index 5c6deedfb34..f3b9beb8d3e 100644 --- a/api/src/com/cloud/api/response/SecurityGroupResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java @@ -14,19 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.security.SecurityGroup; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") -public class SecurityGroupResponse extends BaseResponse implements ControlledEntityResponse{ +@EntityReference(value = SecurityGroup.class) +public class SecurityGroupResponse extends BaseResponse implements ControlledViewEntityResponse{ + @SerializedName(ApiConstants.ID) @Param(description="the ID of the security group") - private IdentityProxy id = new IdentityProxy("security_group"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the security group") private String name; @@ -36,36 +41,52 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the security group") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the group") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the group") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the security group") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the security group") private String domainName; @SerializedName("ingressrule") @Param(description="the list of ingress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class) - private List ingressRules; + private Set ingressRules; @SerializedName("egressrule") @Param(description="the list of egress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class) - private List egressRules; - + private Set egressRules; + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) - private List tags; - - public void setId(Long id) { - this.id.setValue(id); + private Set tags; + + public SecurityGroupResponse(){ + this.ingressRules = new HashSet(); + this.egressRules = new HashSet(); + this.tags = new HashSet(); } - - public Long getId() { - return id.getValue(); + + + + @Override + public String getObjectId() { + return this.getId(); } + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { this.name = name; } @@ -78,25 +99,29 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { this.domainName = domainName; } - public void setSecurityGroupIngressRules(List securityGroupRules) { + public void setSecurityGroupIngressRules(Set securityGroupRules) { this.ingressRules = securityGroupRules; } - public void setSecurityGroupEgressRules(List securityGroupRules) { + public void addSecurityGroupIngressRule(SecurityGroupRuleResponse rule){ + this.ingressRules.add(rule); + } + + public void setSecurityGroupEgressRules(Set securityGroupRules) { this.egressRules = securityGroupRules; } - - @Override - public Long getObjectId() { - return getId(); + + public void addSecurityGroupEgressRule(SecurityGroupRuleResponse rule){ + this.egressRules.add(rule); } @Override @@ -123,18 +148,22 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt return false; return true; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setTags(List tags) { + + public void setTags(Set tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/SecurityGroupRuleResponse.java b/api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java similarity index 73% rename from api/src/com/cloud/api/response/SecurityGroupRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java index f55b810ac33..19aaa4594b9 100644 --- a/api/src/com/cloud/api/response/SecurityGroupRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java @@ -14,16 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.security.SecurityGroupRules; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = SecurityGroupRules.class) public class SecurityGroupRuleResponse extends BaseResponse { @SerializedName("ruleid") @Param(description="the id of the security group rule") - private IdentityProxy ruleId = new IdentityProxy("security_group_rule"); + private String ruleId; @SerializedName("protocol") @Param(description="the protocol of the security group rule") private String protocol; @@ -49,12 +52,12 @@ public class SecurityGroupRuleResponse extends BaseResponse { @SerializedName(ApiConstants.CIDR) @Param(description="the CIDR notation for the base IP address of the security group rule") private String cidr; - public Long getRuleId() { - return ruleId.getValue(); + public String getRuleId() { + return ruleId; } - public void setRuleId(Long ruleId) { - this.ruleId.setValue(ruleId); + public void setRuleId(String ruleId) { + this.ruleId = ruleId; } public String getProtocol() { @@ -120,4 +123,31 @@ public class SecurityGroupRuleResponse extends BaseResponse { public void setCidr(String cidr) { this.cidr = cidr; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + String oid = this.getRuleId(); + result = prime * result + ((oid== null) ? 0 : oid.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SecurityGroupRuleResponse other = (SecurityGroupRuleResponse) obj; + String oid = this.getRuleId(); + if (oid == null) { + if (other.getRuleId() != null) + return false; + } else if (!oid.equals(other.getRuleId())) + return false; + return true; + } } diff --git a/api/src/com/cloud/api/response/ServiceOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java similarity index 82% rename from api/src/com/cloud/api/response/ServiceOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index fe0efc07df9..7a10f7f7673 100644 --- a/api/src/com/cloud/api/response/ServiceOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.ServiceOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = ServiceOffering.class) public class ServiceOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the service offering") - private IdentityProxy id = new IdentityProxy("disk_offering"); + private String id; @SerializedName("name") @Param(description="the name of the service offering") private String name; @@ -50,21 +53,21 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName("offerha") @Param(description="the ha support in the service offering") private Boolean offerHa; - + @SerializedName("limitcpuuse") @Param(description="restrict the CPU usage to committed service offering") private Boolean limitCpuUse; - + @SerializedName("tags") @Param(description="the tags for the service offering") private String tags; - @SerializedName("domainid") @Param(description="the domain id of the service offering") - private IdentityProxy domainId = new IdentityProxy("domain"); - + @SerializedName("domainid") @Param(description="the domain id of the service offering") + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="Domain name for the offering") private String domain; - + @SerializedName(ApiConstants.HOST_TAGS) @Param(description="the host tag for the service offering") - private String hostTag; + private String hostTag; @SerializedName(ApiConstants.IS_SYSTEM_OFFERING) @Param(description="is this a system vm offering") private Boolean isSystem; @@ -74,17 +77,17 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName(ApiConstants.SYSTEM_VM_TYPE) @Param(description="is this a the systemvm type for system vm offering") private String vm_type; - + @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -94,11 +97,11 @@ public class ServiceOfferingResponse extends BaseResponse { public void setName(String name) { this.name = name; } - + public Boolean getIsSystem() { return isSystem; } - + public void setIsSystemOffering(Boolean isSystem) { this.isSystem = isSystem; } @@ -107,16 +110,16 @@ public class ServiceOfferingResponse extends BaseResponse { public Boolean getDefaultUse() { return defaultUse; } - + public void setDefaultUse(Boolean defaultUse) { this.defaultUse = defaultUse; } - + public String getSystemVmType() { return vm_type; } - + public void setSystemVmType(String vmtype) { this.vm_type = vmtype; } @@ -179,13 +182,13 @@ public class ServiceOfferingResponse extends BaseResponse { } public Boolean getLimitCpuUse() { - return limitCpuUse; + return limitCpuUse; } - + public void setLimitCpuUse(Boolean limitCpuUse) { - this.limitCpuUse = limitCpuUse; + this.limitCpuUse = limitCpuUse; } - + public String getTags() { return tags; } @@ -194,29 +197,29 @@ public class ServiceOfferingResponse extends BaseResponse { this.tags = tags; } - public Long getDomainId() { - return domainId.getValue(); - } + public String getDomainId() { + return domainId; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + public void setDomainId(String domainId) { + this.domainId = domainId; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } - - public String getHostTag() { - return hostTag; - } + public void setDomain(String domain) { + this.domain = domain; + } - public void setHostTag(String hostTag) { - this.hostTag = hostTag; - } + public String getHostTag() { + return hostTag; + } + + public void setHostTag(String hostTag) { + this.hostTag = hostTag; + } public void setNetworkRate(Integer networkRate) { this.networkRate = networkRate; diff --git a/api/src/com/cloud/api/response/ServiceResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java similarity index 92% rename from api/src/com/cloud/api/response/ServiceResponse.java rename to api/src/org/apache/cloudstack/api/response/ServiceResponse.java index 3c73e927053..11f7d710383 100644 --- a/api/src/com/cloud/api/response/ServiceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class ServiceResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the service name") private String name; - + @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name") private List providers; - + @SerializedName("capability") @Param(description="the list of capabilities", responseObject = CapabilityResponse.class) private List capabilities; @@ -45,4 +46,4 @@ public class ServiceResponse extends BaseResponse { public void setProviders(List providers) { this.providers = providers; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java similarity index 86% rename from api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java index 7c706f3452a..d164580bdea 100644 --- a/api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteCustomerGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteCustomerGateway.class) @SuppressWarnings("unused") public class Site2SiteCustomerGatewayResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_customer_gateway"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="name of the customer gateway") private String name; @@ -45,41 +48,41 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co @SerializedName(ApiConstants.IKE_POLICY) @Param(description="IKE policy of customer gateway") private String ikePolicy; - + @SerializedName(ApiConstants.ESP_POLICY) @Param(description="IPsec policy of customer gateway") private String espPolicy; - + @SerializedName(ApiConstants.IKE_LIFETIME) @Param(description="Lifetime of IKE SA of customer gateway") private Long ikeLifetime; - + @SerializedName(ApiConstants.ESP_LIFETIME) @Param(description="Lifetime of ESP SA of customer gateway") private Long espLifetime; - + @SerializedName(ApiConstants.DPD) @Param(description="if DPD is enabled for customer gateway") private Boolean dpd; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - + public void setId(String id) { + this.id = id; + } + public void setName(String name) { this.name = name; } @@ -98,40 +101,40 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co public void setIpsecPsk(String ipsecPsk) { this.ipsecPsk = ipsecPsk; - } - + } + public void setIkePolicy(String ikePolicy) { this.ikePolicy = ikePolicy; - } - + } + public void setEspPolicy(String espPolicy) { this.espPolicy = espPolicy; - } - + } + public void setIkeLifetime(Long ikeLifetime) { this.ikeLifetime = ikeLifetime; - } - + } + public void setEspLifetime(Long espLifetime) { this.espLifetime = espLifetime; - } - + } + public void setDpd(Boolean dpd) { this.dpd= dpd; - } - + } + public void setRemoved(Date removed) { this.removed = removed; - } - + } + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -140,8 +143,8 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java similarity index 79% rename from api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java index 1af50178172..c398116a9f8 100644 --- a/api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java @@ -14,29 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteVpnConnection; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteVpnConnection.class) @SuppressWarnings("unused") public class Site2SiteVpnConnectionResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_vpn_connection"); + private String id; @SerializedName(ApiConstants.S2S_VPN_GATEWAY_ID) @Param(description="the vpn gateway ID") - private IdentityProxy vpnGatewayId= new IdentityProxy("s2s_vpn_gateway"); - + private String vpnGatewayId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address") //from VpnGateway private String ip; @SerializedName(ApiConstants.S2S_CUSTOMER_GATEWAY_ID) @Param(description="the customer gateway ID") - private IdentityProxy customerGatewayId = new IdentityProxy("s2s_customer_gateway"); - + private String customerGatewayId; + @SerializedName(ApiConstants.GATEWAY) @Param(description="public ip address id of the customer gateway") //from CustomerGateway private String gatewayIp; @@ -54,85 +57,85 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont @SerializedName(ApiConstants.IKE_LIFETIME) @Param(description="Lifetime of IKE SA of customer gateway") //from CustomerGateway private Long ikeLifetime; - + @SerializedName(ApiConstants.ESP_LIFETIME) @Param(description="Lifetime of ESP SA of customer gateway") //from CustomerGateway private Long espLifetime; - + @SerializedName(ApiConstants.DPD) @Param(description="if DPD is enabled for customer gateway") //from CustomerGateway private Boolean dpd; - + @SerializedName(ApiConstants.STATE) @Param(description="State of vpn connection") private String state; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date and time the host was created") private Date created; @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - - public void setVpnGatewayId(Long vpnGatewayId) { - this.vpnGatewayId.setValue(vpnGatewayId); + public void setId(String id) { + this.id = id; + } + + public void setVpnGatewayId(String vpnGatewayId) { + this.vpnGatewayId = vpnGatewayId; } public void setIp(String ip) { - this.ip = ip; - } - - public void setCustomerGatewayId(Long customerGatewayId) { - this.customerGatewayId.setValue(customerGatewayId); + this.ip = ip; } - + + public void setCustomerGatewayId(String customerGatewayId) { + this.customerGatewayId = customerGatewayId; + } + public void setGatewayIp(String gatewayIp) { - this.gatewayIp = gatewayIp; + this.gatewayIp = gatewayIp; } - + public void setGuestCidrList(String guestCidrList) { - this.guestCidrList = guestCidrList; + this.guestCidrList = guestCidrList; } - + public void setIpsecPsk(String ipsecPsk) { - this.ipsecPsk = ipsecPsk; + this.ipsecPsk = ipsecPsk; } - + public void setIkePolicy(String ikePolicy) { - this.ikePolicy = ikePolicy; + this.ikePolicy = ikePolicy; } - + public void setEspPolicy(String espPolicy) { - this.espPolicy = espPolicy; + this.espPolicy = espPolicy; } - + public void setIkeLifetime(Long ikeLifetime) { this.ikeLifetime = ikeLifetime; - } - + } + public void setEspLifetime(Long espLifetime) { this.espLifetime = espLifetime; - } - + } + public void setDpd(Boolean dpd) { this.dpd= dpd; - } - + } + public void setState(String state) { this.state = state; } @@ -143,7 +146,7 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont public void setRemoved(Date removed) { this.removed = removed; - } + } @Override public void setAccountName(String accountName) { @@ -151,8 +154,8 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -161,8 +164,8 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java similarity index 75% rename from api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java index b1eaffdced6..8cb06fc8a56 100644 --- a/api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java @@ -14,68 +14,71 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteVpnGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteVpnGateway.class) @SuppressWarnings("unused") public class Site2SiteVpnGatewayResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_vpn_gateway"); + private String id; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address") private String ip; @SerializedName(ApiConstants.VPC_ID) @Param(description="the vpc id of this gateway") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - - public void setIp(String ip) { - this.ip = ip; - } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); - } - + public void setId(String id) { + this.id = id; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + public void setRemoved(Date removed) { this.removed = removed; - } - + } + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -84,8 +87,8 @@ public class Site2SiteVpnGatewayResponse extends BaseResponse implements Control } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/SnapshotPolicyResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java similarity index 81% rename from api/src/com/cloud/api/response/SnapshotPolicyResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java index ac1b6cbe3ae..6bf77a04298 100644 --- a/api/src/com/cloud/api/response/SnapshotPolicyResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; +import com.cloud.storage.snapshot.SnapshotPolicy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=SnapshotPolicy.class) public class SnapshotPolicyResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the snapshot policy") - private IdentityProxy id = new IdentityProxy("snapshot_policy"); + private String id; @SerializedName("volumeid") @Param(description="the ID of the disk volume") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName("schedule") @Param(description="time the snapshot is scheduled to be taken.") private String schedule; @@ -39,20 +42,20 @@ public class SnapshotPolicyResponse extends BaseResponse { @SerializedName("timezone") @Param(description="the time zone of the snapshot policy") private String timezone; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getVolumeId() { - return volumeId.getValue(); + public String getVolumeId() { + return volumeId; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } public String getSchedule() { diff --git a/api/src/com/cloud/api/response/SnapshotResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java similarity index 81% rename from api/src/com/cloud/api/response/SnapshotResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotResponse.java index 71b1b14b8b5..8ea0d7fb87f 100644 --- a/api/src/com/cloud/api/response/SnapshotResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java @@ -14,22 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.Snapshot; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Snapshot.class) @SuppressWarnings("unused") public class SnapshotResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "ID of the snapshot") - private IdentityProxy id = new IdentityProxy("snapshots"); + private String id; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the snapshot") @@ -37,15 +39,15 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the snapshot's account") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain name of the snapshot's account") private String domainName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the snapshot") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the snapshot") private String projectName; @@ -55,7 +57,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.VOLUME_ID) @Param(description = "ID of the disk volume") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName(ApiConstants.VOLUME_NAME) @Param(description = "name of the disk volume") @@ -66,7 +68,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe private String volumeType; @SerializedName(ApiConstants.CREATED) - @Param(description = " the date the snapshot was created") + @Param(description = " the date the snapshot was created") private Date created; @SerializedName(ApiConstants.NAME) @@ -80,21 +82,22 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.STATE) @Param(description = "the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage") private Snapshot.Status state; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with snapshot", responseObject = ResourceTagResponse.class) private List tags; + @Override - public Long getObjectId() { - return getId(); - } - - private Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + private String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getAccountName() { @@ -105,12 +108,13 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe this.accountName = accountName; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -121,8 +125,8 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe this.snapshotType = snapshotType; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } public void setVolumeName(String volumeName) { @@ -150,15 +154,15 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/SnapshotScheduleResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java similarity index 67% rename from api/src/com/cloud/api/response/SnapshotScheduleResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java index 37f82b83290..19bb189467b 100644 --- a/api/src/com/cloud/api/response/SnapshotScheduleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java @@ -14,49 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SnapshotScheduleResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the snapshot schedule") - private IdentityProxy id = new IdentityProxy("snapshot_schedule"); + private String id; @SerializedName("volumeid") @Param(description="the volume ID the snapshot schedule applied for") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName("snapshotpolicyid") @Param(description="the snapshot policy ID used by the snapshot schedule") - private IdentityProxy snapshotPolicyId = new IdentityProxy("snapshot_policy"); + private String snapshotPolicyId; @SerializedName("scheduled") @Param(description="time the snapshot is scheduled to be taken") private Date scheduled; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getVolumeId() { - return volumeId.getValue(); + public String getVolumeId() { + return volumeId; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } - public Long getSnapshotPolicyId() { - return snapshotPolicyId.getValue(); + public String getSnapshotPolicyId() { + return snapshotPolicyId; } - public void setSnapshotPolicyId(Long snapshotPolicyId) { - this.snapshotPolicyId.setValue(snapshotPolicyId); + public void setSnapshotPolicyId(String snapshotPolicyId) { + this.snapshotPolicyId = snapshotPolicyId; } public Date getScheduled() { diff --git a/api/src/com/cloud/api/response/StaticRouteResponse.java b/api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java similarity index 77% rename from api/src/com/cloud/api/response/StaticRouteResponse.java rename to api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java index 0b950ecffe0..e7383e3787d 100644 --- a/api/src/com/cloud/api/response/StaticRouteResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java @@ -14,99 +14,108 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.StaticRoute; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StaticRoute.class) @SuppressWarnings("unused") public class StaticRouteResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of static route") - private IdentityProxy id = new IdentityProxy("static_routes"); - + private String id; + @SerializedName(ApiConstants.STATE) @Param(description="the state of the static route") private String state; @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the static route belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - + private String vpcId; + @SerializedName(ApiConstants.GATEWAY_ID) @Param(description="VPC gateway the route is created for") - private IdentityProxy gatewayId = new IdentityProxy("vpc_gateways"); - + private String gatewayId; + @SerializedName(ApiConstants.CIDR) @Param(description="static route CIDR") private String cidr; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the static route") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the static route") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the static route") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the static route") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the static route") private String domainName; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with static route", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setState(String state) { this.state = state; } - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - public void setGatewayId(Long gatewayId) { - this.gatewayId.setValue(gatewayId); + public void setGatewayId(String gatewayId) { + this.gatewayId = gatewayId; } public void setCidr(String cidr) { this.cidr = cidr; } - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/StatusResponse.java b/api/src/org/apache/cloudstack/api/response/StatusResponse.java similarity index 92% rename from api/src/com/cloud/api/response/StatusResponse.java rename to api/src/org/apache/cloudstack/api/response/StatusResponse.java index 336cad7b76a..ffe7c7c0c1e 100644 --- a/api/src/com/cloud/api/response/StatusResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StatusResponse.java @@ -14,14 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class StatusResponse extends BaseResponse { @SerializedName("status") private Boolean status; - + public Boolean getStatus() { return status; } diff --git a/api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java b/api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java old mode 100755 new mode 100644 similarity index 86% rename from api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java rename to api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java index 68a939778cf..328180f5260 --- a/api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.dc.StorageNetworkIpRange; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StorageNetworkIpRange.class) public class StorageNetworkIpRangeResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the uuid of storage network IP range.") private String uuid; - + @SerializedName(ApiConstants.VLAN) @Param(description="the ID or VID of the VLAN.") private Integer vlan; - + @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod uuid for the storage network IP range") private String podUuid; @@ -36,35 +39,35 @@ public class StorageNetworkIpRangeResponse extends BaseResponse { @SerializedName(ApiConstants.END_IP) @Param(description="the end ip of the storage network IP range") private String endIp; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the storage network IP range") private String gateway; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the network uuid of storage network IP range") private String networkUuid; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone uuid of the storage network IP range") private String zoneUuid; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the storage network IP range") private String netmask; - - public void setUuid(String uuid) { - this.uuid = uuid; - } - + + public void setUuid(String uuid) { + this.uuid = uuid; + } + public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } - + public void setVlan(Integer vlan) { this.vlan = vlan; } - + public void setPodUuid(String podUuid) { this.podUuid = podUuid; } - + public void setStartIp(String startIp) { this.startIp = startIp; } @@ -76,12 +79,12 @@ public class StorageNetworkIpRangeResponse extends BaseResponse { public void setNetworkUuid(String networkUuid) { this.networkUuid = networkUuid; } - + public void setNetmask(String netmask) { - this.netmask = netmask; + this.netmask = netmask; } - + public void setGateway(String gateway) { - this.gateway = gateway; + this.gateway = gateway; } } diff --git a/api/src/com/cloud/api/response/StoragePoolResponse.java b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/response/StoragePoolResponse.java rename to api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java index 3b6a5792127..7afce716fda --- a/api/src/com/cloud/api/response/StoragePoolResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java @@ -14,28 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.StoragePool; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.StoragePoolStatus; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StoragePool.class) public class StoragePoolResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the storage pool") - private IdentityProxy id = new IdentityProxy("storage_pool"); + private String id; @SerializedName("zoneid") @Param(description="the Zone ID of the storage pool") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the storage pool") private String zoneName; @SerializedName("podid") @Param(description="the Pod ID of the storage pool") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the storage pool") private String podName; @@ -56,7 +59,7 @@ public class StoragePoolResponse extends BaseResponse { private String type; @SerializedName("clusterid") @Param(description="the ID of the cluster for the storage pool") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the name of the cluster for the storage pool") private String clusterName; @@ -66,7 +69,7 @@ public class StoragePoolResponse extends BaseResponse { @SerializedName("disksizeallocated") @Param(description="the host's currently allocated disk size") private Long diskSizeAllocated; - + @SerializedName("disksizeused") @Param(description="the host's currently used disk size") private Long diskSizeUsed; @@ -76,25 +79,27 @@ public class StoragePoolResponse extends BaseResponse { @SerializedName(ApiConstants.STATE) @Param(description="the state of the storage pool") private StoragePoolStatus state; + + @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -105,12 +110,12 @@ public class StoragePoolResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -161,12 +166,12 @@ public class StoragePoolResponse extends BaseResponse { this.type = type; } - public Long getClusterId() { - return clusterId.getValue(); + public String getClusterId() { + return clusterId; } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); + public void setClusterId(String clusterId) { + this.clusterId = clusterId; } public String getClusterName() { @@ -194,14 +199,14 @@ public class StoragePoolResponse extends BaseResponse { } public Long getDiskSizeUsed() { - return diskSizeUsed; - } + return diskSizeUsed; + } - public void setDiskSizeUsed(Long diskSizeUsed) { - this.diskSizeUsed = diskSizeUsed; - } + public void setDiskSizeUsed(Long diskSizeUsed) { + this.diskSizeUsed = diskSizeUsed; + } - public String getTags() { + public String getTags() { return tags; } @@ -216,5 +221,5 @@ public class StoragePoolResponse extends BaseResponse { public void setState(StoragePoolStatus state) { this.state = state; } - + } diff --git a/api/src/com/cloud/api/response/SuccessResponse.java b/api/src/org/apache/cloudstack/api/response/SuccessResponse.java similarity index 71% rename from api/src/com/cloud/api/response/SuccessResponse.java rename to api/src/org/apache/cloudstack/api/response/SuccessResponse.java index b390e0bd79d..47c65b6a068 100644 --- a/api/src/com/cloud/api/response/SuccessResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SuccessResponse.java @@ -14,37 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SuccessResponse extends BaseResponse { - @SerializedName("success") @Param(description="true if operation is executed successfully") - private Boolean success = true; - + @SerializedName("success") @Param(description="true if operation is executed successfully") + private Boolean success = true; + @SerializedName("displaytext") @Param(description="any text associated with the success or failure") private String displayText; - - public Boolean getSuccess() { - return success; - } - public void setSuccess(Boolean success) { - this.success = success; - } + public Boolean getSuccess() { + return success; + } - public String getDisplayText() { - return displayText; - } + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getDisplayText() { + return displayText; + } public void setDisplayText(String displayText) { this.displayText = displayText; } - + public SuccessResponse() {} - + public SuccessResponse(String responseName) { - super.setResponseName(responseName); + super.setResponseName(responseName); } } diff --git a/api/src/com/cloud/api/response/SwiftResponse.java b/api/src/org/apache/cloudstack/api/response/SwiftResponse.java old mode 100755 new mode 100644 similarity index 87% rename from api/src/com/cloud/api/response/SwiftResponse.java rename to api/src/org/apache/cloudstack/api/response/SwiftResponse.java index 81171defdf0..83fceb348f7 --- a/api/src/com/cloud/api/response/SwiftResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SwiftResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SwiftResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description = "the ID of swift") - private IdentityProxy id = new IdentityProxy("swift"); + private String id; @SerializedName(ApiConstants.URL) @Param(description = "url for swift") @@ -45,13 +45,9 @@ public class SwiftResponse extends BaseResponse { private String username; - @Override - public Long getObjectId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public String getUrl() { diff --git a/api/src/com/cloud/api/response/SystemVmInstanceResponse.java b/api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java similarity index 80% rename from api/src/com/cloud/api/response/SystemVmInstanceResponse.java rename to api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java index cae526efe57..48df8549ab3 100644 --- a/api/src/com/cloud/api/response/SystemVmInstanceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; /* * This is the generic response for all types of System VMs (SSVM, consoleproxy, domain routers(router, LB, DHCP)) */ public class SystemVmInstanceResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the system VM") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName("systemvmtype") @Param(description="the system VM type") private String systemVmType; @@ -34,25 +34,22 @@ public class SystemVmInstanceResponse extends BaseResponse { private String name; @SerializedName("hostid") @Param(description="the host ID for the system VM") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("state") @Param(description="the state of the system VM") private String state; - + @SerializedName("role") @Param(description="the role of the system VM") private String role; - - - public Long getObjectId() { - return getId(); + + + + public String getId() { + return id; } - public Long getId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getSystemVmType() { @@ -71,12 +68,12 @@ public class SystemVmInstanceResponse extends BaseResponse { this.name = name; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getState() { @@ -86,13 +83,13 @@ public class SystemVmInstanceResponse extends BaseResponse { public void setState(String state) { this.state = state; } - + public String getRole() { return role; } public void setRole(String role) { this.role = role; - } + } } diff --git a/api/src/com/cloud/api/response/SystemVmResponse.java b/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java similarity index 84% rename from api/src/com/cloud/api/response/SystemVmResponse.java rename to api/src/org/apache/cloudstack/api/response/SystemVmResponse.java index ea0025852cf..8b0f80b255a 100644 --- a/api/src/com/cloud/api/response/SystemVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java @@ -14,30 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachine.class) public class SystemVmResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the system VM") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName("systemvmtype") @Param(description="the system VM type") private String systemVmType; @SerializedName("jobid") @Param(description="the job ID associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.") - private IdentityProxy jobId = new IdentityProxy("async_job"); + private String jobId; @SerializedName("jobstatus") @Param(description="the job status associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.") private Integer jobStatus; @SerializedName("zoneid") @Param(description="the Zone ID for the system VM") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name for the system VM") private String zoneName; @@ -58,10 +61,10 @@ public class SystemVmResponse extends BaseResponse { private String name; @SerializedName("podid") @Param(description="the Pod ID for the system VM") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("hostid") @Param(description="the host ID for the system VM") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the hostname for the system VM") private String hostName; @@ -74,7 +77,7 @@ public class SystemVmResponse extends BaseResponse { @SerializedName(ApiConstants.PRIVATE_NETMASK) @Param(description="the private netmask for the system VM") private String privateNetmask; - + @SerializedName(ApiConstants.LINK_LOCAL_IP) @Param(description="the link local IP address for the system vm") private String linkLocalIp; @@ -94,33 +97,33 @@ public class SystemVmResponse extends BaseResponse { private String publicNetmask; @SerializedName("templateid") @Param(description="the template ID for the system VM") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("created") @Param(description="the date and time the system VM was created") private Date created; @SerializedName("state") @Param(description="the state of the system VM") private String state; - + @SerializedName("activeviewersessions") @Param(description="the number of active console sessions for the console proxy system vm") private Integer activeViewerSessions; - - private Long objectId; - - public Long getObjectId() { - return objectId; - } - - public void setObjectId(Long objectId) { - this.objectId = objectId; + + // private Long objectId; + + + + @Override + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getSystemVmType() { @@ -131,12 +134,12 @@ public class SystemVmResponse extends BaseResponse { this.systemVmType = systemVmType; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -187,20 +190,20 @@ public class SystemVmResponse extends BaseResponse { this.name = name; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getHostName() { @@ -259,12 +262,12 @@ public class SystemVmResponse extends BaseResponse { this.publicNetmask = publicNetmask; } - public Long getTemplateId() { - return templateId.getValue(); + public String getTemplateId() { + return templateId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public Date getCreated() { diff --git a/api/src/com/cloud/api/response/TemplatePermissionsResponse.java b/api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java similarity index 80% rename from api/src/com/cloud/api/response/TemplatePermissionsResponse.java rename to api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java index 1f801462e2d..f1e08e3dcc6 100644 --- a/api/src/com/cloud/api/response/TemplatePermissionsResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java @@ -14,43 +14,46 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachineTemplate.class) @SuppressWarnings("unused") public class TemplatePermissionsResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName(ApiConstants.IS_PUBLIC) @Param(description="true if this template is a public template, false otherwise") private Boolean publicTemplate; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain to which the template belongs") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the list of accounts the template is available for") private List accountNames; - + @SerializedName(ApiConstants.PROJECT_IDS) @Param(description="the list of projects the template is available for") private List projectIds; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setPublicTemplate(Boolean publicTemplate) { this.publicTemplate = publicTemplate; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setAccountNames(List accountNames) { diff --git a/api/src/com/cloud/api/response/TemplateResponse.java b/api/src/org/apache/cloudstack/api/response/TemplateResponse.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/response/TemplateResponse.java rename to api/src/org/apache/cloudstack/api/response/TemplateResponse.java index 5c3d3399799..033c2e243d5 --- a/api/src/com/cloud/api/response/TemplateResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TemplateResponse.java @@ -14,22 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; +import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.Storage.ImageFormat; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachineTemplate.class) @SuppressWarnings("unused") public class TemplateResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the template name") private String name; @@ -67,19 +70,19 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private boolean crossZones; @SerializedName(ApiConstants.OS_TYPE_ID) @Param(description="the ID of the OS type for this template.") - private IdentityProxy osTypeId = new IdentityProxy("guest_os"); + private String osTypeId; @SerializedName("ostypename") @Param(description="the name of the OS type for this template.") private String osTypeName; @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the account id to which the template belongs") - private IdentityProxy accountId = new IdentityProxy("account"); + private String accountId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name to which the template belongs") private String account; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the zone for this template") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone for this template") private String zoneName; @@ -97,10 +100,10 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private String hypervisor; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the domain to which the template belongs") - private String domainName; + private String domainName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain to which the template belongs") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.IS_EXTRACTABLE) @Param(description="true if the template is extractable, false otherwise") private Boolean extractable; @@ -109,65 +112,67 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private String checksum; @SerializedName("sourcetemplateid") @Param(description="the template ID of the parent template if present") - private IdentityProxy sourcetemplateId = new IdentityProxy("vm_template"); + private String sourcetemplateId; @SerializedName(ApiConstants.HOST_ID) @Param(description="the ID of the secondary storage host for the template") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the secondary storage host for the template") private String hostName; @SerializedName(ApiConstants.TEMPLATE_TAG) @Param(description="the tag of this template") private String templateTag; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the template") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the template") private String projectName; - + @SerializedName(ApiConstants.DETAILS) @Param(description="additional key/value details tied with template") private Map details; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with tempate", responseObject = ResourceTagResponse.class) private List tags; - + + @SerializedName(ApiConstants.SSHKEY_ENABLED) @Param(description="true if template is sshkey enabled, false otherwise") + private Boolean sshKeyEnabled; @Override - public Long getObjectId() { - return getId(); - } - - public Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public String getId() { + return id; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } public void setAccountName(String account) { this.account = account; } - public void setOsTypeId(Long osTypeId) { - this.osTypeId.setValue(osTypeId); + public void setOsTypeId(String osTypeId) { + this.osTypeId = osTypeId; } public void setOsTypeName(String osTypeName) { this.osTypeName = osTypeName; } - public void setId(long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -229,15 +234,15 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe public void setHypervisor(String hypervisor) { this.hypervisor = hypervisor; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setExtractable(Boolean extractable) { @@ -248,12 +253,12 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe this.checksum = checksum; } - public void setSourceTemplateId(Long sourcetemplateId) { - this.sourcetemplateId.setValue(sourcetemplateId); - } + public void setSourceTemplateId(String sourcetemplateId) { + this.sourcetemplateId = sourcetemplateId; + } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { @@ -263,26 +268,31 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe public void setTemplateTag(String templateTag) { this.templateTag = templateTag; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public Map getDetails() { - return this.details; + return this.details; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } - + public void setTags(List tags) { this.tags = tags; } + + public void setSshKeyEnabled(boolean sshKeyEnabled) { + this.sshKeyEnabled = sshKeyEnabled; + } + } diff --git a/server/src/com/cloud/server/api/response/TrafficMonitorResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java similarity index 77% rename from server/src/com/cloud/server/api/response/TrafficMonitorResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java index 9271c04bb5d..366e5d631b0 100644 --- a/server/src/com/cloud/server/api/response/TrafficMonitorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java @@ -14,67 +14,66 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class TrafficMonitorResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external firewall") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external firewall") private String numRetries; - + @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } - + public String getTimeout() { return timeout; } - + public void setTimeout(String timeout) { this.timeout = timeout; } diff --git a/api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java old mode 100755 new mode 100644 similarity index 61% rename from api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java index 3a5d4f71aa3..30adc3d87ca --- a/api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class TrafficTypeImplementorResponse extends BaseResponse { - @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="network traffic type") - private String trafficType; - - @SerializedName(ApiConstants.TRAFFIC_TYPE_IMPLEMENTOR) @Param(description="implementor of network traffic type") - private String implementor; - - public void setTrafficType(String type) { - this.trafficType = type; - } - - public void setImplementor(String impl) { - this.implementor = impl; - } + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="network traffic type") + private String trafficType; + + @SerializedName(ApiConstants.TRAFFIC_TYPE_IMPLEMENTOR) @Param(description="implementor of network traffic type") + private String implementor; + + public void setTrafficType(String type) { + this.trafficType = type; + } + + public void setImplementor(String impl) { + this.implementor = impl; + } } diff --git a/api/src/com/cloud/api/response/TrafficTypeResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java similarity index 81% rename from api/src/com/cloud/api/response/TrafficTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java index f64fbb1dd24..43760f2e1b4 100644 --- a/api/src/com/cloud/api/response/TrafficTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java @@ -14,13 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetworkTrafficType; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetworkTrafficType.class) public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="id of the network provider") @@ -28,10 +31,10 @@ public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the trafficType to be added to the physical network") private String trafficType; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.XEN_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenNetworkLabel; @@ -41,30 +44,36 @@ public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.VMWARE_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareNetworkLabel; - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + @Override + public String getObjectId() { + return this.id; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - + + public String getphysicalNetworkId() { + return physicalNetworkId; + } + public void setId(String uuid) { this.id = uuid; } - + public String getId() { return this.id; } - + public String getTrafficType() { return trafficType; } - + public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - + public String getXenLabel() { return xenNetworkLabel; } @@ -72,7 +81,7 @@ public class TrafficTypeResponse extends BaseResponse { public String getKvmLabel() { return kvmNetworkLabel; } - + public void setXenLabel(String xenLabel) { this.xenNetworkLabel = xenLabel; } @@ -83,8 +92,8 @@ public class TrafficTypeResponse extends BaseResponse { public void setVmwareLabel(String vmwareNetworkLabel) { this.vmwareNetworkLabel = vmwareNetworkLabel; - } - + } + public String getVmwareLabel() { return vmwareNetworkLabel; } diff --git a/api/src/com/cloud/api/response/UpgradeVmResponse.java b/api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java similarity index 83% rename from api/src/com/cloud/api/response/UpgradeVmResponse.java rename to api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java index e48ec08fe7c..767f783da44 100644 --- a/api/src/com/cloud/api/response/UpgradeVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class UpgradeVmResponse extends BaseResponse { - @SerializedName("id") - private IdentityProxy id = new IdentityProxy("vm_instance"); + @SerializedName("id") + private String id; public String getName() { return name; @@ -67,12 +67,12 @@ public class UpgradeVmResponse extends BaseResponse { this.account = account; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomain() { @@ -91,12 +91,12 @@ public class UpgradeVmResponse extends BaseResponse { this.haEnable = haEnable; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getDisplayName() { @@ -115,12 +115,12 @@ public class UpgradeVmResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getHostName() { @@ -131,12 +131,12 @@ public class UpgradeVmResponse extends BaseResponse { this.hostName = hostName; } - public Long getTemplateId() { - return templateId.getValue(); + public String getTemplateId() { + return templateId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public String getTemplateName() { @@ -163,12 +163,12 @@ public class UpgradeVmResponse extends BaseResponse { this.passwordEnabled = passwordEnabled; } - public Long getServiceOfferingId() { - return serviceOfferingId.getValue(); + public String getServiceOfferingId() { + return serviceOfferingId; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public String getServiceOfferingName() { @@ -219,8 +219,8 @@ public class UpgradeVmResponse extends BaseResponse { this.networkKbsWrite = networkKbsWrite; } - public Long isId() { - return id.getValue(); + public String isId() { + return id; } @SerializedName("name") @Param(description="the ID of the virtual machine") @@ -239,7 +239,7 @@ public class UpgradeVmResponse extends BaseResponse { private String account; @SerializedName("domainid") @Param(description="the ID of the domain in which the virtual machine exists") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description="the name of the domain in which the virtual machine exists") private String domain; @@ -248,7 +248,7 @@ public class UpgradeVmResponse extends BaseResponse { private boolean haEnable; @SerializedName("zoneid") @Param(description="the ID of the availablility zone for the virtual machine") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName("displayname") @Param(description="user generated name. The name of the virtual machine is returned if no displayname exists.") private String displayName; @@ -257,25 +257,25 @@ public class UpgradeVmResponse extends BaseResponse { private String zoneName; @SerializedName("hostid") @Param(description="the ID of the host for the virtual machine") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the host for the virtual machine") private String hostName; @SerializedName("templateid") @Param(description="the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file.") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("templatename") @Param(description="the name of the template for the virtual machine") private String templateName; - @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") + @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") private String templateDisplayText; @SerializedName("passwordenabled") @Param(description="true if the password rest feature is enabled, false otherwise") private boolean passwordEnabled; @SerializedName("serviceofferingid") @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; diff --git a/server/src/com/cloud/server/api/response/UsageRecordResponse.java b/api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java similarity index 80% rename from server/src/com/cloud/server/api/response/UsageRecordResponse.java rename to api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java index e80e262b716..9679575c046 100644 --- a/server/src/com/cloud/server/api/response/UsageRecordResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java @@ -14,12 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; -import com.cloud.api.response.ControlledEntityResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.response.ControlledEntityResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @@ -27,24 +26,24 @@ import com.google.gson.annotations.SerializedName; public class UsageRecordResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ACCOUNT) @Param(description="the user account name") private String accountName; - + @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the user account Id") - private IdentityProxy accountId = new IdentityProxy("account"); - + private String accountId; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the resource") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the resource") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain the resource is associated with") private String domainName; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.DESCRIPTION) @Param(description="description of the usage record") private String description; @@ -59,7 +58,7 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit private String rawUsage; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="virtual machine ID") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName(ApiConstants.NAME) @Param(description="virtual machine name") private String vmName; @@ -68,11 +67,11 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit private String offeringId; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="template ID") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("usageid") @Param(description="id of the resource") private String usageId; - + @SerializedName(ApiConstants.TYPE) @Param(description="resource type") private String type; @@ -90,29 +89,29 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="True if the IPAddress is system IP - allocated during vm deploy or lb rule create") private Boolean isSystem; - + @SerializedName("networkid") @Param(description="id of the network") private String networkId; - + @SerializedName("isdefault") @Param(description="True if the resource is default") private Boolean isDefault; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); - } - - @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setAccountId(String accountId) { + this.accountId = accountId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setDescription(String description) { @@ -131,8 +130,8 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit this.rawUsage = rawUsage; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVmName(String vmName) { @@ -143,8 +142,8 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit this.offeringId = offeringId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setUsageId(String usageId) { @@ -174,17 +173,17 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit public void setSystem(Boolean isSystem) { this.isSystem = isSystem; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; @@ -193,7 +192,7 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit public void setNetworkId(String networkId) { this.networkId = networkId; } - + public void setDefault(Boolean isDefault) { this.isDefault = isDefault; } diff --git a/server/src/com/cloud/server/api/response/UsageTypeResponse.java b/api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java similarity index 92% rename from server/src/com/cloud/server/api/response/UsageTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java index cb927e1c106..b21d26f3774 100644 --- a/server/src/com/cloud/server/api/response/UsageTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java @@ -14,10 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/api/src/com/cloud/api/response/UserResponse.java b/api/src/org/apache/cloudstack/api/response/UserResponse.java similarity index 84% rename from api/src/com/cloud/api/response/UserResponse.java rename to api/src/org/apache/cloudstack/api/response/UserResponse.java index b1382e98b8a..9ab6248ed2e 100644 --- a/api/src/com/cloud/api/response/UserResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UserResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import com.cloud.serializer.Param; +import com.cloud.user.User; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +@EntityReference(value = User.class) public class UserResponse extends BaseResponse { @SerializedName("id") @Param(description="the user ID") - private IdentityProxy id = new IdentityProxy("user"); + private String id; @SerializedName("username") @Param(description="the user name") private String username; @@ -52,7 +55,7 @@ public class UserResponse extends BaseResponse { private Short accountType; @SerializedName("domainid") @Param(description="the domain ID of the user") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description="the domain name of the user") private String domainName; @@ -67,17 +70,22 @@ public class UserResponse extends BaseResponse { private String secretKey; @SerializedName("accountid") @Param(description="the account ID of the user") - private IdentityProxy accountId = new IdentityProxy("account"); + private String accountId; @SerializedName("iscallerchilddomain") @Param(description="the boolean value representing if the updating target is in caller's child domain") private boolean isCallerChildDomain; - - public Long getId() { - return id.getValue(); + + @Override + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getUsername() { @@ -144,12 +152,12 @@ public class UserResponse extends BaseResponse { this.accountType = accountType; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomainName() { @@ -183,19 +191,19 @@ public class UserResponse extends BaseResponse { public void setSecretKey(String secretKey) { this.secretKey = secretKey; } - public Long getAccountId() { - return accountId.getValue(); + public String getAccountId() { + return accountId; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } - + public boolean getIsCallerSubdomain() { - return this.isCallerChildDomain; + return this.isCallerChildDomain; } - + public void setIsCallerChildDomain(boolean isCallerChildDomain) { - this.isCallerChildDomain = isCallerChildDomain; + this.isCallerChildDomain = isCallerChildDomain; } } diff --git a/api/src/com/cloud/api/response/UserVmResponse.java b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java old mode 100755 new mode 100644 similarity index 78% rename from api/src/com/cloud/api/response/UserVmResponse.java rename to api/src/org/apache/cloudstack/api/response/UserVmResponse.java index f74c07254c7..5450bfb6452 --- a/api/src/com/cloud/api/response/UserVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java @@ -14,20 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import com.cloud.network.router.VirtualRouter; +import com.cloud.uservm.UserVm; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.vm.VirtualMachine; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value={VirtualMachine.class, UserVm.class, VirtualRouter.class}) public class UserVmResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the virtual machine") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the virtual machine") private String name; @@ -37,15 +43,15 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the virtual machine") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vm") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vm") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain in which the virtual machine exists") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the domain in which the virtual machine exists") private String domainName; @@ -60,37 +66,37 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private Boolean haEnable; @SerializedName(ApiConstants.GROUP_ID) @Param(description="the group ID of the virtual machine") - private IdentityProxy groupId = new IdentityProxy("instance_group"); + private String groupId; @SerializedName(ApiConstants.GROUP) @Param(description="the group name of the virtual machine") private String group; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the availablility zone for the virtual machine") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the availability zone for the virtual machine") private String zoneName; @SerializedName(ApiConstants.HOST_ID) @Param(description="the ID of the host for the virtual machine") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the host for the virtual machine") private String hostName; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file.") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("templatename") @Param(description="the name of the template for the virtual machine") private String templateName; - @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") + @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") private String templateDisplayText; @SerializedName(ApiConstants.PASSWORD_ENABLED) @Param(description="true if the password rest feature is enabled, false otherwise") private Boolean passwordEnabled; @SerializedName("isoid") @Param(description="the ID of the ISO attached to the virtual machine") - private IdentityProxy isoId = new IdentityProxy("vm_template"); + private String isoId; @SerializedName("isoname") @Param(description="the name of the ISO attached to the virtual machine") private String isoName; @@ -99,11 +105,11 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private String isoDisplayText; @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; - + @SerializedName("forvirtualnetwork") @Param(description="the virtual network for the service offering") private Boolean forVirtualNetwork; @@ -118,7 +124,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @SerializedName("cpuused") @Param(description="the amount of the vm's CPU currently used") private String cpuUsed; - + @SerializedName("networkkbsread") @Param(description="the incoming network traffic on the vm") private Long networkKbsRead; @@ -126,7 +132,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private Long networkKbsWrite; @SerializedName("guestosid") @Param(description="Os type ID of the virtual machine") - private IdentityProxy guestOsId = new IdentityProxy("guest_os"); + private String guestOsId; @SerializedName("rootdeviceid") @Param(description="device ID of the root volume") private Long rootDeviceId; @@ -135,42 +141,55 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private String rootDeviceType; @SerializedName("securitygroup") @Param(description="list of security groups associated with the virtual machine", responseObject = SecurityGroupResponse.class) - private List securityGroupList; + private Set securityGroupList; @SerializedName(ApiConstants.PASSWORD) @Param(description="the password (if exists) of the virtual machine") private String password; @SerializedName("nic") @Param(description="the list of nics associated with vm", responseObject = NicResponse.class) - private List nics; - + private Set nics; + @SerializedName("hypervisor") @Param(description="the hypervisor on which the template runs") private String hypervisor; - + @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description="public IP address id associated with vm via Static nat rule") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); - + private String publicIpId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="public IP address id associated with vm via Static nat rule") private String publicIp; - + @SerializedName(ApiConstants.INSTANCE_NAME) @Param(description="instance name of the user vm; this parameter is returned to the ROOT admin only", since="3.0.1") private String instanceName; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) - private List tags; + private Set tags; @SerializedName(ApiConstants.SSH_KEYPAIR) @Param(description="ssh key-pair") private String keyPairName; - public void setHypervisor(String hypervisor) { - this.hypervisor = hypervisor; - } - - public void setId(Long id) { - this.id.setValue(id); + public UserVmResponse(){ + securityGroupList = new HashSet(); + nics = new HashSet(); + tags = new HashSet(); } - public Long getId() { - return this.id.getValue(); + public void setHypervisor(String hypervisor) { + this.hypervisor = hypervisor; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return this.id; + } + + + + @Override + public String getObjectId() { + return this.getId(); } public void setName(String name) { @@ -185,8 +204,9 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -205,32 +225,32 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.haEnable = haEnable; } - public void setGroupId(Long groupId) { - this.groupId.setValue(groupId); + public void setGroupId(String groupId) { + this.groupId = groupId; } public void setGroup(String group) { this.group = group; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { this.hostName = hostName; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setTemplateName(String templateName) { @@ -245,8 +265,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.passwordEnabled = passwordEnabled; } - public void setIsoId(Long isoId) { - this.isoId.setValue(isoId); + public void setIsoId(String isoId) { + this.isoId = isoId; } public void setIsoName(String isoName) { @@ -257,8 +277,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.isoDisplayText = isoDisplayText; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -289,8 +309,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.networkKbsWrite = networkKbsWrite; } - public void setGuestOsId(Long guestOsId) { - this.guestOsId.setValue(guestOsId); + public void setGuestOsId(String guestOsId) { + this.guestOsId = guestOsId; } public void setRootDeviceId(Long rootDeviceId) { @@ -305,39 +325,38 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.password = password; } -/* - public void setJobId(Long jobId) { - super.setJobId(jobId); - } - - public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; - } -*/ public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - public void setNics(List nics) { + public void setNics(Set nics) { this.nics = nics; } - public void setSecurityGroupList(List securityGroups) { + public void addNic(NicResponse nic) { + this.nics.add(nic); + } + + public void setSecurityGroupList(Set securityGroups) { this.securityGroupList = securityGroups; } - - @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + + public void addSecurityGroup(SecurityGroupResponse securityGroup){ + this.securityGroupList.add(securityGroup); } - + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } public void setPublicIp(String publicIp) { @@ -348,11 +367,16 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.instanceName = instanceName; } - public void setTags(List tags) { + public void setTags(Set tags) { this.tags = tags; } + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } + public void setKeyPairName(String keyPairName) { this.keyPairName = keyPairName; } + } diff --git a/api/src/com/cloud/api/response/VirtualRouterProviderResponse.java b/api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java similarity index 79% rename from api/src/com/cloud/api/response/VirtualRouterProviderResponse.java rename to api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java index 3e3e33dee16..dcb2322e5b9 100644 --- a/api/src/com/cloud/api/response/VirtualRouterProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java @@ -14,49 +14,52 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.VirtualRouterProvider; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualRouterProvider.class) public class VirtualRouterProviderResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the router") - private IdentityProxy id = new IdentityProxy("virtual_router_providers"); - + private String id; + @SerializedName(ApiConstants.NSP_ID) @Param(description="the physical network service provider id of the provider") - private IdentityProxy nspId = new IdentityProxy("physical_network_service_providers"); - + private String nspId; + @SerializedName(ApiConstants.ENABLED) @Param(description="Enabled/Disabled the service provider") private Boolean enabled; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the provider") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private Long projectId; - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID associated with the provider") - private Long domainId; + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain associated with the provider") private String domainName; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } @Override - public void setDomainId(Long domainId) { + public void setDomainId(String domainId) { this.domainId = domainId; } @@ -66,7 +69,7 @@ public class VirtualRouterProviderResponse extends BaseResponse implements Contr } @Override - public void setProjectId(Long projectId) { + public void setProjectId(String projectId) { this.projectId = projectId; } @@ -75,8 +78,8 @@ public class VirtualRouterProviderResponse extends BaseResponse implements Contr this.projectName = projectName; } - public void setNspId(Long nspId) { - this.nspId.setValue(nspId); + public void setNspId(String nspId) { + this.nspId = nspId; } public void setEnabled(Boolean enabled) { diff --git a/api/src/com/cloud/api/response/VlanIpRangeResponse.java b/api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java similarity index 75% rename from api/src/com/cloud/api/response/VlanIpRangeResponse.java rename to api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java index 63358161eaf..bfde73963c1 100644 --- a/api/src/com/cloud/api/response/VlanIpRangeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java @@ -14,23 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.dc.Vlan; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Vlan.class) @SuppressWarnings("unused") public class VlanIpRangeResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of the VLAN IP range") - private IdentityProxy id = new IdentityProxy("vlan"); + private String id; @SerializedName("forvirtualnetwork") @Param(description="the virtual network for the VLAN IP range") private Boolean forVirtualNetwork; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the VLAN IP range") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.VLAN) @Param(description="the ID or VID of the VLAN.") private String vlan; @@ -39,13 +42,13 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the VLAN IP range") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the VLAN IP range") private String domainName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID for the VLAN IP range") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name for the VLAN IP range") private String podName; @@ -64,49 +67,49 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.END_IP) @Param(description="the end ip of the VLAN IP range") private String endIp; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the network id of vlan range") - private IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vlan range") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vlan range") private String projectName; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - public void setId(Long id) { - this.id.setValue(id); + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") + private String physicalNetworkId; + + public void setId(String id) { + this.id = id; } public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public void setVlan(String vlan) { this.vlan = vlan; } - + public void setAccountName(String accountName) { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { this.domainName = domainName; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public void setPodName(String podName) { @@ -133,25 +136,25 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit this.endIp = endIp; } - public void setNetworkId(Long networkId) { - this.networkId.setValue(networkId); + public void setNetworkId(String networkId) { + this.networkId = networkId; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); - } + public String getphysicalNetworkId() { + return physicalNetworkId; + } } diff --git a/api/src/com/cloud/api/response/VolumeResponse.java b/api/src/org/apache/cloudstack/api/response/VolumeResponse.java old mode 100755 new mode 100644 similarity index 81% rename from api/src/com/cloud/api/response/VolumeResponse.java rename to api/src/org/apache/cloudstack/api/response/VolumeResponse.java index b5633908a81..d92153d0dbe --- a/api/src/com/cloud/api/response/VolumeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VolumeResponse.java @@ -14,21 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import com.cloud.storage.Volume; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Volume.class) @SuppressWarnings("unused") -public class VolumeResponse extends BaseResponse implements ControlledEntityResponse{ +public class VolumeResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description = "ID of the disk volume") - private IdentityProxy id = new IdentityProxy("volumes"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description = "name of the disk volume") @@ -36,7 +40,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ZONE_ID) @Param(description = "ID of the availability zone") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description = "name of the availability zone") @@ -52,7 +56,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description = "id of the virtual machine") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("vmname") @Param(description = "name of the virtual machine") @@ -81,16 +85,16 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the disk volume") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the disk volume") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the disk volume") @@ -106,7 +110,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.DISK_OFFERING_ID) @Param(description = "ID of the disk offering") - private IdentityProxy diskOfferingId = new IdentityProxy("disk_offering"); + private String diskOfferingId; @SerializedName("diskofferingname") @Param(description = "name of the disk offering") @@ -122,7 +126,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.SNAPSHOT_ID) @Param(description = "ID of the snapshot from which this volume was created") - private IdentityProxy snapshotId = new IdentityProxy("snapshots"); + private String snapshotId; @SerializedName("attached") @Param(description = "the date the volume was attached to a VM instance") @@ -134,7 +138,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description = "ID of the service offering for root disk") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description = "name of the service offering for root disk") @@ -147,17 +151,21 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName("isextractable") @Param(description = "true if the volume is extractable, false otherwise") private Boolean extractable; - + @SerializedName(ApiConstants.STATUS) @Param(description="the status of the volume") private String status; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with volume", responseObject = ResourceTagResponse.class) - private List tags; + private Set tags; + + public VolumeResponse(){ + tags = new HashSet(); + } @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } public Boolean getDestroyed() { @@ -168,22 +176,22 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.destroyed = destroyed; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { this.name = name; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public void setZoneName(String zoneName) { this.zoneName = zoneName; } @@ -196,8 +204,8 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.deviceId = deviceId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVirtualMachineName(String virtualMachineName) { @@ -224,10 +232,11 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } - + public void setDomainName(String domainName) { this.domainName = domainName; } @@ -240,8 +249,8 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.hypervisor = hypervisor; } - public void setDiskOfferingId(Long diskOfferingId) { - this.diskOfferingId.setValue(diskOfferingId); + public void setDiskOfferingId(String diskOfferingId) { + this.diskOfferingId = diskOfferingId; } public void setDiskOfferingName(String diskOfferingName) { @@ -256,16 +265,16 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.storagePoolName = storagePoolName; } - public void setSnapshotId(Long snapshotId) { - this.snapshotId.setValue(snapshotId); + public void setSnapshotId(String snapshotId) { + this.snapshotId = snapshotId; } public void setAttached(Date attached) { this.attached = attached; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -273,10 +282,10 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp } public void setStatus(String status) { - this.status = status; - } + this.status = status; + } - public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { + public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { this.serviceOfferingDisplayText = serviceOfferingDisplayText; } @@ -287,18 +296,22 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp public void setState(String state) { this.state = state; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setTags(List tags) { + + public void setTags(Set tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/VpcOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java similarity index 85% rename from api/src/com/cloud/api/response/VpcOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java index 51c5fc2c9ba..3e196febe24 100644 --- a/api/src/com/cloud/api/response/VpcOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java @@ -14,42 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.VpcOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VpcOffering.class) @SuppressWarnings("unused") -public class VpcOfferingResponse extends BaseResponse{ +public class VpcOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the vpc offering") - private final IdentityProxy id = new IdentityProxy("vpc_offerings"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the vpc offering") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the vpc offering.") private String displayText; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date this vpc offering was created") private Date created; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if vpc offering is default, false otherwise") private Boolean isDefault; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the vpc offering. Can be Disabled/Enabled") private String state; - + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -71,7 +74,7 @@ public class VpcOfferingResponse extends BaseResponse{ public void setServices(List services) { this.services = services; } - + public void setState(String state) { this.state = state; } diff --git a/api/src/com/cloud/api/response/VpcResponse.java b/api/src/org/apache/cloudstack/api/response/VpcResponse.java similarity index 83% rename from api/src/com/cloud/api/response/VpcResponse.java rename to api/src/org/apache/cloudstack/api/response/VpcResponse.java index bb79e53e942..94ea5983bf6 100644 --- a/api/src/com/cloud/api/response/VpcResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpcResponse.java @@ -14,77 +14,80 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.Vpc; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Vpc.class) @SuppressWarnings("unused") public class VpcResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName("id") @Param(description="the id of the VPC") - private final IdentityProxy id = new IdentityProxy("vpc"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the VPC") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the VPC.") private String displayText; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the VPC. Can be Inactive/Enabled") private String state; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the vpc") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the VPC belongs to") private String zoneName; - + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.CIDR) @Param(description="the cidr the VPC") private String cidr; - + @SerializedName(ApiConstants.VPC_OFF_ID) @Param(description="vpc offering id the VPC is created from") - private IdentityProxy vpcOfferingId = new IdentityProxy("vpc_offerings"); - + private String vpcOfferingId; + @SerializedName(ApiConstants.CREATED) @Param(description="the date this VPC was created") private Date created; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the VPC") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the VPC") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the VPC") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the VPC owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.NETWORK) @Param(description="the list of networks belongign to the VPC", responseObject = NetworkResponse.class) private List networks; - + @SerializedName(ApiConstants.RESTART_REQUIRED) @Param(description="true VPC requires restart") private Boolean restartRequired; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain of the VPC") private String networkDomain; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the project", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -102,7 +105,7 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons public void setServices(List services) { this.services = services; } - + public void setState(String state) { this.state = state; } @@ -113,8 +116,8 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -123,8 +126,8 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -132,16 +135,16 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons this.domain = domainName; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setCidr(String cidr) { this.cidr = cidr; } - - public void setVpcOfferingId(Long vpcOfferingId) { - this.vpcOfferingId.setValue(vpcOfferingId); + + public void setVpcOfferingId(String vpcOfferingId) { + this.vpcOfferingId = vpcOfferingId; } public List getNetworks() { @@ -151,19 +154,19 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons public void setNetworks(List networks) { this.networks = networks; } - + public void setRestartRequired(Boolean restartRequired) { this.restartRequired = restartRequired; } - + public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + public void setZoneName(String zoneName) { this.zoneName = zoneName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/VpnUsersResponse.java b/api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java similarity index 68% rename from api/src/com/cloud/api/response/VpnUsersResponse.java rename to api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java index d1e05803c9b..958c8b59bc4 100644 --- a/api/src/com/cloud/api/response/VpnUsersResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java @@ -14,17 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.VpnUser; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = VpnUser.class) @SuppressWarnings("unused") public class VpnUsersResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the vpn userID") - private IdentityProxy id = new IdentityProxy("vpn_users"); + private String id; @SerializedName(ApiConstants.USERNAME) @Param(description="the username of the vpn user") private String userName; @@ -33,46 +36,47 @@ public class VpnUsersResponse extends BaseResponse implements ControlledEntityRe private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the account of the remote access vpn") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the account of the remote access vpn") - private String domainName; - + private String domainName; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; - - public void setId(Long id) { - this.id.setValue(id); - } - - public void setUserName(String name) { - this.userName = name; - } - public void setAccountName(String accountName) { - this.accountName = accountName; - } + public void setId(String id) { + this.id = id; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + public void setUserName(String name) { + this.userName = name; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public void setDomainName(String name) { - this.domainName = name; - } - @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setDomainName(String name) { + this.domainName = name; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; - } + } } diff --git a/api/src/com/cloud/api/response/ZoneResponse.java b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/response/ZoneResponse.java rename to api/src/org/apache/cloudstack/api/response/ZoneResponse.java index 98f808d7044..72e0bb2844d --- a/api/src/com/cloud/api/response/ZoneResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.dc.DataCenter; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value = DataCenter.class) public class ZoneResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="Zone id") - private IdentityProxy id = new IdentityProxy("data_center"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="Zone name") private String name; @@ -45,52 +48,52 @@ public class ZoneResponse extends BaseResponse { @SerializedName(ApiConstants.INTERNAL_DNS2) @Param(description="the second internal DNS for the Zone") private String internalDns2; - + @SerializedName(ApiConstants.VLAN) @Param(description="the vlan range of the zone") private String vlan; @SerializedName(ApiConstants.GUEST_CIDR_ADDRESS) @Param(description="the guest CIDR address for the Zone") private String guestCidrAddress; - + //TODO - generate description @SerializedName("status") private String status; @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the display text of the zone") private String displayText; - + @SerializedName(ApiConstants.DOMAIN) @Param(description="Network domain name for the networks in the zone") private String domain; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the containing domain, null for public zones") private Long domainId; - + @SerializedName("domainname") @Param(description="the name of the containing domain, null for public zones") private String domainName; - + @SerializedName(ApiConstants.NETWORK_TYPE) @Param(description="the network type of the zone; can be Basic or Advanced") private String networkType; - + @SerializedName("securitygroupsenabled") @Param(description="true if security groups support is enabled, false otherwise") private boolean securityGroupsEnabled; - + @SerializedName("allocationstate") @Param(description="the allocation state of the cluster") - private String allocationState; - + private String allocationState; + @SerializedName(ApiConstants.ZONE_TOKEN) @Param(description="Zone Token") - private String zoneToken; - + private String zoneToken; + @SerializedName(ApiConstants.DHCP_PROVIDER) @Param(description="the dhcp Provider for the Zone") - private String dhcpProvider; - + private String dhcpProvider; + @SerializedName("capacity") @Param(description="the capacity of the Zone", responseObject = CapacityResponse.class) private List capacitites; @SerializedName(ApiConstants.LOCAL_STORAGE_ENABLED) @Param(description="true if local storage offering enabled, false otherwise") private boolean localStorageEnabled; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -137,10 +140,10 @@ public class ZoneResponse extends BaseResponse { this.domain = domain; } - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + public void setType(String networkType) { this.networkType = networkType; } @@ -148,26 +151,26 @@ public class ZoneResponse extends BaseResponse { public void setSecurityGroupsEnabled(boolean securityGroupsEnabled) { this.securityGroupsEnabled = securityGroupsEnabled; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - - public void setZoneToken(String zoneToken) { - this.zoneToken = zoneToken; - } - public void setDhcpProvider(String dhcpProvider) { - this.dhcpProvider = dhcpProvider; - } + public void setZoneToken(String zoneToken) { + this.zoneToken = zoneToken; + } - public void setCapacitites(List capacitites) { - this.capacitites = capacitites; - } + public void setDhcpProvider(String dhcpProvider) { + this.dhcpProvider = dhcpProvider; + } - public void setDomainName(String domainName) { - this.domainName = domainName; - } + public void setCapacitites(List capacitites) { + this.capacitites = capacitites; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } public void setLocalStorageEnabled(boolean localStorageEnabled) { this.localStorageEnabled = localStorageEnabled; diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java similarity index 89% rename from server/src/com/cloud/network/ExternalNetworkDeviceManager.java rename to api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java index b1de86f70f2..426a3b57dd9 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java +++ b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java @@ -14,19 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network; +package org.apache.cloudstack.network; import java.util.ArrayList; import java.util.List; -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; + +import com.cloud.network.Network; +import org.apache.cloudstack.api.command.admin.network.AddNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.ListNetworkDeviceCmd; import com.cloud.host.Host; -import com.cloud.server.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; import com.cloud.utils.component.Manager; public interface ExternalNetworkDeviceManager extends Manager { - + public static class NetworkDevice { private String _name; private String _provider; @@ -47,7 +49,7 @@ public interface ExternalNetworkDeviceManager extends Manager { _provider = ntwkServiceprovider; supportedNetworkDevices.add(this); } - + public String getName() { return _name; } @@ -67,11 +69,11 @@ public interface ExternalNetworkDeviceManager extends Manager { } public Host addNetworkDevice(AddNetworkDeviceCmd cmd); - + public NetworkDeviceResponse getApiResponse(Host device); - + public List listNetworkDevice(ListNetworkDeviceCmd cmd); - + public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd); - + } diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java new file mode 100644 index 00000000000..b03a7fc0062 --- /dev/null +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.query; + +import java.util.List; + +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; + + + +import com.cloud.async.AsyncJob; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.utils.Pair; + +/** + * Service used for list api query. + * @author minc + * + */ +public interface QueryService { + + public ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException; + + public ListResponse searchForEvents(ListEventsCmd cmd); + + public ListResponse listTags(ListTagsCmd cmd); + + public ListResponse searchForVmGroups(ListVMGroupsCmd cmd); + + public ListResponse searchForUserVMs(ListVMsCmd cmd); + + public ListResponse searchForSecurityGroups(ListSecurityGroupsCmd cmd); + + public ListResponse searchForRouters(ListRoutersCmd cmd); + + public ListResponse listProjectInvitations(ListProjectInvitationsCmd cmd); + + public ListResponse listProjects(ListProjectsCmd cmd); + + public ListResponse listProjectAccounts(ListProjectAccountsCmd cmd); + + public ListResponse searchForServers(ListHostsCmd cmd); + + public ListResponse searchForVolumes(ListVolumesCmd cmd); + + public ListResponse searchForStoragePools(ListStoragePoolsCmd cmd); + + public ListResponse searchForAccounts(ListAccountsCmd cmd); + + public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd); +} diff --git a/client/tomcatconf/virtualrouter_commands.properties.in b/api/test/integration/api/__init__.py similarity index 60% rename from client/tomcatconf/virtualrouter_commands.properties.in rename to api/test/integration/api/__init__.py index 0feef6ae4b6..d216be4ddc9 100644 --- a/client/tomcatconf/virtualrouter_commands.properties.in +++ b/api/test/integration/api/__init__.py @@ -5,20 +5,12 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### router commands -createVirtualRouterElement=com.cloud.api.commands.CreateVirtualRouterElementCmd;7 -configureVirtualRouterElement=com.cloud.api.commands.ConfigureVirtualRouterElementCmd;7 -listVirtualRouterElements=com.cloud.api.commands.ListVirtualRouterElementsCmd;7 +# under the License. \ No newline at end of file diff --git a/client/tomcatconf/simulator_commands.properties.in b/api/test/integration/api/setup.py similarity index 92% rename from client/tomcatconf/simulator_commands.properties.in rename to api/test/integration/api/setup.py index d2a46997e6f..13a83393a91 100644 --- a/client/tomcatconf/simulator_commands.properties.in +++ b/api/test/integration/api/setup.py @@ -14,6 +14,3 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. - - -configureSimulator=com.cloud.api.commands.ConfigureSimulator;1 \ No newline at end of file diff --git a/client/tomcatconf/cisconexusvsm_commands.properties.in b/api/test/integration/api/test/__init__.py similarity index 56% rename from client/tomcatconf/cisconexusvsm_commands.properties.in rename to api/test/integration/api/test/__init__.py index f6db0d9a9f0..d216be4ddc9 100644 --- a/client/tomcatconf/cisconexusvsm_commands.properties.in +++ b/api/test/integration/api/test/__init__.py @@ -5,21 +5,12 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### Cisco Nexus 1000v Virtual Supervisor Module (VSM) commands -deleteCiscoNexusVSM = com.cloud.api.commands.DeleteCiscoNexusVSMCmd;1 -enableCiscoNexusVSM = com.cloud.api.commands.EnableCiscoNexusVSMCmd;1 -disableCiscoNexusVSM = com.cloud.api.commands.DisableCiscoNexusVSMCmd;1 -listCiscoNexusVSMs = com.cloud.api.commands.ListCiscoNexusVSMsCmd;1 +# under the License. \ No newline at end of file diff --git a/client/tomcatconf/nicira-nvp_commands.properties.in b/api/test/integration/api/test/account/__init__.py similarity index 53% rename from client/tomcatconf/nicira-nvp_commands.properties.in rename to api/test/integration/api/test/account/__init__.py index 3a934adef67..d216be4ddc9 100644 --- a/client/tomcatconf/nicira-nvp_commands.properties.in +++ b/api/test/integration/api/test/account/__init__.py @@ -5,25 +5,12 @@ # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### nicira nvp commands - -addNiciraNvpDevice = com.cloud.api.commands.AddNiciraNvpDeviceCmd;1 -deleteNiciraNvpDevice = com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;1 -listNiciraNvpDevices = com.cloud.api.commands.ListNiciraNvpDevicesCmd;1 -listNiciraNvpDeviceNetworks = com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;1 - -# Not implemented (yet) -#configureNiciraNvpDevice = com.cloud.api.commands.ConfigureNiciraNvpDeviceCmd;1 +# under the License. \ No newline at end of file diff --git a/api/test/integration/api/test/account/testCreateAccount.py b/api/test/integration/api/test/account/testCreateAccount.py new file mode 100644 index 00000000000..b094e819421 --- /dev/null +++ b/api/test/integration/api/test/account/testCreateAccount.py @@ -0,0 +1,61 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import factory +import marvin +from marvin import cloudstackTestCase +from marvin.integration.lib.base import * +from marvin.integration.lib import utils + +class AccountFactory(factory.Factory): + FACTORY_FOR = createAccount.createAccountCmd + + firstname = 'firstname-'+random_gen() + lastname = 'lastname-'+random_gen() + email = factory.lazy_attribute(lambda e: '{0}.{1}@cloudstack.org'.format(e.firstname, e.lastname).lower()) + +class AdminAccountFactory(AccountFactory): + accounttype = 1 + +class UserAccountFactory(AccountFactory): + accounttype = 0 + +class TestCreateAccount(cloudstackTestCase): + def setUp(self): + self.apiClient = self.testClient.getApiClient() + self.userApiClient = self.testClient.getUserApiClient(account='test'+utils.random_gen(), 'ROOT') + + def test_createAccountAsAdmin(self): + """ + creates an account for a user as admin + """ + Account.create(self.apiClient, services=None) + from marvin.cloudstackAPI.createAccount import createAccountCmd + self.assertEqual(True, False) + + def test_createAccountAsUser(self): + """ + negative: create account as a user + """ + self.assertEqual(True, False) + + def tearDown(self): + self.apiClient.close() + self.userApiClient.close() + +if __name__ == '__main__': + unittest.main() diff --git a/api/test/src/com/cloud/agent/api/test/AgentControlAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java similarity index 96% rename from api/test/src/com/cloud/agent/api/test/AgentControlAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java index f8aaa4b800b..d0e8b4c7337 100644 --- a/api/test/src/com/cloud/agent/api/test/AgentControlAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/agent/api/test/AgentControlCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java similarity index 96% rename from api/test/src/com/cloud/agent/api/test/AgentControlCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java index 6df0edfc948..24d0fe587b8 100644 --- a/api/test/src/com/cloud/agent/api/test/AgentControlCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/agent/api/test/AnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/AnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java index c79db564201..343a3ce2a51 100644 --- a/api/test/src/com/cloud/agent/api/test/AnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/AttachIsoCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/AttachIsoCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java index 7fec7f2172f..d189d9ca858 100644 --- a/api/test/src/com/cloud/agent/api/test/AttachIsoCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/agent/api/test/AttachVolumeAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/AttachVolumeAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java index e7ec7d9cbf3..251a6cb917e 100644 --- a/api/test/src/com/cloud/agent/api/test/AttachVolumeAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/AttachVolumeCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/AttachVolumeCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java index 6fcd8c11bc7..1ec416a4d02 100644 --- a/api/test/src/com/cloud/agent/api/test/AttachVolumeCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java index b3f2847cd51..ede86e9d857 100644 --- a/api/test/src/com/cloud/agent/api/test/BackupSnapshotAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java similarity index 99% rename from api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java index a6241488943..91573d03c43 100644 --- a/api/test/src/com/cloud/agent/api/test/BackupSnapshotCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/agent/api/test/BumpUpPriorityCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/BumpUpPriorityCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java index 17afd5dd107..f5f59852ea8 100644 --- a/api/test/src/com/cloud/agent/api/test/BumpUpPriorityCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/CancelCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java similarity index 96% rename from api/test/src/com/cloud/agent/api/test/CancelCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java index 0f724c430e5..19827fd5753 100644 --- a/api/test/src/com/cloud/agent/api/test/CancelCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/ChangeAgentAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java similarity index 96% rename from api/test/src/com/cloud/agent/api/test/ChangeAgentAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java index 46ad821cd3a..8933e6e9b27 100644 --- a/api/test/src/com/cloud/agent/api/test/ChangeAgentAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/ChangeAgentCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java similarity index 97% rename from api/test/src/com/cloud/agent/api/test/ChangeAgentCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java index c084fefc68a..d0c2bf8b47b 100644 --- a/api/test/src/com/cloud/agent/api/test/ChangeAgentCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/agent/api/test/CheckHealthAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java similarity index 97% rename from api/test/src/com/cloud/agent/api/test/CheckHealthAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java index e07f6f35120..6fa94f9884d 100644 --- a/api/test/src/com/cloud/agent/api/test/CheckHealthAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/CheckHealthCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java similarity index 96% rename from api/test/src/com/cloud/agent/api/test/CheckHealthCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java index 61e985af7a0..1b565a5505b 100644 --- a/api/test/src/com/cloud/agent/api/test/CheckHealthCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/CheckNetworkAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java similarity index 97% rename from api/test/src/com/cloud/agent/api/test/CheckNetworkAnswerTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java index cae921af0e2..1853d3967c9 100644 --- a/api/test/src/com/cloud/agent/api/test/CheckNetworkAnswerTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/CheckNetworkCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java similarity index 97% rename from api/test/src/com/cloud/agent/api/test/CheckNetworkCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java index 0fbee4aaec5..0b87b587563 100644 --- a/api/test/src/com/cloud/agent/api/test/CheckNetworkCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/api/test/src/com/cloud/agent/api/test/CheckOnHostCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java similarity index 98% rename from api/test/src/com/cloud/agent/api/test/CheckOnHostCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java index a255399a9a1..1b682761996 100644 --- a/api/test/src/com/cloud/agent/api/test/CheckOnHostCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -43,6 +43,12 @@ public class CheckOnHostCommandTest { return 101L; }; + + @Override + public String getUuid() { + return "101"; + } + public String getName() { return "hostName"; }; diff --git a/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java similarity index 99% rename from api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java rename to api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java index 98cdee2a8bf..a7359134f0a 100644 --- a/api/test/src/com/cloud/agent/api/test/SnapshotCommandTest.java +++ b/api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.agent.api.test; +package org.apache.cloudstack.api.agent.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/api/test/src/com/cloud/api/commands/test/ActivateProjectCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java similarity index 95% rename from api/test/src/com/cloud/api/commands/test/ActivateProjectCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java index fb8bfebff56..49b5b0e1a16 100644 --- a/api/test/src/com/cloud/api/commands/test/ActivateProjectCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.user.project.ActivateProjectCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.commands.ActivateProjectCmd; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.projects.ProjectService; diff --git a/api/test/src/com/cloud/api/commands/test/AddAccountToProjectCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java similarity index 97% rename from api/test/src/com/cloud/api/commands/test/AddAccountToProjectCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java index 9b1606e1847..4d2000d4249 100644 --- a/api/test/src/com/cloud/api/commands/test/AddAccountToProjectCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.user.account.AddAccountToProjectCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -29,7 +30,6 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.projects.ProjectService; import com.cloud.user.Account; -import com.cloud.api.commands.AddAccountToProjectCmd; public class AddAccountToProjectCmdTest extends TestCase { diff --git a/api/test/src/com/cloud/api/commands/test/AddClusterCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java similarity index 94% rename from api/test/src/com/cloud/api/commands/test/AddClusterCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java index 933eef5fcd6..60fea9e54d2 100644 --- a/api/test/src/com/cloud/api/commands/test/AddClusterCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ResponseGenerator; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddClusterCmd; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.DiscoveryException; import com.cloud.exception.ResourceInUseException; import com.cloud.org.Cluster; diff --git a/api/test/src/com/cloud/api/commands/test/AddHostCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java similarity index 94% rename from api/test/src/com/cloud/api/commands/test/AddHostCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java index 476d1be63dd..4c1b5ee0e0a 100644 --- a/api/test/src/com/cloud/api/commands/test/AddHostCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.admin.host.AddHostCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ResponseGenerator; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddHostCmd; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.DiscoveryException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; diff --git a/api/test/src/com/cloud/api/commands/test/AddNetworkServiceProviderCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java similarity index 95% rename from api/test/src/com/cloud/api/commands/test/AddNetworkServiceProviderCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java index d4c5e614732..0b5798fbe23 100644 --- a/api/test/src/com/cloud/api/commands/test/AddNetworkServiceProviderCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import java.util.ArrayList; import java.util.List; @@ -22,14 +22,14 @@ import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.admin.network.AddNetworkServiceProviderCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddNetworkServiceProviderCmd; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.NetworkService; import com.cloud.network.PhysicalNetworkServiceProvider; diff --git a/api/test/src/com/cloud/api/commands/test/AddSecondaryStorageCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java similarity index 93% rename from api/test/src/com/cloud/api/commands/test/AddSecondaryStorageCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java index fb5ec4b827f..1cdd76fbfe2 100644 --- a/api/test/src/com/cloud/api/commands/test/AddSecondaryStorageCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java @@ -14,21 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.admin.host.AddSecondaryStorageCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ResponseGenerator; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddSecondaryStorageCmd; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.host.Host; import com.cloud.resource.ResourceService; diff --git a/api/test/src/com/cloud/api/commands/test/AddSwiftCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java similarity index 91% rename from api/test/src/com/cloud/api/commands/test/AddSwiftCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java index b5376b34daf..34d0baff5ab 100644 --- a/api/test/src/com/cloud/api/commands/test/AddSwiftCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java @@ -14,21 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ResponseGenerator; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.response.SwiftResponse; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.exception.DiscoveryException; import com.cloud.resource.ResourceService; import com.cloud.storage.Swift; diff --git a/api/test/src/com/cloud/api/commands/test/AddVpnUserCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java similarity index 96% rename from api/test/src/com/cloud/api/commands/test/AddVpnUserCmdTest.java rename to api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java index 63d1e2b7ff5..78e9d92fc9b 100644 --- a/api/test/src/com/cloud/api/commands/test/AddVpnUserCmdTest.java +++ b/api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package src.com.cloud.api.commands.test; +package org.apache.cloudstack.api.command.test; import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.cloudstack.api.command.user.vpn.AddVpnUserCmd; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.AddVpnUserCmd; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.network.VpnUser; import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.user.Account; diff --git a/api/test/src/com/cloud/agent/api/test/ResizeVolumeCommandTest.java b/api/test/src/com/cloud/agent/api/test/ResizeVolumeCommandTest.java new file mode 100644 index 00000000000..2d248b2f53a --- /dev/null +++ b/api/test/src/com/cloud/agent/api/test/ResizeVolumeCommandTest.java @@ -0,0 +1,199 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package src.com.cloud.agent.api.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.junit.Test; + +import com.cloud.agent.api.storage.ResizeVolumeCommand; +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.storage.StoragePool; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.StoragePoolStatus; + + +public class ResizeVolumeCommandTest { + + public StoragePool dummypool = new StoragePool() { + public long getId() { + return 1L; + }; + + public String getName() { + return "name"; + }; + + public String getUuid() { + return "bed9f83e-cac3-11e1-ac8a-0050568b007e"; + }; + + public StoragePoolType getPoolType() { + return StoragePoolType.Filesystem; + }; + + public Date getCreated() { + Date date = null; + try { + date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/1970 12:12:12"); + } catch (ParseException e) { + e.printStackTrace(); + } + return date; + } + + public Date getUpdateTime() { + return new Date(); + }; + + public long getDataCenterId() { + return 0L; + }; + + public long getCapacityBytes() { + return 0L; + }; + + public long getAvailableBytes() { + return 0L; + }; + + public Long getClusterId() { + return 0L; + }; + + public String getHostAddress() { + return "hostAddress"; + }; + + public String getPath() { + return "path"; + }; + + public String getUserInfo() { + return "userInfo"; + }; + + public boolean isShared() { + return false; + }; + + public boolean isLocal() { + return false; + }; + + public StoragePoolStatus getStatus() { + return StoragePoolStatus.Up; + }; + + public int getPort() { + return 25; + }; + + public Long getPodId() { + return 0L; + }; + }; + + Long newSize = 4194304L; + Long currentSize = 1048576L; + + ResizeVolumeCommand rv = new ResizeVolumeCommand("dummydiskpath", + new StorageFilerTO(dummypool), currentSize, newSize, false, + "vmName"); + + @Test + public void testExecuteInSequence() { + boolean b = rv.executeInSequence(); + assertFalse(b); + } + + @Test + public void testGetPath() { + String path = rv.getPath(); + assertTrue(path.equals("dummydiskpath")); + } + + @Test + public void testGetPoolUuid() { + String poolUuid = rv.getPoolUuid(); + assertTrue(poolUuid.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + } + + @Test + public void testGetPool() { + StorageFilerTO pool = rv.getPool(); + + Long id = pool.getId(); + Long expectedL = 1L; + assertEquals(expectedL, id); + + String uuid = pool.getUuid(); + assertTrue(uuid.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + + String host = pool.getHost(); + assertTrue(host.equals("hostAddress")); + + String path = pool.getPath(); + assertTrue(path.equals("path")); + + String userInfo = pool.getUserInfo(); + assertTrue(userInfo.equals("userInfo")); + + Integer port = pool.getPort(); + Integer expectedI = 25; + assertEquals(expectedI, port); + + StoragePoolType type = pool.getType(); + assertEquals(StoragePoolType.Filesystem, type); + + String str = pool.toString(); + assertTrue(str.equals("Pool[" + id.toString() + "|" + host + ":" + + port.toString() + "|" + path + "]")); + } + + @Test + public void testGetNewSize() { + long newSize = rv.getNewSize(); + assertTrue(newSize == 4194304L); + } + + @Test + public void testGetCurrentSize() { + long currentSize = rv.getCurrentSize(); + assertTrue(currentSize == 1048576L); + } + + @Test + public void testGetShrinkOk() { + assertFalse(rv.getShrinkOk()); + } + + @Test + public void testGetInstanceName() { + String vmName = rv.getInstanceName(); + assertTrue(vmName.equals("vmName")); + } + +} diff --git a/awsapi/pom.xml b/awsapi/pom.xml index 06c9d7e058a..3ab595211d4 100644 --- a/awsapi/pom.xml +++ b/awsapi/pom.xml @@ -266,6 +266,7 @@ mysql mysql-connector-java + ${cs.mysql.version} runtime diff --git a/client/bindir/cloud-setup-management.in b/client/bindir/cloud-setup-management.in index 469c9614b41..ca1327ae725 100755 --- a/client/bindir/cloud-setup-management.in +++ b/client/bindir/cloud-setup-management.in @@ -16,8 +16,9 @@ # specific language governing permissions and limitations # under the License. +import sys from cloudutils.syscfg import sysConfigFactory -from cloudutils.utilities import initLoging +from cloudutils.utilities import initLoging, UnknownSystemException from cloudutils.cloudException import CloudRuntimeException, CloudInternalException from cloudutils.globalEnv import globalEnv from cloudutils.serviceConfigServer import cloudManagementConfig @@ -35,7 +36,12 @@ if __name__ == '__main__': glbEnv.mode = "Server" print "Starting to configure CloudStack Management Server:" - syscfg = sysConfigFactory.getSysConfigFactory(glbEnv) + try: + syscfg = sysConfigFactory.getSysConfigFactory(glbEnv) + except UnknownSystemException: + print >>sys.stderr, ("Error: CloudStack failed to detect your " + "operating system. Exiting.") + sys.exit(1) try: syscfg.registerService(cloudManagementConfig) syscfg.config() diff --git a/client/distro/ubuntu/SYSCONFDIR/init.d/cloud-management.in b/client/distro/ubuntu/SYSCONFDIR/init.d/cloud-management.in index 5ed86c2ceb5..4afa707a9e9 100755 --- a/client/distro/ubuntu/SYSCONFDIR/init.d/cloud-management.in +++ b/client/distro/ubuntu/SYSCONFDIR/init.d/cloud-management.in @@ -38,6 +38,11 @@ CATALINA_HOME=@MSENVIRON@ DEFAULT=@MSCONF@/tomcat6.conf JVM_TMP=/tmp/$NAME-temp +# We have to explicitly set the HOME variable to the homedir from the user "cloud" +# This is because various scripts run by the management server read the HOME variable +# and fail when this init script is run manually. +HOME=$(echo ~cloud) + if [ `id -u` -ne 0 ]; then echo "You need root privileges to run this script" exit 1 diff --git a/client/pom.xml b/client/pom.xml index 77077066f9a..1bbae1f7d08 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -25,6 +25,16 @@ cloud-server ${project.version} + + org.apache.cloudstack + cloud-plugin-acl-static-role-based + ${project.version} + + + org.apache.cloudstack + cloud-plugin-api-discovery + ${project.version} + org.apache.cloudstack cloud-plugin-user-authenticator-ldap @@ -104,6 +114,7 @@ mysql mysql-connector-java + ${cs.mysql.version} runtime diff --git a/client/tomcatconf/commands-ext.properties.in b/client/tomcatconf/commands-ext.properties.in deleted file mode 100644 index f172067ede9..00000000000 --- a/client/tomcatconf/commands-ext.properties.in +++ /dev/null @@ -1,35 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -#### usage commands -generateUsageRecords=com.cloud.api.commands.GenerateUsageRecordsCmd;1 -listUsageRecords=com.cloud.api.commands.GetUsageRecordsCmd;1 -listUsageTypes=com.cloud.api.commands.ListUsageTypesCmd;1 - - - -### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 - -#### traffic monitor commands -addTrafficMonitor=com.cloud.api.commands.AddTrafficMonitorCmd;1 -deleteTrafficMonitor=com.cloud.api.commands.DeleteTrafficMonitorCmd;1 -listTrafficMonitors=com.cloud.api.commands.ListTrafficMonitorsCmd;1 - - diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in old mode 100755 new mode 100644 index 27e0c2fc3cf..182cbd8cf3b --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -19,412 +19,493 @@ ### Please standardize naming conventions to camel-case (even for acronyms). ### Account commands -createAccount=com.cloud.api.commands.CreateAccountCmd;3 -deleteAccount=com.cloud.api.commands.DeleteAccountCmd;3 -updateAccount=com.cloud.api.commands.UpdateAccountCmd;3 -disableAccount=com.cloud.api.commands.DisableAccountCmd;7 -enableAccount=com.cloud.api.commands.EnableAccountCmd;7 -###lockAccount=com.cloud.api.commands.LockAccountCmd;7 -listAccounts=com.cloud.api.commands.ListAccountsCmd;15 -markDefaultZoneForAccount=com.cloud.api.commands.MarkDefaultZoneForAccountCmd;1 +createAccount=3 +deleteAccount=3 +updateAccount=3 +disableAccount=7 +enableAccount=7 +lockAccount=7 +listAccounts=15 +markDefaultZoneForAccount=1 #### User commands -createUser=com.cloud.api.commands.CreateUserCmd;3 -deleteUser=com.cloud.api.commands.DeleteUserCmd;3 -updateUser=com.cloud.api.commands.UpdateUserCmd;15 -listUsers=com.cloud.api.commands.ListUsersCmd;7 -####lockUser=com.cloud.api.commands.LockUserCmd;7 -disableUser=com.cloud.api.commands.DisableUserCmd;7 -enableUser=com.cloud.api.commands.EnableUserCmd;7 -getUser=com.cloud.api.commands.GetUserCmd;1 +createUser=3 +deleteUser=3 +updateUser=15 +listUsers=7 +lockUser=7 +disableUser=7 +enableUser=7 +getUser=1 #### Domain commands -createDomain=com.cloud.api.commands.CreateDomainCmd;1 -updateDomain=com.cloud.api.commands.UpdateDomainCmd;1 -deleteDomain=com.cloud.api.commands.DeleteDomainCmd;1 -listDomains=com.cloud.api.commands.ListDomainsCmd;7 -listDomainChildren=com.cloud.api.commands.ListDomainChildrenCmd;7 +createDomain=1 +updateDomain=1 +deleteDomain=1 +listDomains=7 +listDomainChildren=7 ####Cloud Identifier commands -getCloudIdentifier=com.cloud.api.commands.GetCloudIdentifierCmd;15 +getCloudIdentifier=15 #### Limit commands -updateResourceLimit=com.cloud.api.commands.UpdateResourceLimitCmd;7 -updateResourceCount=com.cloud.api.commands.UpdateResourceCountCmd;7 -listResourceLimits=com.cloud.api.commands.ListResourceLimitsCmd;15 +updateResourceLimit=7 +updateResourceCount=7 +listResourceLimits=15 #### VM commands -deployVirtualMachine=com.cloud.api.commands.DeployVMCmd;15 -destroyVirtualMachine=com.cloud.api.commands.DestroyVMCmd;15 -rebootVirtualMachine=com.cloud.api.commands.RebootVMCmd;15 -startVirtualMachine=com.cloud.api.commands.StartVMCmd;15 -stopVirtualMachine=com.cloud.api.commands.StopVMCmd;15 -resetPasswordForVirtualMachine=com.cloud.api.commands.ResetVMPasswordCmd;15 -changeServiceForVirtualMachine=com.cloud.api.commands.UpgradeVMCmd;15 -updateVirtualMachine=com.cloud.api.commands.UpdateVMCmd;15 -recoverVirtualMachine=com.cloud.api.commands.RecoverVMCmd;7 -listVirtualMachines=com.cloud.api.commands.ListVMsCmd;15 -getVMPassword=com.cloud.api.commands.GetVMPasswordCmd;15 -migrateVirtualMachine=com.cloud.api.commands.MigrateVMCmd;1 -assignVirtualMachine=com.cloud.api.commands.AssignVMCmd;1 -restoreVirtualMachine=com.cloud.api.commands.RestoreVMCmd;15 +deployVirtualMachine=15 +destroyVirtualMachine=15 +rebootVirtualMachine=15 +startVirtualMachine=15 +stopVirtualMachine=15 +resetPasswordForVirtualMachine=15 +updateVirtualMachine=15 +listVirtualMachines=15 +getVMPassword=15 +restoreVirtualMachine=15 +changeServiceForVirtualMachine=15 +assignVirtualMachine=1 +migrateVirtualMachine=1 +recoverVirtualMachine=7 #### snapshot commands -createSnapshot=com.cloud.api.commands.CreateSnapshotCmd;15 -listSnapshots=com.cloud.api.commands.ListSnapshotsCmd;15 -deleteSnapshot=com.cloud.api.commands.DeleteSnapshotCmd;15 -createSnapshotPolicy=com.cloud.api.commands.CreateSnapshotPolicyCmd;15 -deleteSnapshotPolicies=com.cloud.api.commands.DeleteSnapshotPoliciesCmd;15 -listSnapshotPolicies=com.cloud.api.commands.ListSnapshotPoliciesCmd;15 +createSnapshot=15 +listSnapshots=15 +deleteSnapshot=15 +createSnapshotPolicy=15 +deleteSnapshotPolicies=15 +listSnapshotPolicies=15 #### template commands -createTemplate=com.cloud.api.commands.CreateTemplateCmd;15 -registerTemplate=com.cloud.api.commands.RegisterTemplateCmd;15 -updateTemplate=com.cloud.api.commands.UpdateTemplateCmd;15 -copyTemplate=com.cloud.api.commands.CopyTemplateCmd;15 -deleteTemplate=com.cloud.api.commands.DeleteTemplateCmd;15 -listTemplates=com.cloud.api.commands.ListTemplatesCmd;15 -updateTemplatePermissions=com.cloud.api.commands.UpdateTemplatePermissionsCmd;15 -listTemplatePermissions=com.cloud.api.commands.ListTemplatePermissionsCmd;15 -extractTemplate=com.cloud.api.commands.ExtractTemplateCmd;15 -prepareTemplate=com.cloud.api.commands.PrepareTemplateCmd;1 +createTemplate=15 +registerTemplate=15 +updateTemplate=15 +copyTemplate=15 +deleteTemplate=15 +listTemplates=15 +updateTemplatePermissions=15 +listTemplatePermissions=15 +extractTemplate=15 +prepareTemplate=1 #### iso commands -attachIso=com.cloud.api.commands.AttachIsoCmd;15 -detachIso=com.cloud.api.commands.DetachIsoCmd;15 -listIsos=com.cloud.api.commands.ListIsosCmd;15 -registerIso=com.cloud.api.commands.RegisterIsoCmd;15 -updateIso=com.cloud.api.commands.UpdateIsoCmd;15 -deleteIso=com.cloud.api.commands.DeleteIsoCmd;15 -copyIso=com.cloud.api.commands.CopyTemplateCmd;15 -updateIsoPermissions=com.cloud.api.commands.UpdateIsoPermissionsCmd;15 -listIsoPermissions=com.cloud.api.commands.ListIsoPermissionsCmd;15 -extractIso=com.cloud.api.commands.ExtractIsoCmd;15 +attachIso=15 +detachIso=15 +listIsos=15 +registerIso=15 +updateIso=15 +deleteIso=15 +copyIso=15 +updateIsoPermissions=15 +listIsoPermissions=15 +extractIso=15 #### guest OS commands -listOsTypes=com.cloud.api.commands.ListGuestOsCmd;15 -listOsCategories=com.cloud.api.commands.ListGuestOsCategoriesCmd;15 +listOsTypes=15 +listOsCategories=15 #### service offering commands -createServiceOffering=com.cloud.api.commands.CreateServiceOfferingCmd;1 -deleteServiceOffering=com.cloud.api.commands.DeleteServiceOfferingCmd;1 -updateServiceOffering=com.cloud.api.commands.UpdateServiceOfferingCmd;1 -listServiceOfferings=com.cloud.api.commands.ListServiceOfferingsCmd;15 +createServiceOffering=1 +deleteServiceOffering=1 +updateServiceOffering=1 +listServiceOfferings=15 #### disk offering commands -createDiskOffering=com.cloud.api.commands.CreateDiskOfferingCmd;1 -updateDiskOffering=com.cloud.api.commands.UpdateDiskOfferingCmd;1 -deleteDiskOffering=com.cloud.api.commands.DeleteDiskOfferingCmd;1 -listDiskOfferings=com.cloud.api.commands.ListDiskOfferingsCmd;15 +createDiskOffering=1 +updateDiskOffering=1 +deleteDiskOffering=1 +listDiskOfferings=15 #### vlan commands -createVlanIpRange=com.cloud.api.commands.CreateVlanIpRangeCmd;1 -deleteVlanIpRange=com.cloud.api.commands.DeleteVlanIpRangeCmd;1 -listVlanIpRanges=com.cloud.api.commands.ListVlanIpRangesCmd;1 +createVlanIpRange=1 +deleteVlanIpRange=1 +listVlanIpRanges=1 #### address commands -associateIpAddress=com.cloud.api.commands.AssociateIPAddrCmd;15 -disassociateIpAddress=com.cloud.api.commands.DisassociateIPAddrCmd;15 -listPublicIpAddresses=com.cloud.api.commands.ListPublicIpAddressesCmd;15 +associateIpAddress=15 +disassociateIpAddress=15 +listPublicIpAddresses=15 #### firewall commands -listPortForwardingRules=com.cloud.api.commands.ListPortForwardingRulesCmd;15 -createPortForwardingRule=com.cloud.api.commands.CreatePortForwardingRuleCmd;15 -deletePortForwardingRule=com.cloud.api.commands.DeletePortForwardingRuleCmd;15 -#### updatePortForwardingRule=com.cloud.api.commands.UpdatePortForwardingRuleCmd;15 +listPortForwardingRules=15 +createPortForwardingRule=15 +deletePortForwardingRule=15 +updatePortForwardingRule=15 #### NAT commands -enableStaticNat=com.cloud.api.commands.EnableStaticNatCmd;15 -createIpForwardingRule=com.cloud.api.commands.CreateIpForwardingRuleCmd;15 -deleteIpForwardingRule=com.cloud.api.commands.DeleteIpForwardingRuleCmd;15 -listIpForwardingRules=com.cloud.api.commands.ListIpForwardingRulesCmd;15 -disableStaticNat=com.cloud.api.commands.DisableStaticNatCmd;15 +enableStaticNat=15 +createIpForwardingRule=15 +deleteIpForwardingRule=15 +listIpForwardingRules=15 +disableStaticNat=15 #### load balancer commands -createLoadBalancerRule=com.cloud.api.commands.CreateLoadBalancerRuleCmd;15 -deleteLoadBalancerRule=com.cloud.api.commands.DeleteLoadBalancerRuleCmd;15 -removeFromLoadBalancerRule=com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;15 -assignToLoadBalancerRule=com.cloud.api.commands.AssignToLoadBalancerRuleCmd;15 -createLBStickinessPolicy=com.cloud.api.commands.CreateLBStickinessPolicyCmd;15 -deleteLBStickinessPolicy=com.cloud.api.commands.DeleteLBStickinessPolicyCmd;15 -listLoadBalancerRules=com.cloud.api.commands.ListLoadBalancerRulesCmd;15 -listLBStickinessPolicies=com.cloud.api.commands.ListLBStickinessPoliciesCmd;15 -listLoadBalancerRuleInstances=com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;15 -updateLoadBalancerRule=com.cloud.api.commands.UpdateLoadBalancerRuleCmd;15 +createLoadBalancerRule=15 +deleteLoadBalancerRule=15 +removeFromLoadBalancerRule=15 +assignToLoadBalancerRule=15 +createLBStickinessPolicy=15 +deleteLBStickinessPolicy=15 +listLoadBalancerRules=15 +listLBStickinessPolicies=15 +listLoadBalancerRuleInstances=15 +updateLoadBalancerRule=15 #### autoscale commands -createCounter = com.cloud.api.commands.CreateCounterCmd;1 -createCondition = com.cloud.api.commands.CreateConditionCmd;15 -createAutoScalePolicy=com.cloud.api.commands.CreateAutoScalePolicyCmd;15 -createAutoScaleVmProfile=com.cloud.api.commands.CreateAutoScaleVmProfileCmd;15 -createAutoScaleVmGroup=com.cloud.api.commands.CreateAutoScaleVmGroupCmd;15 -deleteCounter = com.cloud.api.commands.DeleteCounterCmd;1 -deleteCondition = com.cloud.api.commands.DeleteConditionCmd;15 -deleteAutoScalePolicy=com.cloud.api.commands.DeleteAutoScalePolicyCmd;15 -deleteAutoScaleVmProfile=com.cloud.api.commands.DeleteAutoScaleVmProfileCmd;15 -deleteAutoScaleVmGroup=com.cloud.api.commands.DeleteAutoScaleVmGroupCmd;15 -listCounters = com.cloud.api.commands.ListCountersCmd;15 -listConditions = com.cloud.api.commands.ListConditionsCmd;15 -listAutoScalePolicies=com.cloud.api.commands.ListAutoScalePoliciesCmd;15 -listAutoScaleVmProfiles=com.cloud.api.commands.ListAutoScaleVmProfilesCmd;15 -listAutoScaleVmGroups=com.cloud.api.commands.ListAutoScaleVmGroupsCmd;15 -enableAutoScaleVmGroup=com.cloud.api.commands.EnableAutoScaleVmGroupCmd;15 -disableAutoScaleVmGroup=com.cloud.api.commands.DisableAutoScaleVmGroupCmd;15 -updateAutoScalePolicy=com.cloud.api.commands.UpdateAutoScalePolicyCmd;15 -updateAutoScaleVmProfile=com.cloud.api.commands.UpdateAutoScaleVmProfileCmd;15 -updateAutoScaleVmGroup=com.cloud.api.commands.UpdateAutoScaleVmGroupCmd;15 +createCounter=1 +createCondition=15 +createAutoScalePolicy=15 +createAutoScaleVmProfile=15 +createAutoScaleVmGroup=15 +deleteCounter=1 +deleteCondition=15 +deleteAutoScalePolicy=15 +deleteAutoScaleVmProfile=15 +deleteAutoScaleVmGroup=15 +listCounters=15 +listConditions=15 +listAutoScalePolicies=15 +listAutoScaleVmProfiles=15 +listAutoScaleVmGroups=15 +enableAutoScaleVmGroup=15 +disableAutoScaleVmGroup=15 +updateAutoScalePolicy=15 +updateAutoScaleVmProfile=15 +updateAutoScaleVmGroup=15 #### router commands -startRouter=com.cloud.api.commands.StartRouterCmd;7 -rebootRouter=com.cloud.api.commands.RebootRouterCmd;7 -stopRouter=com.cloud.api.commands.StopRouterCmd;7 -destroyRouter=com.cloud.api.commands.DestroyRouterCmd;7 -changeServiceForRouter=com.cloud.api.commands.UpgradeRouterCmd;7 -listRouters=com.cloud.api.commands.ListRoutersCmd;7 -listVirtualRouterElements=com.cloud.api.commands.ListVirtualRouterElementsCmd;7 -configureVirtualRouterElement=com.cloud.api.commands.ConfigureVirtualRouterElementCmd;7 +startRouter=7 +rebootRouter=7 +stopRouter=7 +destroyRouter=7 +changeServiceForRouter=7 +listRouters=7 +listVirtualRouterElements=7 +configureVirtualRouterElement=7 +createVirtualRouterElement=7 #### system vm commands -startSystemVm=com.cloud.api.commands.StartSystemVMCmd;1 -rebootSystemVm=com.cloud.api.commands.RebootSystemVmCmd;1 -stopSystemVm=com.cloud.api.commands.StopSystemVmCmd;1 -destroySystemVm=com.cloud.api.commands.DestroySystemVmCmd;1 -listSystemVms=com.cloud.api.commands.ListSystemVMsCmd;3 -migrateSystemVm=com.cloud.api.commands.MigrateSystemVMCmd;1 -changeServiceForSystemVm=com.cloud.api.commands.UpgradeSystemVMCmd;1 +startSystemVm=1 +rebootSystemVm=1 +stopSystemVm=1 +destroySystemVm=1 +listSystemVms=3 +migrateSystemVm=1 +changeServiceForSystemVm=1 #### configuration commands -updateConfiguration=com.cloud.api.commands.UpdateCfgCmd;1 -listConfigurations=com.cloud.api.commands.ListCfgsByCmd;1 -ldapConfig=com.cloud.api.commands.LDAPConfigCmd;1 -ldapRemove=com.cloud.api.commands.LDAPRemoveCmd;1 -listCapabilities=com.cloud.api.commands.ListCapabilitiesCmd;15 +updateConfiguration=1 +listConfigurations=1 +ldapConfig=1 +ldapRemove=1 +listCapabilities=15 #### pod commands -createPod=com.cloud.api.commands.CreatePodCmd;1 -updatePod=com.cloud.api.commands.UpdatePodCmd;1 -deletePod=com.cloud.api.commands.DeletePodCmd;1 -listPods=com.cloud.api.commands.ListPodsByCmd;3 +createPod=1 +updatePod=1 +deletePod=1 +listPods=3 #### zone commands -createZone=com.cloud.api.commands.CreateZoneCmd;1 -updateZone=com.cloud.api.commands.UpdateZoneCmd;1 -deleteZone=com.cloud.api.commands.DeleteZoneCmd;1 -listZones=com.cloud.api.commands.ListZonesByCmd;15 +createZone=1 +updateZone=1 +deleteZone=1 +listZones=15 #### events commands -listEvents=com.cloud.api.commands.ListEventsCmd;15 -listEventTypes=com.cloud.api.commands.ListEventTypesCmd;15 +listEvents=15 +listEventTypes=15 #### alerts commands -listAlerts=com.cloud.api.commands.ListAlertsCmd;3 +listAlerts=3 #### system capacity commands -listCapacity=com.cloud.api.commands.ListCapacityCmd;3 +listCapacity=3 -#### swift commands^M -addSwift=com.cloud.api.commands.AddSwiftCmd;1 -listSwifts=com.cloud.api.commands.ListSwiftsCmd;1 +#### swift commands +addSwift=1 +listSwifts=1 #### s3 commands -addS3=com.cloud.api.commands.AddS3Cmd;1 -listS3s=com.cloud.api.commands.ListS3sCmd;1 +addS3=1 +listS3s=1 #### host commands -addHost=com.cloud.api.commands.AddHostCmd;3 -addCluster=com.cloud.api.commands.AddClusterCmd;1 -deleteCluster=com.cloud.api.commands.DeleteClusterCmd;1 -updateCluster=com.cloud.api.commands.UpdateClusterCmd;1 -reconnectHost=com.cloud.api.commands.ReconnectHostCmd;1 -updateHost=com.cloud.api.commands.UpdateHostCmd;1 -deleteHost=com.cloud.api.commands.DeleteHostCmd;3 -prepareHostForMaintenance=com.cloud.api.commands.PrepareForMaintenanceCmd;1 -cancelHostMaintenance=com.cloud.api.commands.CancelMaintenanceCmd;1 -listHosts=com.cloud.api.commands.ListHostsCmd;3 -addSecondaryStorage=com.cloud.api.commands.AddSecondaryStorageCmd;1 -updateHostPassword=com.cloud.api.commands.UpdateHostPasswordCmd;1 +addHost=3 +addCluster=1 +deleteCluster=1 +updateCluster=1 +reconnectHost=1 +updateHost=1 +deleteHost=3 +prepareHostForMaintenance=1 +cancelHostMaintenance=1 +listHosts=3 +addSecondaryStorage=1 +updateHostPassword=1 #### volume commands -attachVolume=com.cloud.api.commands.AttachVolumeCmd;15 -uploadVolume=com.cloud.api.commands.UploadVolumeCmd;15 -detachVolume=com.cloud.api.commands.DetachVolumeCmd;15 -createVolume=com.cloud.api.commands.CreateVolumeCmd;15 -deleteVolume=com.cloud.api.commands.DeleteVolumeCmd;15 -listVolumes=com.cloud.api.commands.ListVolumesCmd;15 -extractVolume=com.cloud.api.commands.ExtractVolumeCmd;15 -migrateVolume=com.cloud.api.commands.MigrateVolumeCmd;15 +attachVolume=15 +uploadVolume=15 +detachVolume=15 +createVolume=15 +deleteVolume=15 +listVolumes=15 +extractVolume=15 +migrateVolume=15 +resizeVolume=15 #### registration command: FIXME -- this really should be something in management server that #### generates a new key for the user and they just have to #### use that key...the key is stored in the db associated w/ #### the userId...every request to the developer API should be #### checked against the key -registerUserKeys=com.cloud.api.commands.RegisterCmd;15 +registerUserKeys=15 ### async-query command -queryAsyncJobResult=com.cloud.api.commands.QueryAsyncJobResultCmd;15 -listAsyncJobs=com.cloud.api.commands.ListAsyncJobsCmd;15 +queryAsyncJobResult=15 +listAsyncJobs=15 #### storage pools commands -listStoragePools=com.cloud.api.commands.ListStoragePoolsCmd;3 -createStoragePool=com.cloud.api.commands.CreateStoragePoolCmd;1 -updateStoragePool=com.cloud.api.commands.UpdateStoragePoolCmd;1 -deleteStoragePool=com.cloud.api.commands.DeletePoolCmd;1 -listClusters=com.cloud.api.commands.ListClustersCmd;3 -enableStorageMaintenance=com.cloud.api.commands.PreparePrimaryStorageForMaintenanceCmd;1 -cancelStorageMaintenance=com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd;1 +listStoragePools=3 +createStoragePool=1 +updateStoragePool=1 +deleteStoragePool=1 +listClusters=3 +enableStorageMaintenance=1 +cancelStorageMaintenance=1 #### security group commands -createSecurityGroup=com.cloud.api.commands.CreateSecurityGroupCmd;15 -deleteSecurityGroup=com.cloud.api.commands.DeleteSecurityGroupCmd;15 -authorizeSecurityGroupIngress=com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;15 -revokeSecurityGroupIngress=com.cloud.api.commands.RevokeSecurityGroupIngressCmd;15 -authorizeSecurityGroupEgress=com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;15 -revokeSecurityGroupEgress=com.cloud.api.commands.RevokeSecurityGroupEgressCmd;15 -listSecurityGroups=com.cloud.api.commands.ListSecurityGroupsCmd;15 +createSecurityGroup=15 +deleteSecurityGroup=15 +authorizeSecurityGroupIngress=15 +revokeSecurityGroupIngress=15 +authorizeSecurityGroupEgress=15 +revokeSecurityGroupEgress=15 +listSecurityGroups=15 #### vm group commands -createInstanceGroup=com.cloud.api.commands.CreateVMGroupCmd;15 -deleteInstanceGroup=com.cloud.api.commands.DeleteVMGroupCmd;15 -updateInstanceGroup=com.cloud.api.commands.UpdateVMGroupCmd;15 -listInstanceGroups=com.cloud.api.commands.ListVMGroupsCmd;15 +createInstanceGroup=15 +deleteInstanceGroup=15 +updateInstanceGroup=15 +listInstanceGroups=15 ### Certificate commands -uploadCustomCertificate=com.cloud.api.commands.UploadCustomCertificateCmd;1 +uploadCustomCertificate=1 ### other commands -listHypervisors=com.cloud.api.commands.ListHypervisorsCmd;15 +listHypervisors=15 ### VPN -createRemoteAccessVpn=com.cloud.api.commands.CreateRemoteAccessVpnCmd;15 -deleteRemoteAccessVpn=com.cloud.api.commands.DeleteRemoteAccessVpnCmd;15 -listRemoteAccessVpns=com.cloud.api.commands.ListRemoteAccessVpnsCmd;15 +createRemoteAccessVpn=15 +deleteRemoteAccessVpn=15 +listRemoteAccessVpns=15 -addVpnUser=com.cloud.api.commands.AddVpnUserCmd;15 -removeVpnUser=com.cloud.api.commands.RemoveVpnUserCmd;15 -listVpnUsers=com.cloud.api.commands.ListVpnUsersCmd;15 +addVpnUser=15 +removeVpnUser=15 +listVpnUsers=15 #### network offering commands -createNetworkOffering=com.cloud.api.commands.CreateNetworkOfferingCmd;1 -updateNetworkOffering=com.cloud.api.commands.UpdateNetworkOfferingCmd;1 -deleteNetworkOffering=com.cloud.api.commands.DeleteNetworkOfferingCmd;1 -listNetworkOfferings=com.cloud.api.commands.ListNetworkOfferingsCmd;15 +createNetworkOffering=1 +updateNetworkOffering=1 +deleteNetworkOffering=1 +listNetworkOfferings=15 #### network commands -createNetwork=com.cloud.api.commands.CreateNetworkCmd;15 -deleteNetwork=com.cloud.api.commands.DeleteNetworkCmd;15 -listNetworks=com.cloud.api.commands.ListNetworksCmd;15 -restartNetwork=com.cloud.api.commands.RestartNetworkCmd;15 -updateNetwork=com.cloud.api.commands.UpdateNetworkCmd;15 +createNetwork=15 +deleteNetwork=15 +listNetworks=15 +restartNetwork=15 +updateNetwork=15 #### SSH key pair commands -registerSSHKeyPair=com.cloud.api.commands.RegisterSSHKeyPairCmd;15 -createSSHKeyPair=com.cloud.api.commands.CreateSSHKeyPairCmd;15 -deleteSSHKeyPair=com.cloud.api.commands.DeleteSSHKeyPairCmd;15 -listSSHKeyPairs=com.cloud.api.commands.ListSSHKeyPairsCmd;15 +registerSSHKeyPair=15 +createSSHKeyPair=15 +deleteSSHKeyPair=15 +listSSHKeyPairs=15 #### Projects commands -createProject=com.cloud.api.commands.CreateProjectCmd;15 -deleteProject=com.cloud.api.commands.DeleteProjectCmd;15 -updateProject=com.cloud.api.commands.UpdateProjectCmd;15 -activateProject=com.cloud.api.commands.ActivateProjectCmd;15 -suspendProject=com.cloud.api.commands.SuspendProjectCmd;15 -listProjects=com.cloud.api.commands.ListProjectsCmd;15 -addAccountToProject=com.cloud.api.commands.AddAccountToProjectCmd;15 -deleteAccountFromProject=com.cloud.api.commands.DeleteAccountFromProjectCmd;15 -listProjectAccounts=com.cloud.api.commands.ListProjectAccountsCmd;15 -listProjectInvitations=com.cloud.api.commands.ListProjectInvitationsCmd;15 -updateProjectInvitation=com.cloud.api.commands.UpdateProjectInvitationCmd;15 -deleteProjectInvitation=com.cloud.api.commands.DeleteProjectInvitationCmd;15 +createProject=15 +deleteProject=15 +updateProject=15 +activateProject=15 +suspendProject=15 +listProjects=15 +addAccountToProject=15 +deleteAccountFromProject=15 +listProjectAccounts=15 +listProjectInvitations=15 +updateProjectInvitation=15 +deleteProjectInvitation=15 #### -createFirewallRule=com.cloud.api.commands.CreateFirewallRuleCmd;15 -deleteFirewallRule=com.cloud.api.commands.DeleteFirewallRuleCmd;15 -listFirewallRules=com.cloud.api.commands.ListFirewallRulesCmd;15 +createFirewallRule=15 +deleteFirewallRule=15 +listFirewallRules=15 #### hypervisor capabilities commands -updateHypervisorCapabilities=com.cloud.api.commands.UpdateHypervisorCapabilitiesCmd;1 -listHypervisorCapabilities=com.cloud.api.commands.ListHypervisorCapabilitiesCmd;1 +updateHypervisorCapabilities=1 +listHypervisorCapabilities=1 #### Physical Network commands -createPhysicalNetwork=com.cloud.api.commands.CreatePhysicalNetworkCmd;1 -deletePhysicalNetwork=com.cloud.api.commands.DeletePhysicalNetworkCmd;1 -listPhysicalNetworks=com.cloud.api.commands.ListPhysicalNetworksCmd;1 -updatePhysicalNetwork=com.cloud.api.commands.UpdatePhysicalNetworkCmd;1 +createPhysicalNetwork=1 +deletePhysicalNetwork=1 +listPhysicalNetworks=1 +updatePhysicalNetwork=1 #### Physical Network Service Provider commands -listSupportedNetworkServices=com.cloud.api.commands.ListSupportedNetworkServicesCmd;1 -addNetworkServiceProvider=com.cloud.api.commands.AddNetworkServiceProviderCmd;1 -deleteNetworkServiceProvider=com.cloud.api.commands.DeleteNetworkServiceProviderCmd;1 -listNetworkServiceProviders=com.cloud.api.commands.ListNetworkServiceProvidersCmd;1 -updateNetworkServiceProvider=com.cloud.api.commands.UpdateNetworkServiceProviderCmd;1 +listSupportedNetworkServices=1 +addNetworkServiceProvider=1 +deleteNetworkServiceProvider=1 +listNetworkServiceProviders=1 +updateNetworkServiceProvider=1 #### Physical Network Traffic Type commands -addTrafficType=com.cloud.api.commands.AddTrafficTypeCmd;1 -deleteTrafficType=com.cloud.api.commands.DeleteTrafficTypeCmd;1 -listTrafficTypes=com.cloud.api.commands.ListTrafficTypesCmd;1 -updateTrafficType=com.cloud.api.commands.UpdateTrafficTypeCmd;1 -listTrafficTypeImplementors=com.cloud.api.commands.ListTrafficTypeImplementorsCmd;1 +addTrafficType=1 +deleteTrafficType=1 +listTrafficTypes=1 +updateTrafficType=1 +listTrafficTypeImplementors=1 #### Storage Network commands -createStorageNetworkIpRange=com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;1 -deleteStorageNetworkIpRange=com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;1 -listStorageNetworkIpRange=com.cloud.api.commands.listStorageNetworkIpRangeCmd;1 -updateStorageNetworkIpRange=com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;1 +createStorageNetworkIpRange=1 +deleteStorageNetworkIpRange=1 +listStorageNetworkIpRange=1 +updateStorageNetworkIpRange=1 ### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 - -### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 +addNetworkDevice=1 +listNetworkDevice=1 +deleteNetworkDevice=1 ### VPC commands -createVPC=com.cloud.api.commands.CreateVPCCmd;15 -listVPCs=com.cloud.api.commands.ListVPCsCmd;15 -deleteVPC=com.cloud.api.commands.DeleteVPCCmd;15 -updateVPC=com.cloud.api.commands.UpdateVPCCmd;15 -restartVPC=com.cloud.api.commands.RestartVPCCmd;15 +createVPC=15 +listVPCs=15 +deleteVPC=15 +updateVPC=15 +restartVPC=15 #### VPC offering commands -createVPCOffering=com.cloud.api.commands.CreateVPCOfferingCmd;1 -updateVPCOffering=com.cloud.api.commands.UpdateVPCOfferingCmd;1 -deleteVPCOffering=com.cloud.api.commands.DeleteVPCOfferingCmd;1 -listVPCOfferings=com.cloud.api.commands.ListVPCOfferingsCmd;15 +createVPCOffering=1 +updateVPCOffering=1 +deleteVPCOffering=1 +listVPCOfferings=15 #### Private gateway commands -createPrivateGateway=com.cloud.api.commands.CreatePrivateGatewayCmd;1 -listPrivateGateways=com.cloud.api.commands.ListPrivateGatewaysCmd;15 -deletePrivateGateway=com.cloud.api.commands.DeletePrivateGatewayCmd;1 +createPrivateGateway=1 +listPrivateGateways=15 +deletePrivateGateway=1 #### Network ACL commands -createNetworkACL=com.cloud.api.commands.CreateNetworkACLCmd;15 -deleteNetworkACL=com.cloud.api.commands.DeleteNetworkACLCmd;15 -listNetworkACLs=com.cloud.api.commands.ListNetworkACLsCmd;15 +createNetworkACL=15 +deleteNetworkACL=15 +listNetworkACLs=15 #### Static route commands -createStaticRoute=com.cloud.api.commands.CreateStaticRouteCmd;15 -deleteStaticRoute=com.cloud.api.commands.DeleteStaticRouteCmd;15 -listStaticRoutes=com.cloud.api.commands.ListStaticRoutesCmd;15 +createStaticRoute=15 +deleteStaticRoute=15 +listStaticRoutes=15 #### Tags commands -createTags=com.cloud.api.commands.CreateTagsCmd;15 -deleteTags=com.cloud.api.commands.DeleteTagsCmd;15 -listTags=com.cloud.api.commands.ListTagsCmd;15 +createTags=15 +deleteTags=15 +listTags=15 ### Site-to-site VPN commands -createVpnCustomerGateway=com.cloud.api.commands.CreateVpnCustomerGatewayCmd;15 -createVpnGateway=com.cloud.api.commands.CreateVpnGatewayCmd;15 -createVpnConnection=com.cloud.api.commands.CreateVpnConnectionCmd;15 -deleteVpnCustomerGateway=com.cloud.api.commands.DeleteVpnCustomerGatewayCmd;15 -deleteVpnGateway=com.cloud.api.commands.DeleteVpnGatewayCmd;15 -deleteVpnConnection=com.cloud.api.commands.DeleteVpnConnectionCmd;15 -updateVpnCustomerGateway=com.cloud.api.commands.UpdateVpnCustomerGatewayCmd;15 -resetVpnConnection=com.cloud.api.commands.ResetVpnConnectionCmd;15 -listVpnCustomerGateways=com.cloud.api.commands.ListVpnCustomerGatewaysCmd;15 -listVpnGateways=com.cloud.api.commands.ListVpnGatewaysCmd;15 -listVpnConnections=com.cloud.api.commands.ListVpnConnectionsCmd;15 +createVpnCustomerGateway=15 +createVpnGateway=15 +createVpnConnection=15 +deleteVpnCustomerGateway=15 +deleteVpnGateway=15 +deleteVpnConnection=15 +updateVpnCustomerGateway=15 +resetVpnConnection=15 +listVpnCustomerGateways=15 +listVpnGateways=15 +listVpnConnections=15 + +#### router commands +createVirtualRouterElement=7 +configureVirtualRouterElement=7 +listVirtualRouterElements=7 + +#### usage commands +generateUsageRecords=1 +listUsageRecords=1 +listUsageTypes=1 + +#### traffic monitor commands +addTrafficMonitor=1 +deleteTrafficMonitor=1 +listTrafficMonitors=1 + +#### Cisco Nexus 1000v Virtual Supervisor Module (VSM) commands +deleteCiscoNexusVSM=1 +enableCiscoNexusVSM=1 +disableCiscoNexusVSM=1 +listCiscoNexusVSMs=1 + +#### f5 big ip load balancer commands + +#Deprecated commands +addExternalLoadBalancer=1 +deleteExternalLoadBalancer=1 +listExternalLoadBalancers=1 + +addF5LoadBalancer=1 +configureF5LoadBalancer=1 +deleteF5LoadBalancer=1 +listF5LoadBalancers=1 +listF5LoadBalancerNetworks=1 + +#### juniper srx firewall commands +addExternalFirewall=1 +deleteExternalFirewall=1 +listExternalFirewalls=1 + +addSrxFirewall=1 +deleteSrxFirewall=1 +configureSrxFirewall=1 +listSrxFirewalls=1 +listSrxFirewallNetworks=1 + +####Netapp integration commands +createVolumeOnFiler=15 +destroyVolumeOnFiler=15 +listVolumesOnFiler=15 +createLunOnFiler=15 +destroyLunOnFiler=15 +listLunsOnFiler=15 +associateLun=15 +dissociateLun=15 +createPool=15 +deletePool=15 +modifyPool=15 +listPools=15 + +#### netscaler load balancer commands +addNetscalerLoadBalancer=1 +deleteNetscalerLoadBalancer=1 +configureNetscalerLoadBalancer=1 +listNetscalerLoadBalancers=1 +listNetscalerLoadBalancerNetworks=1 + +#### nicira nvp commands + +addNiciraNvpDevice=1 +deleteNiciraNvpDevice=1 +listNiciraNvpDevices=1 +listNiciraNvpDeviceNetworks=1 + +# Not implemented (yet) +#configureNiciraNvpDevice=1 + +#### host simulator commands + +configureSimulator=1 + +#### api discovery commands + +listApis=15 diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index f678f5d655a..958757a3563 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -53,6 +53,9 @@ under the License. true + + + @@ -147,7 +150,7 @@ under the License. - + @@ -227,6 +230,7 @@ under the License. + diff --git a/client/tomcatconf/f5bigip_commands.properties.in b/client/tomcatconf/f5bigip_commands.properties.in deleted file mode 100644 index e48bd482d20..00000000000 --- a/client/tomcatconf/f5bigip_commands.properties.in +++ /dev/null @@ -1,32 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### f5 big ip load balancer commands - -#Deprecated commands -addExternalLoadBalancer = com.cloud.api.commands.AddExternalLoadBalancerCmd;1 -deleteExternalLoadBalancer = com.cloud.api.commands.DeleteExternalLoadBalancerCmd;1 -listExternalLoadBalancers = com.cloud.api.commands.ListExternalLoadBalancersCmd;1 - -addF5LoadBalancer = com.cloud.api.commands.AddF5LoadBalancerCmd;1 -configureF5LoadBalancer = com.cloud.api.commands.ConfigureF5LoadBalancerCmd;1 -deleteF5LoadBalancer = com.cloud.api.commands.DeleteF5LoadBalancerCmd;1 -listF5LoadBalancers = com.cloud.api.commands.ListF5LoadBalancersCmd;1 -listF5LoadBalancerNetworks = com.cloud.api.commands.ListF5LoadBalancerNetworksCmd;1 diff --git a/client/tomcatconf/junipersrx_commands.properties.in b/client/tomcatconf/junipersrx_commands.properties.in deleted file mode 100644 index 57fd0893ce0..00000000000 --- a/client/tomcatconf/junipersrx_commands.properties.in +++ /dev/null @@ -1,30 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### juniper srx firewall commands -addExternalFirewall = com.cloud.api.commands.AddExternalFirewallCmd;1 -deleteExternalFirewall = com.cloud.api.commands.DeleteExternalFirewallCmd;1 -listExternalFirewalls = com.cloud.api.commands.ListExternalFirewallsCmd;1 - -addSrxFirewall = com.cloud.api.commands.AddSrxFirewallCmd;1 -deleteSrxFirewall = com.cloud.api.commands.DeleteSrxFirewallCmd;1 -configureSrxFirewall = com.cloud.api.commands.ConfigureSrxFirewallCmd;1 -listSrxFirewalls = com.cloud.api.commands.ListSrxFirewallsCmd;1 -listSrxFirewallNetworks = com.cloud.api.commands.ListSrxFirewallNetworksCmd;1 diff --git a/client/tomcatconf/log4j-cloud.xml.in b/client/tomcatconf/log4j-cloud.xml.in index 6c7f29d0162..02f70998d53 100755 --- a/client/tomcatconf/log4j-cloud.xml.in +++ b/client/tomcatconf/log4j-cloud.xml.in @@ -104,6 +104,10 @@ under the License. + + + + diff --git a/client/tomcatconf/netapp_commands.properties.in b/client/tomcatconf/netapp_commands.properties.in deleted file mode 100644 index 21844035592..00000000000 --- a/client/tomcatconf/netapp_commands.properties.in +++ /dev/null @@ -1,33 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -####Netapp integration commands -createVolumeOnFiler=com.cloud.api.commands.netapp.CreateVolumeOnFilerCmd;15 -destroyVolumeOnFiler=com.cloud.api.commands.netapp.DestroyVolumeOnFilerCmd;15 -listVolumesOnFiler=com.cloud.api.commands.netapp.ListVolumesOnFilerCmd;15 -createLunOnFiler=com.cloud.api.commands.netapp.CreateLunCmd;15 -destroyLunOnFiler=com.cloud.api.commands.netapp.DestroyLunCmd;15 -listLunsOnFiler=com.cloud.api.commands.netapp.ListLunsCmd;15 -associateLun=com.cloud.api.commands.netapp.AssociateLunCmd;15 -dissociateLun=com.cloud.api.commands.netapp.DissociateLunCmd;15 -createPool=com.cloud.api.commands.netapp.CreateVolumePoolCmd;15 -deletePool=com.cloud.api.commands.netapp.DeleteVolumePoolCmd;15 -modifyPool=com.cloud.api.commands.netapp.ModifyVolumePoolCmd;15 -listPools=com.cloud.api.commands.netapp.ListVolumePoolsCmd;15 diff --git a/client/tomcatconf/netscalerloadbalancer_commands.properties.in b/client/tomcatconf/netscalerloadbalancer_commands.properties.in deleted file mode 100644 index 114e7d37cca..00000000000 --- a/client/tomcatconf/netscalerloadbalancer_commands.properties.in +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -### bitmap of permissions at the end of each classname, 1 = ADMIN, 2 = RESOURCE_DOMAIN_ADMIN, 4 = DOMAIN_ADMIN, 8 = USER -### Please standardize naming conventions to camel-case (even for acronyms). - -#### netscaler load balancer commands -addNetscalerLoadBalancer = com.cloud.api.commands.AddNetscalerLoadBalancerCmd;1 -deleteNetscalerLoadBalancer = com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd;1 -configureNetscalerLoadBalancer = com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;1 -listNetscalerLoadBalancers = com.cloud.api.commands.ListNetscalerLoadBalancersCmd;1 -listNetscalerLoadBalancerNetworks = com.cloud.api.commands.ListNetscalerLoadBalancerNetworksCmd;1 diff --git a/client/tomcatconf/server-nonssl.xml.in b/client/tomcatconf/server-nonssl.xml.in index 607b0b3b8d6..847197cbae0 100755 --- a/client/tomcatconf/server-nonssl.xml.in +++ b/client/tomcatconf/server-nonssl.xml.in @@ -68,7 +68,7 @@ redirectPort="8443" /> --> - - --> - - newTags) { if (newTags.isEmpty()) { setTags(null); return; } - + StringBuilder buf = new StringBuilder(); for (String tag : newTags) { buf.append(tag).append(","); } - + buf.delete(buf.length() - 1, buf.length()); - + setTags(buf.toString()); } @@ -293,12 +294,12 @@ public class DiskOfferingVO implements DiskOffering, Identity { public void setRemoved(Date removed) { this.removed = removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -306,7 +307,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { public void setSortKey(int key) { sortKey = key; } - + public int getSortKey() { return sortKey; } diff --git a/core/src/com/cloud/storage/GuestOSCategoryVO.java b/core/src/com/cloud/storage/GuestOSCategoryVO.java index cbe242eef5d..03a74793001 100644 --- a/core/src/com/cloud/storage/GuestOSCategoryVO.java +++ b/core/src/com/cloud/storage/GuestOSCategoryVO.java @@ -25,32 +25,33 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="guest_os_category") -public class GuestOSCategoryVO implements GuestOsCategory, Identity { +public class GuestOSCategoryVO implements GuestOsCategory { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="name") String name; - + @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Override public long getId() { return id; } - + @Override public String getName() { - return name; + return name; } - + @Override public void setName(String name) { this.name = name; @@ -60,7 +61,7 @@ public class GuestOSCategoryVO implements GuestOsCategory, Identity { public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/GuestOSVO.java b/core/src/com/cloud/storage/GuestOSVO.java index 85db94e29f6..49e136d03c1 100644 --- a/core/src/com/cloud/storage/GuestOSVO.java +++ b/core/src/com/cloud/storage/GuestOSVO.java @@ -25,64 +25,65 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="guest_os") -public class GuestOSVO implements GuestOS, Identity { +public class GuestOSVO implements GuestOS { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="category_id") private long categoryId; - + @Column(name="name") String name; - + @Column(name="display_name") String displayName; - + @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Override public long getId() { return id; } - + public long getCategoryId() { return categoryId; } - + public void setCategoryId(long categoryId) { this.categoryId = categoryId; } - + @Override public String getName() { - return name; + return name; } - + public void setName(String name) { this.name = name; } - + @Override public String getDisplayName() { return displayName; } - + public void setDisplayName(String displayName) { this.displayName = displayName; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/LaunchPermissionVO.java b/core/src/com/cloud/storage/LaunchPermissionVO.java index 8bfe09d3719..992bac2365e 100644 --- a/core/src/com/cloud/storage/LaunchPermissionVO.java +++ b/core/src/com/cloud/storage/LaunchPermissionVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -23,7 +25,7 @@ import javax.persistence.Table; @Entity @Table(name="launch_permission") -public class LaunchPermissionVO { +public class LaunchPermissionVO implements InternalIdentity { @Id @Column(name="id") private Long id; @@ -41,7 +43,7 @@ public class LaunchPermissionVO { this.accountId = accountId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/S3VO.java b/core/src/com/cloud/storage/S3VO.java index 89f233b87fe..ec49bc92d74 100644 --- a/core/src/com/cloud/storage/S3VO.java +++ b/core/src/com/cloud/storage/S3VO.java @@ -19,8 +19,9 @@ package com.cloud.storage; import com.cloud.agent.api.to.S3TO; -import com.cloud.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; import javax.persistence.Column; import javax.persistence.Entity; @@ -32,7 +33,7 @@ import java.util.Date; @Entity @Table(name = "s3") -public class S3VO implements S3, Identity { +public class S3VO implements S3 { public static final String ID_COLUMN_NAME = "id"; diff --git a/core/src/com/cloud/storage/SnapshotPolicyVO.java b/core/src/com/cloud/storage/SnapshotPolicyVO.java index d059fcbc6da..4eb4916afd3 100644 --- a/core/src/com/cloud/storage/SnapshotPolicyVO.java +++ b/core/src/com/cloud/storage/SnapshotPolicyVO.java @@ -25,19 +25,20 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.utils.DateUtil.IntervalType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshot_policy") -public class SnapshotPolicyVO implements SnapshotPolicy, Identity { - +public class SnapshotPolicyVO implements SnapshotPolicy { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="volume_id") long volumeId; @@ -46,20 +47,20 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { @Column(name="timezone") String timezone; - + @Column(name="interval") private short interval; - + @Column(name="max_snaps") private int maxSnaps; - + @Column(name="active") boolean active = false; @Column(name="uuid") String uuid; - - public SnapshotPolicyVO() { + + public SnapshotPolicyVO() { this.uuid = UUID.randomUUID().toString(); } @@ -76,7 +77,7 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public long getId() { return id; } - + public long getVolumeId() { return volumeId; } @@ -88,7 +89,7 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public String getSchedule() { return schedule; } - + public void setInterval(short interval) { this.interval = interval; } @@ -96,11 +97,11 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public void setTimezone(String timezone) { this.timezone = timezone; } - + public String getTimezone() { return timezone; } - + public short getInterval() { return interval; } @@ -120,12 +121,12 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public void setActive(boolean active) { this.active = active; } - + @Override public String getUuid() { return this.uuid; } - + 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 80216e48a55..75757c6b22b 100644 --- a/core/src/com/cloud/storage/SnapshotScheduleVO.java +++ b/core/src/com/cloud/storage/SnapshotScheduleVO.java @@ -28,18 +28,19 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotSchedule; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshot_schedule") -public class SnapshotScheduleVO implements SnapshotSchedule, Identity { +public class SnapshotScheduleVO implements SnapshotSchedule { @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; @@ -50,16 +51,16 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { @Column(name="scheduled_timestamp") @Temporal(value=TemporalType.TIMESTAMP) Date scheduledTimestamp; - + @Column(name="async_job_id") Long asyncJobId; - + @Column(name="snapshot_id") Long snapshotId; @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + public SnapshotScheduleVO() { } public SnapshotScheduleVO(long volumeId, long policyId, Date scheduledTimestamp) { @@ -69,15 +70,15 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { this.snapshotId = null; this.asyncJobId = null; } - + public long getId() { return id; } - + public Long getVolumeId() { return volumeId; } - + public Long getPolicyId() { return policyId; } @@ -92,7 +93,7 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { public Date getScheduledTimestamp() { return scheduledTimestamp; } - + public void setScheduledTimestamp(Date scheduledTimestamp) { this.scheduledTimestamp = scheduledTimestamp; } @@ -100,24 +101,24 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { public Long getAsyncJobId() { return asyncJobId; } - + public void setAsyncJobId(Long asyncJobId) { this.asyncJobId = asyncJobId; } - + public Long getSnapshotId() { return snapshotId; } - + public void setSnapshotId(Long snapshotId) { this.snapshotId = snapshotId; } - + @Override public String getUuid() { return this.uuid; } - + 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 ae4fd6aafef..e5e36504ea6 100644 --- a/core/src/com/cloud/storage/SnapshotVO.java +++ b/core/src/com/cloud/storage/SnapshotVO.java @@ -28,32 +28,33 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshots") -public class SnapshotVO implements Snapshot, Identity { - +public class SnapshotVO implements Snapshot { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id = -1; - + @Column(name="data_center_id") long dataCenterId; @Column(name="account_id") long accountId; - + @Column(name="domain_id") long domainId; @Column(name="volume_id") Long volumeId; - + @Column(name="disk_offering_id") Long diskOfferingId; @@ -64,7 +65,7 @@ public class SnapshotVO implements Snapshot, Identity { @Expose @Column(name="name") String name; - + @Expose @Column(name="status", updatable = true, nullable=false) @Enumerated(value=EnumType.STRING) @@ -75,10 +76,10 @@ public class SnapshotVO implements Snapshot, Identity { @Column(name="type_description") String typeDescription; - + @Column(name="size") long size; - + @Column(name=GenericDao.CREATED_COLUMN) Date created; @@ -87,10 +88,10 @@ public class SnapshotVO implements Snapshot, Identity { @Column(name="backup_snap_id") String backupSnapshotId; - + @Column(name="swift_id") Long swiftId; - + @Column(name="s3_id") Long s3Id; @@ -103,14 +104,14 @@ public class SnapshotVO implements Snapshot, Identity { @Column(name="hypervisor_type") @Enumerated(value=EnumType.STRING) HypervisorType hypervisorType; - + @Expose @Column(name="version") String version; - + @Column(name="uuid") String uuid; - + public SnapshotVO() { this.uuid = UUID.randomUUID().toString(); } @@ -132,9 +133,9 @@ public class SnapshotVO implements Snapshot, Identity { this.version = "2.2"; this.uuid = UUID.randomUUID().toString(); } - + @Override - public Long getId() { + public long getId() { return id; } @@ -168,7 +169,7 @@ public class SnapshotVO implements Snapshot, Identity { public String getPath() { return path; } - + public void setPath(String path) { this.path = path; } @@ -181,7 +182,7 @@ public class SnapshotVO implements Snapshot, Identity { public short getsnapshotType() { return snapshotType; } - + @Override public Type getType() { if (snapshotType < 0 || snapshotType >= Type.values().length) { @@ -189,7 +190,7 @@ public class SnapshotVO implements Snapshot, Identity { } return Type.values()[snapshotType]; } - + public Long getSwiftId() { return swiftId; } @@ -210,11 +211,11 @@ public class SnapshotVO implements Snapshot, Identity { public HypervisorType getHypervisorType() { return hypervisorType; } - + public void setSnapshotType(short snapshotType) { this.snapshotType = snapshotType; } - + @Override public boolean isRecursive(){ if ( snapshotType >= Type.HOURLY.ordinal() && snapshotType <= Type.MONTHLY.ordinal() ) { @@ -249,32 +250,32 @@ public class SnapshotVO implements Snapshot, Identity { 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) { for ( Type type : Type.values()) { if ( type.equals(snapshotType)) { @@ -283,12 +284,12 @@ public class SnapshotVO implements Snapshot, Identity { } return null; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/StoragePoolDetailVO.java b/core/src/com/cloud/storage/StoragePoolDetailVO.java index 2e1af7b6dab..48487e566ac 100644 --- a/core/src/com/cloud/storage/StoragePoolDetailVO.java +++ b/core/src/com/cloud/storage/StoragePoolDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="storage_pool_details") -public class StoragePoolDetailVO { +public class StoragePoolDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/storage/StoragePoolHostAssoc.java b/core/src/com/cloud/storage/StoragePoolHostAssoc.java index 3e0d8daa149..34326d963a6 100644 --- a/core/src/com/cloud/storage/StoragePoolHostAssoc.java +++ b/core/src/com/cloud/storage/StoragePoolHostAssoc.java @@ -16,9 +16,11 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface StoragePoolHostAssoc { +public interface StoragePoolHostAssoc extends InternalIdentity { long getHostId(); diff --git a/core/src/com/cloud/storage/StoragePoolHostVO.java b/core/src/com/cloud/storage/StoragePoolHostVO.java index 41c7ce853e6..a8a2bac4886 100644 --- a/core/src/com/cloud/storage/StoragePoolHostVO.java +++ b/core/src/com/cloud/storage/StoragePoolHostVO.java @@ -28,6 +28,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage pools and hosts @@ -75,7 +76,7 @@ public class StoragePoolHostVO implements StoragePoolHostAssoc { } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/StoragePoolVO.java b/core/src/com/cloud/storage/StoragePoolVO.java index 5fecefb756d..cb5209f3e63 100644 --- a/core/src/com/cloud/storage/StoragePoolVO.java +++ b/core/src/com/cloud/storage/StoragePoolVO.java @@ -30,13 +30,14 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="storage_pool") -public class StoragePoolVO implements StoragePool, Identity { +public class StoragePoolVO implements StoragePool { @Id @TableGenerator(name="storage_pool_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="storage_pool_seq", allocationSize=1) @Column(name="id", updatable=false, nullable = false) diff --git a/core/src/com/cloud/storage/StoragePoolWorkVO.java b/core/src/com/cloud/storage/StoragePoolWorkVO.java index c5101eabb85..440065da66b 100644 --- a/core/src/com/cloud/storage/StoragePoolWorkVO.java +++ b/core/src/com/cloud/storage/StoragePoolWorkVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; @@ -26,9 +28,9 @@ import javax.persistence.Table; @Entity @Table(name="storage_pool_work") -public class StoragePoolWorkVO { +public class StoragePoolWorkVO implements InternalIdentity { - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/SwiftVO.java b/core/src/com/cloud/storage/SwiftVO.java index 7e07629e72b..c99f0efc702 100644 --- a/core/src/com/cloud/storage/SwiftVO.java +++ b/core/src/com/cloud/storage/SwiftVO.java @@ -27,24 +27,25 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="swift") -public class SwiftVO implements Swift, Identity { - +public class SwiftVO implements Swift, InternalIdentity { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="url") String url; @Column(name="account") String account; - + @Column(name="username") String userName; @@ -53,10 +54,10 @@ public class SwiftVO implements Swift, Identity { @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Column(name = GenericDao.CREATED_COLUMN) private Date created; - + public SwiftVO() { } public SwiftVO(String url, String account, String userName, String key) { @@ -95,12 +96,12 @@ public class SwiftVO implements Swift, Identity { public SwiftTO toSwiftTO() { return new SwiftTO(getId(), getUrl(), getAccount(), getUserName(), getKey()); } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/UploadVO.java b/core/src/com/cloud/storage/UploadVO.java index b39553e8638..d761bf17e3b 100755 --- a/core/src/com/cloud/storage/UploadVO.java +++ b/core/src/com/cloud/storage/UploadVO.java @@ -17,6 +17,7 @@ package com.cloud.storage; import java.util.Date; +import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; @@ -31,6 +32,7 @@ import javax.persistence.TemporalType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="upload") @@ -38,47 +40,50 @@ public class UploadVO implements Upload { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; - + + @Column(name="uuid") + private String uuid; + @Column(name="host_id") private long hostId; - + @Column(name="type_id") private long typeId; - + @Column(name=GenericDaoBase.CREATED_COLUMN) private Date created = null; - + @Column(name="last_updated") @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; - + private Date lastUpdated = null; + @Column (name="upload_pct") - private int uploadPercent; - + private int uploadPercent; + @Column (name="type") @Enumerated(EnumType.STRING) private Type type; - + @Column (name="mode") @Enumerated(EnumType.STRING) private Mode mode = Mode.FTP_UPLOAD; - + @Column (name="upload_state") @Enumerated(EnumType.STRING) private Status uploadState; - + @Column (name="error_str") private String errorString; @Column (name="job_id") private String jobId; - + @Column (name="url") private String uploadUrl; @Column (name="install_path") private String installPath; - + @Override public long getHostId() { return hostId; @@ -93,7 +98,12 @@ public class UploadVO implements Upload { return id; } - @Override + + public String getUuid() { + return uuid; + } + + @Override public Date getCreated() { return created; } @@ -102,7 +112,7 @@ public class UploadVO implements Upload { public Date getLastUpdated() { return lastUpdated; } - + public void setLastUpdated(Date date) { lastUpdated = date; } @@ -111,6 +121,7 @@ public class UploadVO implements Upload { super(); this.hostId = hostId; this.typeId = templateId; + this.uuid = UUID.randomUUID().toString(); } public UploadVO(long hostId, long typeId, Date lastUpdated, @@ -124,8 +135,9 @@ public class UploadVO implements Upload { this.mode = mode; this.type = type; this.uploadUrl = uploadUrl; + this.uuid = UUID.randomUUID().toString(); } - + public UploadVO(long hostId, long typeId, Date lastUpdated, Status uploadState, int uploadPercent, Type type, Mode mode) { @@ -137,9 +149,11 @@ public class UploadVO implements Upload { this.uploadPercent = uploadPercent; this.type = type; this.mode = mode; + this.uuid = UUID.randomUUID().toString(); + } - protected UploadVO() { + protected UploadVO() { } public UploadVO(Long uploadId) { @@ -219,7 +233,7 @@ public class UploadVO implements Upload { return mode; } - public void setMode(Mode mode) { + public void setMode(Mode mode) { this.mode = mode; } diff --git a/core/src/com/cloud/storage/VMTemplateDetailVO.java b/core/src/com/cloud/storage/VMTemplateDetailVO.java index e3f7487460f..c007802db3f 100644 --- a/core/src/com/cloud/storage/VMTemplateDetailVO.java +++ b/core/src/com/cloud/storage/VMTemplateDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="vm_template_details") -public class VMTemplateDetailVO { +public class VMTemplateDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/storage/VMTemplateHostVO.java b/core/src/com/cloud/storage/VMTemplateHostVO.java index 9c85dd2cc6c..9eae1a00303 100755 --- a/core/src/com/cloud/storage/VMTemplateHostVO.java +++ b/core/src/com/cloud/storage/VMTemplateHostVO.java @@ -30,6 +30,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage hosts and templates diff --git a/core/src/com/cloud/storage/VMTemplateS3VO.java b/core/src/com/cloud/storage/VMTemplateS3VO.java index a75c37d192d..02f3ff5cf7f 100644 --- a/core/src/com/cloud/storage/VMTemplateS3VO.java +++ b/core/src/com/cloud/storage/VMTemplateS3VO.java @@ -19,6 +19,7 @@ package com.cloud.storage; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; import javax.persistence.Column; import javax.persistence.Entity; @@ -32,7 +33,7 @@ import java.util.Date; @Entity @Table(name = "template_s3_ref") -public class VMTemplateS3VO { +public class VMTemplateS3VO implements InternalIdentity { public static final String S3_ID_COLUMN_NAME = "s3_id"; diff --git a/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java index f497c099f2b..32c9dd2ece5 100644 --- a/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java +++ b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java @@ -30,6 +30,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage pools and templates @@ -37,7 +38,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name="template_spool_ref") -public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc{ +public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; diff --git a/core/src/com/cloud/storage/VMTemplateSwiftVO.java b/core/src/com/cloud/storage/VMTemplateSwiftVO.java index a009e237943..6c7a73d3c05 100755 --- a/core/src/com/cloud/storage/VMTemplateSwiftVO.java +++ b/core/src/com/cloud/storage/VMTemplateSwiftVO.java @@ -26,6 +26,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for swift and templates @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name = "template_swift_ref") -public class VMTemplateSwiftVO { +public class VMTemplateSwiftVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; diff --git a/core/src/com/cloud/storage/VMTemplateVO.java b/core/src/com/cloud/storage/VMTemplateVO.java index cd17bc9bf5a..fcfdd0067e1 100755 --- a/core/src/com/cloud/storage/VMTemplateVO.java +++ b/core/src/com/cloud/storage/VMTemplateVO.java @@ -31,16 +31,17 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; import com.cloud.template.VirtualMachineTemplate; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vm_template") -public class VMTemplateVO implements VirtualMachineTemplate, Identity { +public class VMTemplateVO implements VirtualMachineTemplate { @Id @TableGenerator(name="vm_template_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_template_seq", allocationSize=1) @Column(name="id", nullable = false) @@ -85,7 +86,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { private long accountId; @Column(name="checksum") - private String checksum; + private String checksum; @Column(name="display_text", length=4096) private String displayText; @@ -117,16 +118,16 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { @Column(name="template_tag") private String templateTag; - + @Column(name="uuid") private String uuid; - + @Column(name="sort_key") private int sortKey; - + @Column(name="enable_sshkey") private boolean enableSshKey; - + @Transient Map details; @@ -156,7 +157,7 @@ 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; @@ -391,30 +392,30 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { @Override public String getTemplateTag() { return templateTag; - } + } public void setTemplateTag(String templateTag) { this.templateTag = templateTag; - } + } @Override public long getDomainId() { return -1; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public Map getDetails() { return this.details; } - + public void setDetails(Map details) { this.details = details; } @@ -429,7 +430,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { } VMTemplateVO other = (VMTemplateVO)that; - return ((this.getUniqueName().equals(other.getUniqueName()))); + return ((this.getUniqueName().equals(other.getUniqueName()))); } @Override @@ -450,11 +451,11 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public void setRemoved(Date removed) { this.removed = removed; } - + public void setSortKey(int key) { sortKey = key; } - + public int getSortKey() { return sortKey; } @@ -463,7 +464,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public boolean getEnableSshKey() { return enableSshKey; } - + public void setEnableSshKey(boolean enable) { enableSshKey = enable; } diff --git a/core/src/com/cloud/storage/VMTemplateZoneVO.java b/core/src/com/cloud/storage/VMTemplateZoneVO.java index e7169b8cdae..93a67b565d4 100644 --- a/core/src/com/cloud/storage/VMTemplateZoneVO.java +++ b/core/src/com/cloud/storage/VMTemplateZoneVO.java @@ -29,10 +29,11 @@ import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="template_zone_ref") -public class VMTemplateZoneVO { +public class VMTemplateZoneVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id; @@ -64,7 +65,7 @@ public class VMTemplateZoneVO { this.lastUpdated = lastUpdated; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/VolumeHostVO.java b/core/src/com/cloud/storage/VolumeHostVO.java index d3d88ae27a8..f4fc7abc4ee 100755 --- a/core/src/com/cloud/storage/VolumeHostVO.java +++ b/core/src/com/cloud/storage/VolumeHostVO.java @@ -33,6 +33,7 @@ import javax.persistence.TemporalType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage hosts and volumes @@ -40,7 +41,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name="volume_host_ref") -public class VolumeHostVO { +public class VolumeHostVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id; diff --git a/core/src/com/cloud/storage/VolumeVO.java b/core/src/com/cloud/storage/VolumeVO.java index ef0fedaf651..aac82df80ce 100755 --- a/core/src/com/cloud/storage/VolumeVO.java +++ b/core/src/com/cloud/storage/VolumeVO.java @@ -31,14 +31,15 @@ import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "volumes") -public class VolumeVO implements Volume, Identity { +public class VolumeVO implements Volume { @Id @TableGenerator(name = "volume_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "volume_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE) diff --git a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java index d8fdc3a71d6..a4bea9df2b4 100755 --- a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java +++ b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java @@ -93,7 +93,6 @@ import com.cloud.agent.api.storage.UploadCommand; import com.cloud.agent.api.storage.ssCommand; import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.DeleteVolumeCmd; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host; import com.cloud.host.Host.Type; diff --git a/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java b/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java index f5f810a9be1..6f3d2ce5468 100644 --- a/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java +++ b/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java @@ -16,13 +16,15 @@ // under the License. package com.cloud.storage.snapshot; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface SnapshotSchedule { - long getId(); - +public interface SnapshotSchedule extends InternalIdentity, Identity { + Long getVolumeId(); - + Long getPolicyId(); void setPolicyId(long policyId); @@ -31,14 +33,14 @@ public interface SnapshotSchedule { * @return the scheduledTimestamp */ Date getScheduledTimestamp(); - + void setScheduledTimestamp(Date scheduledTimestamp); Long getAsyncJobId(); - + void setAsyncJobId(Long asyncJobId); - + Long getSnapshotId(); - + void setSnapshotId(Long snapshotId); } diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index b0418de5867..922c8b99eb5 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account") -public class AccountVO implements Account, Identity { +public class AccountVO implements Account { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -54,28 +55,28 @@ public class AccountVO implements Account, Identity { @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + @Column(name="cleanup_needed") private boolean needsCleanup = false; - + @Column(name="network_domain") private String networkDomain; @Column(name="uuid") private String uuid; - + @Column(name="default_zone_id") private Long defaultZoneId = null; public AccountVO() { this.uuid = UUID.randomUUID().toString(); } - + public AccountVO(long id) { this.id = id; this.uuid = UUID.randomUUID().toString(); } - + public AccountVO(String accountName, long domainId, String networkDomain, short type) { this.accountName = accountName; this.domainId = domainId; @@ -84,11 +85,11 @@ public class AccountVO implements Account, Identity { this.state = State.enabled; this.uuid = UUID.randomUUID().toString(); } - + public void setNeedsCleanup(boolean value) { needsCleanup = value; } - + public boolean getNeedsCleanup() { return needsCleanup; } @@ -102,16 +103,16 @@ public class AccountVO implements Account, Identity { 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; } @@ -120,16 +121,16 @@ public class AccountVO implements Account, Identity { public long getDomainId() { return domainId; } - + public void setDomainId(long domainId) { this.domainId = domainId; } - + @Override public Long getDefaultZoneId() { return defaultZoneId; } - + public void setDefaultZoneId(Long defaultZoneId) { this.defaultZoneId = defaultZoneId; } @@ -138,7 +139,7 @@ public class AccountVO implements Account, Identity { public State getState() { return state; } - + public void setState(State state) { this.state = state; } @@ -147,31 +148,31 @@ public class AccountVO implements Account, Identity { public Date getRemoved() { return removed; } - + @Override public long getAccountId() { return id; } - + @Override public String toString() { return new StringBuilder("Acct[").append(id).append("-").append(accountName).append("]").toString(); } - + @Override public String getNetworkDomain() { return networkDomain; } - + public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/user/SSHKeyPairVO.java b/core/src/com/cloud/user/SSHKeyPairVO.java index 0e13dc54c00..ab7eb8ea0b5 100644 --- a/core/src/com/cloud/user/SSHKeyPairVO.java +++ b/core/src/com/cloud/user/SSHKeyPairVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/core/src/com/cloud/user/UserAccountVO.java b/core/src/com/cloud/user/UserAccountVO.java index 1236061475b..cfad6171e55 100644 --- a/core/src/com/cloud/user/UserAccountVO.java +++ b/core/src/com/cloud/user/UserAccountVO.java @@ -29,12 +29,13 @@ import javax.persistence.Table; import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="user") @SecondaryTable(name="account", pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) -public class UserAccountVO implements UserAccount { +public class UserAccountVO implements UserAccount, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -101,7 +102,7 @@ public class UserAccountVO implements UserAccount { public UserAccountVO() {} @Override - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/user/UserStatisticsVO.java b/core/src/com/cloud/user/UserStatisticsVO.java index d560c3e6dad..eb59a74f8aa 100644 --- a/core/src/com/cloud/user/UserStatisticsVO.java +++ b/core/src/com/cloud/user/UserStatisticsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="user_statistics") -public class UserStatisticsVO { +public class UserStatisticsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -88,7 +90,7 @@ public class UserStatisticsVO { return accountId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/user/UserVO.java b/core/src/com/cloud/user/UserVO.java index f5fd5da8f96..919f4134e06 100644 --- a/core/src/com/cloud/user/UserVO.java +++ b/core/src/com/cloud/user/UserVO.java @@ -28,10 +28,11 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.user.Account.State; import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * A bean representing a user @@ -39,7 +40,7 @@ import com.cloud.utils.db.GenericDao; */ @Entity @Table(name = "user") -public class UserVO implements User, Identity { +public class UserVO implements User, Identity, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/core/src/com/cloud/vm/InstanceGroupVMMapVO.java b/core/src/com/cloud/vm/InstanceGroupVMMapVO.java index 09cfd9c6070..996655da57e 100644 --- a/core/src/com/cloud/vm/InstanceGroupVMMapVO.java +++ b/core/src/com/cloud/vm/InstanceGroupVMMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.vm; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,7 +36,7 @@ import javax.persistence.Table; @SecondaryTable(name="instance_group", pkJoinColumns={@PrimaryKeyJoinColumn(name="group_id", referencedColumnName="id")}) }) -public class InstanceGroupVMMapVO { +public class InstanceGroupVMMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -54,7 +56,7 @@ public class InstanceGroupVMMapVO { this.instanceId = instanceId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/vm/InstanceGroupVO.java b/core/src/com/cloud/vm/InstanceGroupVO.java index da1efa897da..ad66b5a4b2c 100644 --- a/core/src/com/cloud/vm/InstanceGroupVO.java +++ b/core/src/com/cloud/vm/InstanceGroupVO.java @@ -28,14 +28,15 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="instance_group") @SecondaryTable(name="account", pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) -public class InstanceGroupVO implements InstanceGroup, Identity { +public class InstanceGroupVO implements InstanceGroup { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/vm/UserVmDetailVO.java b/core/src/com/cloud/vm/UserVmDetailVO.java index bf2f32351a1..245b577bc39 100644 --- a/core/src/com/cloud/vm/UserVmDetailVO.java +++ b/core/src/com/cloud/vm/UserVmDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.vm; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="user_vm_details") -public class UserVmDetailVO { +public class UserVmDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/vm/VMInstanceVO.java b/core/src/com/cloud/vm/VMInstanceVO.java index 8cb5816724d..13c1cf35902 100644 --- a/core/src/com/cloud/vm/VMInstanceVO.java +++ b/core/src/com/cloud/vm/VMInstanceVO.java @@ -42,6 +42,7 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; import com.cloud.utils.fsm.FiniteStateObject; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vm_instance") @@ -470,5 +471,5 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject ${basedir}/target/db/create-schema.sql + ${basedir}/target/db/create-schema-view.sql ${basedir}/target/db/create-schema-premium.sql ${basedir}/target/db/templates.sql ${basedir}/target/db/create-index-fk.sql diff --git a/docs/en-US/accessing-vms.xml b/docs/en-US/accessing-vms.xml index d69d021471b..c77ad4eee52 100644 --- a/docs/en-US/accessing-vms.xml +++ b/docs/en-US/accessing-vms.xml @@ -29,7 +29,7 @@ Log in to the &PRODUCT; UI as a user or admin. Click Instances, then click the name of a running VM. - Click the View Console button . + Click the View Console button . To access a VM directly over the network: diff --git a/docs/en-US/added-error-codes.xml b/docs/en-US/added-error-codes.xml index 4436bf381e0..dbfea263598 100644 --- a/docs/en-US/added-error-codes.xml +++ b/docs/en-US/added-error-codes.xml @@ -128,7 +128,7 @@ 4535 : "com.cloud.exception.VirtualMachineMigrationException" - 9999 : "com.cloud.api.ServerApiException" + 9999 : "org.apache.cloudstack.api.ServerApiException" diff --git a/docs/en-US/autoscale.xml b/docs/en-US/autoscale.xml new file mode 100644 index 00000000000..d63281f9e7e --- /dev/null +++ b/docs/en-US/autoscale.xml @@ -0,0 +1,284 @@ + + +%BOOK_ENTITIES; +]> + + +
+ Configuring AutoScale + AutoScaling allows you to scale your back-end services or application VMs up or down + seamlessly and automatically according to the conditions you define. With AutoScaling enabled, + you can ensure that the number of VMs you are using seamlessly scale up when demand increases, + and automatically decreases when demand subsides. Thus it helps you save compute costs by + terminating underused VMs automatically and launching new VMs when you need them, without the + need for manual intervention. + NetScaler AutoScaling is designed to seamlessly launch or terminate VMs based on + user-defined conditions. Conditions for triggering a scaleup or scaledown action can vary from a + simple use case like monitoring the CPU usage of a server to a complex use case of monitoring a + combination of server's responsiveness and its CPU usage. For example, you can configure + AutoScaling to launch an additional VM whenever CPU usage exceeds 80 percent for 15 minutes, or + to remove a VM whenever CPU usage is less than 20 percent for 30 minutes. + &PRODUCT; uses the NetScaler load balancer to monitor all aspects of a system's health and + work in unison with &PRODUCT; to initiate scale-up or scale-down actions. The supported + NetScaler version is 10.0. + + Prerequisites + Before you configure an AutoScale rule, consider the following: + + + + Ensure that the necessary template is prepared before configuring AutoScale. When a VM + is deployed by using a template and when it comes up, the application should be up and + running. + + If the application is not running, the NetScaler device considers the VM as + ineffective and continues provisioning the VMs unconditionally until the resource limit is + exhausted. + + + + Deploy the templates you prepared. Ensure that the applications come up on the first + boot and is ready to take the traffic. Observe the time requires to deploy the template. + Consider this time when you specify the quiet time while configuring AutoScale. + + + The AutoScale feature supports the SNMP counters that can be used to define conditions + for taking scale up or scale down actions. To monitor the SNMP-based counter, ensure that + the SNMP agent is installed in the template used for creating the AutoScale VMs, and the + SNMP operations work with the configured SNMP community and port by using standard SNMP + managers. For example, see to configure SNMP on a RHEL + machine. + + + Ensure that the endpointe.url parameter present in the Global Settings is set to the + Management Server API URL. For example, http://10.102.102.22:8080/client/api. In a + multi-node Management Server deployment, use the virtual IP address configured in the load + balancer for the management server’s cluster. Additionally, ensure that the NetScaler device + has access to this IP address to provide AutoScale support. + If you update the endpointe.url, disable the AutoScale functionality of the load + balancer rules in the system, then enable them back to reflect the changes. For more + information see + + + If the API Key and Secret Key are regenerated for an AutoScale user, ensure that the + AutoScale functionality of the load balancers that the user participates in are disabled and + then enabled to reflect the configuration changes in the NetScaler. + + + In an advanced Zone, ensure that at least one VM should be present before configuring a + load balancer rule with AutoScale. Having one VM in the network ensures that the network is + in implemented state for configuring AutoScale. + + + + Configuration + Specify the following: + + + + + + + autoscaleateconfig.png: Configuring AutoScale + + + + + Template: A template consists of a base OS image and + application. A template is used to provision the new instance of an application on a scaleup + action. When a VM is deployed from a template, the VM can start taking the traffic from the + load balancer without any admin intervention. For example, if the VM is deployed for a Web + service, it should have the Web server running, the database connected, and so on. + + + Compute offering: A predefined set of virtual hardware + attributes, including CPU speed, number of CPUs, and RAM size, that the user can select when + creating a new virtual machine instance. Choose one of the compute offerings to be used + while provisioning a VM instance as part of scaleup action. + + + Min Instance: The minimum number of active VM instances + that is assigned to a load balancing rule. The active VM instances are the application + instances that are up and serving the traffic, and are being load balanced. This parameter + ensures that a load balancing rule has at least the configured number of active VM instances + are available to serve the traffic. + + If an application, such as SAP, running on a VM instance is down for some reason, the + VM is then not counted as part of Min Instance parameter, and the AutoScale feature + initiates a scaleup action if the number of active VM instances is below the configured + value. Similarly, when an application instance comes up from its earlier down state, this + application instance is counted as part of the active instance count and the AutoScale + process initiates a scaledown action when the active instance count breaches the Max + instance value. + + + + Max Instance: Maximum number of active VM instances + that should be assigned to a load balancing rule. This + parameter defines the upper limit of active VM instances that can be assigned to a load + balancing rule. + Specifying a large value for the maximum instance parameter might result in provisioning + large number of VM instances, which in turn leads to a single load balancing rule exhausting + the VM instances limit specified at the account or domain level. + + If an application, such as SAP, running on a VM instance is down for some reason, the + VM is not counted as part of Max Instance parameter. So there may be scenarios where the + number of VMs provisioned for a scaleup action might be more than the configured Max + Instance value. Once the application instances in the VMs are up from an earlier down + state, the AutoScale feature starts aligning to the configured Max Instance value. + + + + Specify the following scale-up and scale-down policies: + + + Duration: The duration, in seconds, for which the + conditions you specify must be true to trigger a scaleup action. The conditions defined + should hold true for the entire duration you specify for an AutoScale action to be invoked. + + + + Counter: The performance counters expose the state of + the monitored instances. By default, &PRODUCT; offers four performance counters: Three SNMP + counters and one NetScaler counter. The SNMP counters are Linux User CPU, Linux System CPU, + and Linux CPU Idle. The NetScaler counter is ResponseTime. The root administrator can add + additional counters into &PRODUCT; by using the &PRODUCT; API. + + + Operator: The following five relational operators are + supported in AutoScale feature: Greater than, Less than, Less than or equal to, Greater than + or equal to, and Equal to. + + + Threshold: Threshold value to be used for the counter. + Once the counter defined above breaches the threshold value, the AutoScale feature initiates + a scaleup or scaledown action. + + + Add: Click Add to add the condition. + + + Additionally, if you want to configure the advanced settings, click Show advanced settings, + and specify the following: + + + Polling interval: Frequency in which the conditions, + combination of counter, operator and threshold, are to be evaluated before taking a scale up + or down action. The default polling interval is 30 seconds. + + + Quiet Time: This is the cool down period after an + AutoScale action is initiated. The time includes the time taken to complete provisioning a + VM instance from its template and the time taken by an application to be ready to serve + traffic. This quiet time allows the fleet to come up to a stable state before any action can + take place. The default is 300 seconds. + + + Destroy VM Grace Period: The duration in seconds, after + a scaledown action is initiated, to wait before the VM is destroyed as part of scaledown + action. This is to ensure graceful close of any pending sessions or transactions being + served by the VM marked for destroy. The default is 120 seconds. + + + Security Groups: Security groups provide a way to + isolate traffic to the VM instances. A security group is a group of VMs that filter their + incoming and outgoing traffic according to a set of rules, called ingress and egress rules. + These rules filter network traffic according to the IP address that is attempting to + communicate with the VM. + + + Disk Offerings: A predefined set of disk size for + primary data storage. + + + SNMP Community: The SNMP community string to be used by + the NetScaler device to query the configured counter value from the provisioned VM + instances. Default is public. + + + SNMP Port: The port number on which the SNMP agent that + run on the provisioned VMs is listening. Default port is 161. + + + User: This is the user that the NetScaler device use to + invoke scaleup and scaledown API calls to the cloud. If no option is specified, the user who + configures AutoScaling is applied. Specify another user name to override. + + + Apply: Click Apply to create the AutoScale + configuration. + + + + Disabling and Enabling an AutoScale Configuration + If you want to perform any maintenance operation on the AutoScale VM instances, disable + the AutoScale configuration. When the AutoScale configuration is disabled, no scaleup or + scaledown action is performed. You can use this downtime for the maintenance activities. To + disable the AutoScale configuration, click the Disable AutoScale + + + + + EnableDisable.png: button to enable or disable AutoScale. + + button. + + The button toggles between enable and disable, depending on whether AutoScale is currently + enabled or not. After the maintenance operations are done, you can enable the AutoScale + configuration back. To enable, open the AutoScale configuration page again, then click the + Enable AutoScale + + + + + EnableDisable.png: button to enable or disable AutoScale. + + button. + + Updating an AutoScale Configuration + You can update the various parameters and add or delete the conditions in a scaleup or + scaledown rule. Before you update an AutoScale configuration, ensure that you disable the + AutoScale load balancer rule by clicking the Disable AutoScale button. + + After you modify the required AutoScale parameters, click Apply. To apply the new AutoScale + policies, open the AutoScale configuration page again, then click the Enable AutoScale + button. + + Runtime Considerations + + + + + An administrator should not assign a VM to a load balancing rule which is configured for + AutoScale. + + + Before a VM provisioning is completed if NetScaler is shutdown or restarted, the + provisioned VM cannot be a part of the load balancing rule though the intent was to assign + it to a load balancing rule. To workaround, rename the AutoScale provisioned VMs based on + the rule name or ID so at any point of time the VMs can be reconciled to its load balancing + rule. + + + Making API calls outside the context of AutoScale, such as destroyVM, on an autoscaled + VM leaves the load balancing configuration in an inconsistent state. Though VM is destroyed + from the load balancer rule, NetScaler continues to show the VM as a service assigned to a + rule. + + +
diff --git a/docs/en-US/aws-api-examples.xml b/docs/en-US/aws-api-examples.xml new file mode 100644 index 00000000000..ee3b44a5bde --- /dev/null +++ b/docs/en-US/aws-api-examples.xml @@ -0,0 +1,145 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Examples + There are many tools available to interface with a AWS compatible API. In this section we provide + a few examples that users of &PRODUCT; can build upon. + +
+ Boto Examples + Boto is one of them. It is a Python package available at https://github.com/boto/boto. + In this section we provide two examples of Python scripts that use Boto and have been tested with the + &PRODUCT; AWS API Interface. + First is an EC2 example. Replace the Access and Secret Keys with your own and + update the endpoint. + + + An EC2 Boto example + #!/usr/bin/env python + +import sys +import os +import boto +import boto.ec2 + +region = boto.ec2.regioninfo.RegionInfo(name="ROOT",endpoint="localhost") +apikey='GwNnpUPrO6KgIdZu01z_ZhhZnKjtSdRwuYd4DvpzvFpyxGMvrzno2q05MB0ViBoFYtdqKd' +secretkey='t4eXLEYWw7chBhDlaKf38adCMSHx_wlds6JfSx3z9fSpSOm0AbP9Moj0oGIzy2LSC8iw' + +def main(): + '''Establish connection to EC2 cloud''' + conn =boto.connect_ec2(aws_access_key_id=apikey, + aws_secret_access_key=secretkey, + is_secure=False, + region=region, + port=7080, + path="/awsapi", + api_version="2010-11-15") + + '''Get list of images that I own''' + images = conn.get_all_images() + print images + myimage = images[0] + '''Pick an instance type''' + vm_type='m1.small' + reservation = myimage.run(instance_type=vm_type,security_groups=['default']) + +if __name__ == '__main__': + main() + + + + Second is an S3 example. Replace the Access and Secret keys with your own, + as well as the endpoint of the service. Be sure to also update the file paths to something + that exists on your machine. + + + An S3 Boto Example + #!/usr/bin/env python + +import sys +import os +from boto.s3.key import Key +from boto.s3.connection import S3Connection +from boto.s3.connection import OrdinaryCallingFormat + +apikey='ChOw-pwdcCFy6fpeyv6kUaR0NnhzmG3tE7HLN2z3OB_s-ogF5HjZtN4rnzKnq2UjtnHeg_yLA5gOw' +secretkey='IMY8R7CJQiSGFk4cHwfXXN3DUFXz07cCiU80eM3MCmfLs7kusgyOfm0g9qzXRXhoAPCH-IRxXc3w' + +cf=OrdinaryCallingFormat() + +def main(): + '''Establish connection to S3 service''' + conn =S3Connection(aws_access_key_id=apikey,aws_secret_access_key=secretkey, \ + is_secure=False, \ + host='localhost', \ + port=7080, \ + calling_format=cf, \ + path="/awsapi/rest/AmazonS3") + + try: + bucket=conn.create_bucket('cloudstack') + k = Key(bucket) + k.key = 'test' + try: + k.set_contents_from_filename('/Users/runseb/Desktop/s3cs.py') + except: + print 'could not write file' + pass + except: + bucket = conn.get_bucket('cloudstack') + k = Key(bucket) + k.key = 'test' + try: + k.get_contents_to_filename('/Users/runseb/Desktop/foobar') + except: + print 'Could not get file' + pass + + try: + bucket1=conn.create_bucket('teststring') + k=Key(bucket1) + k.key('foobar') + k.set_contents_from_string('This is my silly test') + except: + bucket1=conn.get_bucket('teststring') + k = Key(bucket1) + k.key='foobar' + k.get_contents_as_string() + +if __name__ == '__main__': + main() + + + + +
+ +
+ JClouds Examples + +
+ +
diff --git a/docs/en-US/aws-ec2-configuration.xml b/docs/en-US/aws-ec2-configuration.xml index d6c4066d1d8..7d26027ba35 100644 --- a/docs/en-US/aws-ec2-configuration.xml +++ b/docs/en-US/aws-ec2-configuration.xml @@ -23,26 +23,88 @@ -->
- Enabling the AWS API Compatible Interface - - The software that provides AWS API compatibility is installed along with &PRODUCT;. However, you must enable the feature and perform some setup steps. - - - Set the global configuration parameter enable.ec2.api to true. See . - Create a set of &PRODUCT; service offerings with names that match the Amazon service offerings. - You can do this through the &PRODUCT; UI as described in the Administration Guide. - Be sure you have included the Amazon default service offering, m1.small. - If you did not already do so when you set the configuration parameter in step 1, restart the Management Server. - # service cloud-management restart - (Optional) The AWS API listens for requests on port 7080. If you prefer AWS API to listen on another port, you can change it as follows: - - Edit the files /etc/cloud/management/server.xml, /etc/cloud/management/server-nonssl.xml, and /etc/cloud/management/server-ssl.xml. - In each file, find the tag <Service name="Catalina7080">. Under this tag, locate <Connector executor="tomcatThreadPool-internal" port= ....<. - Change the port to whatever port you want to use, then save the files. - Restart the Management Server. - If you re-install CloudStack, you will have to make these changes again. + Enabling the EC2 and S3 Compatible Interface + + The software that provides AWS API compatibility is installed along with &PRODUCT;. You must enable the services and perform some setup steps prior to using it. + + + Set the global configuration parameters for each service to true. + See . + Create a set of &PRODUCT; service offerings with names that match the Amazon service offerings. + You can do this through the &PRODUCT; UI as described in the Administration Guide. + Be sure you have included the Amazon default service offering, m1.small. As well as any EC2 instance types that you will use. - - - + If you did not already do so when you set the configuration parameter in step 1, + restart the Management Server. + # service cloud-management restart + + + The following sections provides details to perform these steps + +
+ Enabling the Services + To enable the EC2 and S3 compatible services you need to set the configuration variables enable.ec2.api + and enable.s3.api to true. You do not have to enable both at the same time. Enable the ones you need. + This can be done via the &PRODUCT; GUI by going in Global Settings or via the API. + The snapshot below shows you how to use the GUI to enable these services + + + + + + + + Use the GUI to set the configuration variable to true + + + + + Using the &PRODUCT; API, the easiest is to use the so-called integration port on which you can make + unauthenticated calls. In Global Settings set the port to 8096 and subsequently call the updateConfiguration method. + The following urls shows you how: + + + + http://localhost:8096/client/api?command=updateConfiguration&name=enable.ec2.api&value=true + http://localhost:8096/client/api?command=updateConfiguration&name=enable.ec2.api&value=true + + + + Once you have enabled the services, restart the server. +
+ +
+ Creating EC2 Compatible Service Offerings + You will also need to define compute service offerings with names compatible with the + Amazon EC2 instance types API names (e.g m1.small,m1.large). This can be done via the &PRODUCT; GUI. + Go under Service Offerings select Compute offering and either create + a new compute offering or modify an existing one, ensuring that the name matches an EC2 instance type API name. The snapshot below shows you how: + + + + + + + Use the GUI to set the name of a compute service offering to an EC2 instance + type API name. + + + +
+
+ Modifying the AWS API Port + + (Optional) The AWS API listens for requests on port 7080. If you prefer AWS API to listen on another port, you can change it as follows: + + Edit the files /etc/cloud/management/server.xml, /etc/cloud/management/server-nonssl.xml, + and /etc/cloud/management/server-ssl.xml. + In each file, find the tag <Service name="Catalina7080">. Under this tag, + locate <Connector executor="tomcatThreadPool-internal" port= ....<. + Change the port to whatever port you want to use, then save the files. + Restart the Management Server. + + If you re-install &PRODUCT;, you will have to re-enable the services and if need be update the port. + +
+
diff --git a/docs/en-US/aws-ec2-introduction.xml b/docs/en-US/aws-ec2-introduction.xml index a4df086d465..538c09d5ad1 100644 --- a/docs/en-US/aws-ec2-introduction.xml +++ b/docs/en-US/aws-ec2-introduction.xml @@ -23,16 +23,19 @@ -->
- Amazon Web Services EC2 Compatible Interface + Amazon Web Services Compatible Interface &PRODUCT; can translate Amazon Web Services (AWS) API calls to native &PRODUCT; API calls so that users can continue using existing AWS-compatible tools. This translation service runs as a separate web application in the same tomcat server as the management server of &PRODUCT;, - listening on the same port. This Amazon EC2-compatible API is accessible through a SOAP web - service. + listening on a different port. The Amazon Web Services (AWS) compatible interface provides the + EC2 SOAP and Query APIs as well as the S3 REST API. This service was previously enabled by separate software called CloudBridge. It is now fully integrated with the &PRODUCT; management server. + + The compatible interface for the EC2 Query API and the S3 API are Work In Progress. The S3 compatible API offers a way to store data on the management server file system, it is not an implementation of the S3 backend. + Limitations @@ -42,7 +45,9 @@ Available in fresh installations of &PRODUCT;. Not available through upgrade of previous versions. - If you need to support features such as elastic IP, set up a Citrix NetScaler to provide this service. The commands such as ec2-associate-address will not work without EIP setup. Users running VMs in this zone will be using the NetScaler-enabled network offering (DefaultSharedNetscalerEIP and ELBNetworkOffering). + Features such as Elastic IP (EIP) and Elastic Load Balacing (ELB) are only available in an infrastructure + with a Citrix NetScaler device. Users accessing a Zone with a NetScaler device will need to use a + NetScaler-enabled network offering (DefaultSharedNetscalerEIP and ELBNetworkOffering).
diff --git a/docs/en-US/aws-ec2-requirements.xml b/docs/en-US/aws-ec2-requirements.xml index 59fb5b6f5ab..62e94b1ac9f 100644 --- a/docs/en-US/aws-ec2-requirements.xml +++ b/docs/en-US/aws-ec2-requirements.xml @@ -23,13 +23,14 @@ -->
- System Requirements + Supported API Version - This interface complies with Amazon's WDSL version dated November 15, 2010, available at + The EC2 interface complies with Amazon's WDSL version dated November 15, 2010, available at http://ec2.amazonaws.com/doc/2010-11-15/. - Compatible with the EC2 command-line + The interface is compatible with the EC2 command-line tools EC2 tools v. 1.3.6230, which can be downloaded at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip. -
\ No newline at end of file + Work is underway to support a more recent version of the EC2 API + diff --git a/docs/en-US/aws-ec2-supported-commands.xml b/docs/en-US/aws-ec2-supported-commands.xml index 9494218cd1c..7cdbcad8095 100644 --- a/docs/en-US/aws-ec2-supported-commands.xml +++ b/docs/en-US/aws-ec2-supported-commands.xml @@ -24,7 +24,7 @@
Supported AWS API Calls - The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatibility feature is enabled. + The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatible interface is enabled. For a few commands, there are differences between the &PRODUCT; and Amazon EC2 versions, and these differences are noted. The underlying SOAP call for each command is also given, for those who have built tools using those calls. diff --git a/docs/en-US/aws-ec2-timeouts.xml b/docs/en-US/aws-ec2-timeouts.xml index c8b3ec6465f..73d0c16c4df 100644 --- a/docs/en-US/aws-ec2-timeouts.xml +++ b/docs/en-US/aws-ec2-timeouts.xml @@ -24,7 +24,7 @@
Using Timeouts to Ensure AWS API Command Completion - The Amazon EC2 command-line tools have a default connection timeout. When used with &PRODUCT;, a longer timeout might be needed for some commands. If you find that commands are not completing due to timeouts, you can gain more time for commands to finish by overriding the default timeouts on individual commands. You can add the following optional command-line parameters to any &PRODUCT;-supported EC2 command: + The Amazon EC2 command-line tools have a default connection timeout. When used with &PRODUCT;, a longer timeout might be needed for some commands. If you find that commands are not completing due to timeouts, you can specify a custom timeouts. You can add the following optional command-line parameters to any &PRODUCT;-supported EC2 command: @@ -47,4 +47,5 @@ Example: ec2-run-instances 2 –z us-test1 –n 1-3 --connection-timeout 120 --request-timeout 120 -
\ No newline at end of file + The timeouts optional arguments are not specific to &PRODUCT;. + diff --git a/docs/en-US/aws-ec2-user-setup.xml b/docs/en-US/aws-ec2-user-setup.xml index 8607378d88c..edc371ef376 100644 --- a/docs/en-US/aws-ec2-user-setup.xml +++ b/docs/en-US/aws-ec2-user-setup.xml @@ -22,76 +22,84 @@ under the License. -->
- AWS API User Setup Steps + AWS API User Setup In general, users need not be aware that they are using a translation service provided by &PRODUCT;. - They need only send AWS API calls to &PRODUCT;'s endpoint, and it will translate the calls to the native API. - Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools + They only need to send AWS API calls to &PRODUCT;'s endpoint, and it will translate the calls to the native &PRODUCT; API. Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools and scripts and use them with their &PRODUCT; deployment, by specifying the endpoint of the management server and using the proper user credentials. In order to do this, each user must perform the following configuration steps: - Generate user credentials and register with the service. + Generate user credentials. - Set up the environment variables for the EC2 command-line tools. + Register with the service. - For SOAP access, use the endpoint http://&PRODUCT;-management-server:7080/awsapi. - The &PRODUCT;-management-server can be specified by a fully-qualified domain name or IP address. + For convenience, set up environment variables for the EC2 SOAP command-line tools.
AWS API User Registration - Each user must perform a one-time registration. The user follows these steps: - - - Obtain the following by looking in the &PRODUCT; UI, using the API, or asking the cloud administrator: - - The &PRODUCT; server's publicly available DNS name or IP address - The user account's API key and Secret key - - - - - Generate a private key and a self-signed X.509 certificate. The user substitutes their own desired storage location for /path/to/… below. - - $ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem - - - - - Register the mapping from the X.509 certificate to the API/Secret keys. - Download the following script from http://download.cloud.com/releases/3.0.3/cloudstack-aws-api-register and run it. - Substitute the values that were obtained in step 1 in the URL below. - - -$ cloudstack-aws-api-register --apikey=User’s &PRODUCT; API key --secretkey=User’s &PRODUCT; Secret key --cert=/path/to/cert.pem --url=http://&PRODUCT;.server:7080/awsapi - - - + Each user must perform a one-time registration. The user follows these steps: + + + Obtain the following by looking in the &PRODUCT; UI, using the API, or asking the cloud administrator: + + + The &PRODUCT; server's publicly available DNS name or IP address + The user account's Access key and Secret key + + + + Generate a private key and a self-signed X.509 certificate. The user substitutes their own desired storage location for /path/to/… below. + + + $ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem + + + + Register the user X.509 certificate and Access/Secret keys with the AWS compatible service. + If you have the source code of &PRODUCT; go to the awsapi-setup/setup directory and use the Python script + cloudstack-aws-api-register. If you do not have the source then download the script using the following command. + + + wget -O cloudstack-aws-api-register "https://git-wip-us.apache.org/repos/asf?p=incubator-cloudstack.git;a=blob_plain;f=awsapi-setup/setup/cloudstack-aws-api-register;hb=HEAD" + + + Then execute it, using the parameter values that were obtained in step 1. An example is shown below. + + $ cloudstack-aws-api-register --apikey=User’s &PRODUCT; API key --secretkey=User’s &PRODUCT; Secret key --cert=/path/to/cert.pem --url=http://&PRODUCT;.server:7080/awsapi + + + - A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT;, but the public key would be uploaded to the &PRODUCT; management server database. + A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT;, but note that the certificate would be uploaded to the &PRODUCT; management server database.
- AWS API Command-Line Tools Setup - To use the EC2 command-line tools, the user must perform these steps: - - Be sure you have the right version of EC2 Tools. - The supported version is available at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip. - - - Set up the environment variables that will direct the tools to the server. As a best practice, you may wish to place these commands in a script that may be sourced before using the AWS API translation feature. - $ export EC2_CERT=/path/to/cert.pem -$ export EC2_PRIVATE_KEY=/path/to/private_key.pem -$ export EC2_URL=http://&PRODUCT;.server:7080/awsapi -$ export EC2_HOME=/path/to/EC2_tools_directory - - + AWS API Command-Line Tools Setup + To use the EC2 command-line tools, the user must perform these steps: + + + Be sure you have the right version of EC2 Tools. + The supported version is available at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip. + + + + Set up the EC2 environment variables. This can be done every time you use the service or you can set them up in the proper shell profile. Replace the endpoint (i.e EC2_URL) with the proper address of your &PRODUCT; management server and port. In a bash shell do the following. + + + $ export EC2_CERT=/path/to/cert.pem + $ export EC2_PRIVATE_KEY=/path/to/private_key.pem + $ export EC2_URL=http://localhost:7080/awsapi + $ export EC2_HOME=/path/to/EC2_tools_directory + + +
-
\ No newline at end of file + diff --git a/docs/en-US/aws-interface-compatibility.xml b/docs/en-US/aws-interface-compatibility.xml index a03d447b50d..2c85c24b36a 100644 --- a/docs/en-US/aws-interface-compatibility.xml +++ b/docs/en-US/aws-interface-compatibility.xml @@ -23,11 +23,12 @@ --> - Amazon Web Service Interface Compatibility + Amazon Web Services Compatible Interface + diff --git a/docs/en-US/build-deb.xml b/docs/en-US/build-deb.xml index deee3ceb1de..37e5a7d7474 100644 --- a/docs/en-US/build-deb.xml +++ b/docs/en-US/build-deb.xml @@ -110,7 +110,7 @@ cloud-utils_4.0.0-incubating_amd64.deb create /etc/apt/sources.list.d/cloudstack.list with this line: - deb http://server.url/cloudstack/repo binary/ + deb http://server.url/cloudstack/repo binary ./Now that you have the repository info in place, you'll want to run another update so that APT knows where to find the &PRODUCT; packages. diff --git a/docs/en-US/building-marvin.xml b/docs/en-US/building-marvin.xml new file mode 100644 index 00000000000..3dac9d65d60 --- /dev/null +++ b/docs/en-US/building-marvin.xml @@ -0,0 +1,46 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Building and Installing Marvin + Marvin is built with Maven and is dependent on APIdoc. To build it do the following in the root tree of &PRODUCT;: + mvn -P developer -l :cloud-apidoc + mvn -P developer -l :cloud-marvin + If successfull the build will have created the cloudstackAPI Python package under tools/marvin/marvin/cloudstackAPI as well as a gziped Marvin package under tools/marvin dist. To install the Python Marvin module do the following in tools/marvin: + sudo python ./setup.py install + The dependencies will be downloaded the Python module installed and you should be able to use Marvin in Python. Check that you can import the module before starting to use it. + $ python +Python 2.7.3 (default, Nov 17 2012, 19:54:34) +[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import marvin +>>> from marvin.cloudstackAPI import * +>>> + + You could also install it using pip or easy_install using the local distribution package in tools/marvin/dist : + pip install tools/marvin/dist/Marvin-0.1.0.tar.gz + Or: + easy_install tools/marvin/dist/Marvin-0.1.0.tar.gz + +
diff --git a/docs/en-US/configure-snmp-rhel.xml b/docs/en-US/configure-snmp-rhel.xml new file mode 100644 index 00000000000..bd227ff8ed5 --- /dev/null +++ b/docs/en-US/configure-snmp-rhel.xml @@ -0,0 +1,86 @@ + + +%BOOK_ENTITIES; +]> + +
+ Configuring SNMP Community String on a RHEL Server + The SNMP Community string is similar to a user id or password that provides access to a + network device, such as router. This string is sent along with all SNMP requests. If the + community string is correct, the device responds with the requested information. If the + community string is incorrect, the device discards the request and does not respond. + The NetScaler device uses SNMP to communicate with the VMs. You must install SNMP and + configure SNMP Community string for a secure communication between the NetScaler device and the + RHEL machine. + + + Ensure that you installed SNMP on RedHat. If not, run the following command: + yum install net-snmp-utils + + + Edit the /etc/snmp/snmpd.conf file to allow the SNMP polling from the NetScaler + device. + + + Map the community name into a security name (local and mynetwork, depending on where + the request is coming from): + + Use a strong password instead of public when you edit the following table. + + # sec.name source community +com2sec local localhost public +com2sec mynetwork 0.0.0.0 public + + Setting to 0.0.0.0 allows all IPs to poll the NetScaler server. + + + + Map the security names into group names: + # group.name sec.model sec.name +group MyRWGroup v1 local +group MyRWGroup v2c local +group MyROGroup v1 mynetwork +group MyROGroup v2c mynetwork + + + Create a view to allow the groups to have the permission to: + incl/excl subtree mask view all included .1 + + + Grant access with different write permissions to the two groups to the view you + created. + # context sec.model sec.level prefix read write notif + access MyROGroup "" any noauth exact all none none + access MyRWGroup "" any noauth exact all all all + + + + + Unblock SNMP in iptables. + iptables -A INPUT -p udp --dport 161 -j ACCEPT + + + Start the SNMP service: + service snmpd start + + + Ensure that the SNMP service is started automatically during the system startup: + chkconfig snmpd on + + +
diff --git a/docs/en-US/external-firewalls-and-load-balancers.xml b/docs/en-US/external-firewalls-and-load-balancers.xml index 1452804885d..6ca49f0ef03 100644 --- a/docs/en-US/external-firewalls-and-load-balancers.xml +++ b/docs/en-US/external-firewalls-and-load-balancers.xml @@ -3,26 +3,31 @@ %BOOK_ENTITIES; ]> - -
- External Firewalls and Load Balancers - &PRODUCT; is capable of replacing its Virtual Router with an external Juniper SRX device and an optional external NetScaler or F5 load balancer for gateway and load balancing services. In this case, the VMs use the SRX as their gateway. + External Firewalls and Load Balancers + &PRODUCT; is capable of replacing its Virtual Router with an external Juniper SRX device and + an optional external NetScaler or F5 load balancer for gateway and load balancing services. In + this case, the VMs use the SRX as their gateway. + + + + +
diff --git a/docs/en-US/images/compute-service-offerings.png b/docs/en-US/images/compute-service-offerings.png new file mode 100644 index 00000000000..88eb6f80597 Binary files /dev/null and b/docs/en-US/images/compute-service-offerings.png differ diff --git a/docs/en-US/images/ec2-s3-configuration.png b/docs/en-US/images/ec2-s3-configuration.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/docs/en-US/images/view-console-button.png b/docs/en-US/images/view-console-button.png new file mode 100644 index 00000000000..b321ceadefe Binary files /dev/null and b/docs/en-US/images/view-console-button.png differ diff --git a/docs/en-US/marvin.xml b/docs/en-US/marvin.xml index 062616ac888..8fd2c96fe3f 100644 --- a/docs/en-US/marvin.xml +++ b/docs/en-US/marvin.xml @@ -29,4 +29,5 @@ Marvin's complete documenation is on the wiki at https://cwiki.apache.org/CLOUDSTACK/testing-with-python.htmlThe source code is located at tools/marvin + diff --git a/docs/en-US/ongoing-configuration-of-external-firewalls-loadbalancer.xml b/docs/en-US/ongoing-configuration-of-external-firewalls-loadbalancer.xml new file mode 100644 index 00000000000..c90c7ada622 --- /dev/null +++ b/docs/en-US/ongoing-configuration-of-external-firewalls-loadbalancer.xml @@ -0,0 +1,46 @@ + + +%BOOK_ENTITIES; +]> + +
+ Ongoing Configuration of External Firewalls and Load Balancers + Additional user actions (e.g. setting a port forward) will cause further programming of the + firewall and load balancer. A user may request additional public IP addresses and forward + traffic received at these IPs to specific VMs. This is accomplished by enabling static NAT for a + public IP address, assigning the IP to a VM, and specifying a set of protocols and port ranges + to open. When a static NAT rule is created, &PRODUCT; programs the zone's external firewall with + the following objects: + + + A static NAT rule that maps the public IP address to the private IP address of a + VM. + + + A security policy that allows traffic within the set of protocols and port ranges that + are specified. + + + A firewall filter counter that measures the number of bytes of incoming traffic to the + public IP. + + + The number of incoming and outgoing bytes through source NAT, static NAT, and load balancing + rules is measured and saved on each external element. This data is collected on a regular basis + and stored in the &PRODUCT; database. +
diff --git a/docs/en-US/system-service-offerings.xml b/docs/en-US/system-service-offerings.xml index c41aa2e293b..84d5f7ae7b5 100644 --- a/docs/en-US/system-service-offerings.xml +++ b/docs/en-US/system-service-offerings.xml @@ -26,4 +26,5 @@ System Service Offerings System service offerings provide a choice of CPU speed, number of CPUs, tags, and RAM size, just as other service offerings do. But rather than being used for virtual machine instances and exposed to users, system service offerings are used to change the default properties of virtual routers, console proxies, and other system VMs. System service offerings are visible only to the &PRODUCT; root administrator. &PRODUCT; provides default system service offerings. The &PRODUCT; root administrator can create additional custom system service offerings. When &PRODUCT; creates a virtual router for a guest network, it uses default settings which are defined in the system service offering associated with the network offering. You can upgrade the capabilities of the virtual router by applying a new network offering that contains a different system service offering. All virtual routers in that network will begin using the settings from the new service offering. + diff --git a/packaging/centos63/cloud-agent.rc b/packaging/centos63/cloud-agent.rc new file mode 100755 index 00000000000..084b71543a8 --- /dev/null +++ b/packaging/centos63/cloud-agent.rc @@ -0,0 +1,121 @@ +#!/bin/bash + +# chkconfig: 35 99 10 +# description: Cloud Agent + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well + +. /etc/rc.d/init.d/functions + +whatami=cloud-agent + +# set environment variables + +SHORTNAME="$whatami" +PIDFILE=/var/run/"$whatami".pid +LOCKFILE=/var/lock/subsys/"$SHORTNAME" +LOGFILE=/var/log/cloud/agent/agent.log +PROGNAME="Cloud Agent" +CLASS="com.cloud.agent.AgentShell" +JSVC=`which jsvc 2>/dev/null`; + +# exit if we don't find jsvc +if [ -z "$JSVC" ]; then + echo no jsvc found in path; + exit 1; +fi + +unset OPTIONS +[ -r /etc/sysconfig/"$SHORTNAME" ] && source /etc/sysconfig/"$SHORTNAME" + +# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT) +JDK_DIRS="/usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm" + +for jdir in $JDK_DIRS; do + if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then + JAVA_HOME="$jdir" + fi +done +export JAVA_HOME + +SCP="" +DCP="" +ACP=`ls /usr/share/cloud/java/* | tr '\n' ':'` +JCP="/usr/share/java/commons-daemon.jar" + +# We need to append the JSVC daemon JAR to the classpath +# AgentShell implements the JSVC daemon methods +export CLASSPATH="$SCP:$DCP:$ACP:$JCP:/etc/cloud/agent:/usr/lib64/cloud/agent" + +start() { + echo -n $"Starting $PROGNAME: " + if hostname --fqdn >/dev/null 2>&1 ; then + $JSVC -cp "$CLASSPATH" -pidfile "$PIDFILE" $CLASS + RETVAL=$? + echo + else + failure + echo + echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr + RETVAL=9 + fi + [ $RETVAL = 0 ] && touch ${LOCKFILE} + return $RETVAL +} + +stop() { + echo -n $"Stopping $PROGNAME: " + $JSVC -pidfile "$PIDFILE" -stop $CLASS + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE} +} + + +# See how we were called. +case "$1" in + start) + start + ;; + stop) + stop + ;; + status) + status -p ${PIDFILE} $SHORTNAME + RETVAL=$? + ;; + restart) + stop + sleep 3 + start + ;; + condrestart) + if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then + stop + sleep 3 + start + fi + ;; + *) + echo $"Usage: $whatami {start|stop|restart|condrestart|status|help}" + RETVAL=3 +esac + +exit $RETVAL diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec index e6f2ae24ed5..d828e673c97 100644 --- a/packaging/centos63/cloud.spec +++ b/packaging/centos63/cloud.spec @@ -103,6 +103,18 @@ Group: System Environment/Libraries The CloudStack Python library contains a few Python modules that the CloudStack uses. +%package agent +Summary: CloudStack Agent for KVM hypervisors +Requires: java >= 1.6.0 +Requires: %{name}-python = %{_ver} +Requires: libvirt +Requires: bridge-utils +Requires: ebtables +Requires: jsvc +Requires: jna +Group: System Environment/Libraries +%description agent +The CloudStack agent for KVM hypervisors %prep echo Doing CloudStack build @@ -183,8 +195,22 @@ chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/cache/%{name}/management/temp chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/management chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/agent chmod -R ugo+x ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/scripts -%clean +mkdir -p ${RPM_BUILD_ROOT}/etc/cloud/agent +mkdir -p ${RPM_BUILD_ROOT}/var/log/cloud/agent +install -D packaging/centos63/cloud-agent.rc ${RPM_BUILD_ROOT}/etc/init.d/%{name}-agent +install -D agent/target/transformed/agent.properties ${RPM_BUILD_ROOT}/etc/cloud/agent/agent.properties +install -D agent/target/transformed/environment.properties ${RPM_BUILD_ROOT}/etc/cloud/agent/environment.properties +install -D agent/target/transformed/log4j-cloud.xml ${RPM_BUILD_ROOT}/etc/cloud/agent/log4j-cloud.xml +install -D agent/target/transformed/cloud-setup-agent ${RPM_BUILD_ROOT}/usr/bin/cloud-setup-agent +install -D agent/target/transformed/cloud-ssh ${RPM_BUILD_ROOT}/usr/bin/cloud-ssh + +install -D plugins/hypervisors/kvm/target/%{name}-plugin-hypervisor-kvm-%{_maventag}.jar ${RPM_BUILD_ROOT}/usr/share/cloud/java/%{name}-plugin-hypervisor-kvm-%{_maventag}.jar +cp plugins/hypervisors/kvm/target/dependencies/* ${RPM_BUILD_ROOT}/usr/share/cloud/java +mkdir -p ${RPM_BUILD_ROOT}/usr/share/cloud/scripts +cp -r scripts/* ${RPM_BUILD_ROOT}/usr/share/cloud/scripts + +%clean [ ${RPM_BUILD_ROOT} != "/" ] && rm -rf ${RPM_BUILD_ROOT} @@ -271,6 +297,14 @@ fi %doc LICENSE %doc NOTICE +%files agent +%attr(0755,root,root) %{_bindir}/%{name}-setup-agent +%attr(0755,root,root) %{_bindir}/%{name}-ssh +%attr(0755,root,root) %{_sysconfdir}/init.d/cloud-agent +%config(noreplace) %{_sysconfdir}/cloud/agent +%dir /var/log/cloud/agent +%attr(0644,root,root) /usr/share/cloud/java/*.jar +%attr(0755,root,root) /usr/share/cloud/scripts %changelog * Fri Oct 03 2012 Hugo Trippaers 4.1.0 diff --git a/plugins/acl/static-role-based/pom.xml b/plugins/acl/static-role-based/pom.xml new file mode 100644 index 00000000000..a2e8d05d48e --- /dev/null +++ b/plugins/acl/static-role-based/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + cloud-plugin-acl-static-role-based + Apache CloudStack Plugin - ACL Static Role Based + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java new file mode 100644 index 00000000000..16357846cba --- /dev/null +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -0,0 +1,100 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.acl; + +import com.cloud.exception.PermissionDeniedException; +import com.cloud.server.ManagementServer; +import com.cloud.user.Account; +import com.cloud.user.AccountService; +import com.cloud.user.User; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.component.ComponentLocator; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.log4j.Logger; + +// This is the default API access checker that grab's the user's account +// based on the account type, access is granted +@Local(value = APIChecker.class) +public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIChecker { + + protected static final Logger s_logger = Logger.getLogger(StaticRoleBasedAPIAccessChecker.class); + + private static Map> s_roleBasedApisMap = + new HashMap>(); + + private static AccountService s_accountService; + + protected StaticRoleBasedAPIAccessChecker() { + super(); + for (RoleType roleType : RoleType.values()) + s_roleBasedApisMap.put(roleType, new HashSet()); + } + + @Override + public boolean checkAccess(User user, String commandName) + throws PermissionDeniedException { + Account account = s_accountService.getAccount(user.getAccountId()); + if (account == null) { + throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null"); + } + + RoleType roleType = s_accountService.getRoleType(account); + boolean isAllowed = s_roleBasedApisMap.get(roleType).contains(commandName); + if (!isAllowed) { + throw new PermissionDeniedException("The API does not exist or is blacklisted. Role type=" + roleType.toString() + " is not allowed to request the api: " + commandName); + } + return isAllowed; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + + // Read command properties files to build the static map per role. + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + s_accountService = locator.getManager(AccountService.class); + + processMapping(PropertiesUtil.processConfigFile(new String[] + {"commands.properties"})); + + return true; + } + + private void processMapping(Map configMap) { + for (Map.Entry entry : configMap.entrySet()) { + String apiName = entry.getKey(); + String roleMask = entry.getValue(); + try { + short cmdPermissions = Short.parseShort(roleMask); + for (RoleType roleType : RoleType.values()) { + if ((cmdPermissions & roleType.getValue()) != 0) + s_roleBasedApisMap.get(roleType).add(apiName); + } + } catch (NumberFormatException nfe) { + s_logger.info("Malformed key=value pair for entry: " + entry.toString()); + } + } + } +} diff --git a/plugins/api/discovery/pom.xml b/plugins/api/discovery/pom.xml new file mode 100644 index 00000000000..a61b275addc --- /dev/null +++ b/plugins/api/discovery/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + cloud-plugin-api-discovery + Apache CloudStack Plugin - API Discovery + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + + + org.apache.cloudstack + cloud-api + ${project.version} + + + org.apache.cloudstack + cloud-utils + ${project.version} + + + diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java b/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java new file mode 100644 index 00000000000..bad7ca7b5f6 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/command/user/discovery/ListApisCmd.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.discovery; + +import com.cloud.user.User; +import com.cloud.user.UserContext; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.discovery.ApiDiscoveryService; +import org.apache.cloudstack.api.response.ApiDiscoveryResponse; + +import org.apache.log4j.Logger; + +@APICommand(name = "listApis", responseObject = ApiDiscoveryResponse.class, description = "lists all available apis on the server, provided by the Api Discovery plugin", since = "4.1.0") +public class ListApisCmd extends BaseCmd { + + public static final Logger s_logger = Logger.getLogger(ListApisCmd.class.getName()); + private static final String s_name = "listapisresponse"; + + @PlugService + ApiDiscoveryService _apiDiscoveryService; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="API name") + private String name; + + @Override + public void execute() throws ServerApiException { + if (_apiDiscoveryService != null) { + User user = UserContext.current().getCallerUser(); + ListResponse response = (ListResponse) _apiDiscoveryService.listApis(user, name); + if (response == null) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Api Discovery plugin was unable to find an api by that name or process any apis"); + } + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + // no owner is needed for list command + return 0; + } +} diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java new file mode 100644 index 00000000000..de6a9f93965 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiDiscoveryResponse.java @@ -0,0 +1,95 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + +import java.util.HashSet; +import java.util.Set; + +@SuppressWarnings("unused") +public class ApiDiscoveryResponse extends BaseResponse { + @SerializedName(ApiConstants.NAME) @Param(description="the name of the api command") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) @Param(description="description of the api") + private String description; + + @SerializedName(ApiConstants.SINCE) @Param(description="version of CloudStack the api was introduced in") + private String since; + + @SerializedName(ApiConstants.IS_ASYNC) @Param(description="true if api is asynchronous") + private Boolean isAsync; + + @SerializedName("related") @Param(description="comma separated related apis") + private String related; + + @SerializedName(ApiConstants.PARAMS) @Param(description="the list params the api accepts", responseObject = ApiParameterResponse.class) + private Set params; + + @SerializedName(ApiConstants.RESPONSE) @Param(description="api response fields", responseObject = ApiResponseResponse.class) + private Set apiResponse; + + public ApiDiscoveryResponse(){ + params = new HashSet(); + apiResponse = new HashSet(); + isAsync = false; + } + + public void setName(String name) { + this.name = name; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setSince(String since) { + this.since = since; + } + + public void setAsync(Boolean isAsync) { + this.isAsync = isAsync; + } + + public String getRelated() { + return related; + } + + public void setRelated(String related) { + this.related = related; + } + + public Set getParams() { + return params; + } + + public void setParams(Set params) { + this.params = params; + } + + public void addParam(ApiParameterResponse param) { + this.params.add(param); + } + + public void addApiResponse(ApiResponseResponse apiResponse) { + this.apiResponse.add(apiResponse); + } +} diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiParameterResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiParameterResponse.java new file mode 100644 index 00000000000..fa6dc1752d2 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiParameterResponse.java @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + +public class ApiParameterResponse extends BaseResponse { + @SerializedName(ApiConstants.NAME) @Param(description="the name of the api parameter") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) @Param(description="description of the api parameter") + private String description; + + @SerializedName(ApiConstants.TYPE) @Param(description="parameter type") + private String type; + + @SerializedName(ApiConstants.LENGTH) @Param(description="length of the parameter") + private int length; + + @SerializedName(ApiConstants.REQUIRED) @Param(description="true if this parameter is required for the api request") + private Boolean required; + + @SerializedName(ApiConstants.SINCE) @Param(description="version of CloudStack the api was introduced in") + private String since; + + @SerializedName("related") @Param(description="comma separated related apis to get the parameter") + private String related; + + public ApiParameterResponse(){ + } + + public void setName(String name) { + this.name = name; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setType(String type) { + this.type = type; + } + + public void setLength(int length) { + this.length = length; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public void setSince(String since) { + this.since = since; + } + + public String getRelated() { + return related; + } + + public void setRelated(String related) { + this.related = related; + } + + } diff --git a/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java new file mode 100644 index 00000000000..b96295e1290 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/api/response/ApiResponseResponse.java @@ -0,0 +1,45 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + +public class ApiResponseResponse extends BaseResponse { + @SerializedName(ApiConstants.NAME) @Param(description="the name of the api response field") + private String name; + + @SerializedName(ApiConstants.DESCRIPTION) @Param(description="description of the api response field") + private String description; + + @SerializedName(ApiConstants.TYPE) @Param(description="response field type") + private String type; + + public void setName(String name) { + this.name = name; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java new file mode 100644 index 00000000000..6458c5619e8 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryService.java @@ -0,0 +1,26 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.discovery; + +import com.cloud.user.User; +import com.cloud.utils.component.PluggableService; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.response.ListResponse; + +public interface ApiDiscoveryService extends PluggableService { + ListResponse listApis(User user, String apiName); +} diff --git a/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java new file mode 100644 index 00000000000..f06e2005552 --- /dev/null +++ b/plugins/api/discovery/src/org/apache/cloudstack/discovery/ApiDiscoveryServiceImpl.java @@ -0,0 +1,217 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.discovery; + +import com.cloud.serializer.Param; +import com.cloud.user.User; +import com.cloud.utils.ReflectUtil; +import com.cloud.utils.StringUtils; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.component.ComponentLocator; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.acl.APIChecker; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.command.user.discovery.ListApisCmd; +import org.apache.cloudstack.api.response.ApiDiscoveryResponse; +import org.apache.cloudstack.api.response.ApiParameterResponse; +import org.apache.cloudstack.api.response.ApiResponseResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Local(value = ApiDiscoveryService.class) +public class ApiDiscoveryServiceImpl implements ApiDiscoveryService { + private static final Logger s_logger = Logger.getLogger(ApiDiscoveryServiceImpl.class); + + protected static Adapters s_apiAccessCheckers = null; + private static Map s_apiNameDiscoveryResponseMap = null; + + protected ApiDiscoveryServiceImpl() { + super(); + if (s_apiNameDiscoveryResponseMap == null) { + long startTime = System.nanoTime(); + s_apiNameDiscoveryResponseMap = new HashMap(); + cacheResponseMap(); + long endTime = System.nanoTime(); + s_logger.info("Api Discovery Service: Annotation, docstrings, api relation graph processed in " + (endTime - startTime) / 1000000.0 + " ms"); + } + } + + private void cacheResponseMap() { + Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, + new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); + + //TODO: Fix and use PluggableService to get the classes + + Map> responseApiNameListMap = new HashMap>(); + + for (Class cmdClass : cmdClasses) { + APICommand apiCmdAnnotation = cmdClass.getAnnotation(APICommand.class); + if (apiCmdAnnotation == null) + apiCmdAnnotation = cmdClass.getSuperclass().getAnnotation(APICommand.class); + if (apiCmdAnnotation == null + || !apiCmdAnnotation.includeInApiDoc() + || apiCmdAnnotation.name().isEmpty()) + continue; + + String apiName = apiCmdAnnotation.name(); + String responseName = apiCmdAnnotation.responseObject().getName(); + if (!responseName.contains("SuccessResponse")) { + if (!responseApiNameListMap.containsKey(responseName)) + responseApiNameListMap.put(responseName, new ArrayList()); + responseApiNameListMap.get(responseName).add(apiName); + } + ApiDiscoveryResponse response = new ApiDiscoveryResponse(); + response.setName(apiName); + response.setDescription(apiCmdAnnotation.description()); + if (!apiCmdAnnotation.since().isEmpty()) + response.setSince(apiCmdAnnotation.since()); + response.setRelated(responseName); + + Field[] responseFields = apiCmdAnnotation.responseObject().getDeclaredFields(); + for (Field responseField : responseFields) { + SerializedName serializedName = responseField.getAnnotation(SerializedName.class); + if (serializedName != null) { + ApiResponseResponse responseResponse = new ApiResponseResponse(); + responseResponse.setName(serializedName.value()); + Param param = responseField.getAnnotation(Param.class); + if (param != null) + responseResponse.setDescription(param.description()); + responseResponse.setType(responseField.getType().getSimpleName().toLowerCase()); + response.addApiResponse(responseResponse); + } + } + + Field[] fields = ReflectUtil.getAllFieldsForClass(cmdClass, + new Class[]{BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + + boolean isAsync = ReflectUtil.isCmdClassAsync(cmdClass, + new Class[]{BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + + response.setAsync(isAsync); + + for (Field field : fields) { + Parameter parameterAnnotation = field.getAnnotation(Parameter.class); + if (parameterAnnotation != null + && parameterAnnotation.expose() + && parameterAnnotation.includeInApiDoc()) { + + ApiParameterResponse paramResponse = new ApiParameterResponse(); + paramResponse.setName(parameterAnnotation.name()); + paramResponse.setDescription(parameterAnnotation.description()); + paramResponse.setType(parameterAnnotation.type().toString().toLowerCase()); + paramResponse.setLength(parameterAnnotation.length()); + paramResponse.setRequired(parameterAnnotation.required()); + if (!parameterAnnotation.since().isEmpty()) + paramResponse.setSince(parameterAnnotation.since()); + paramResponse.setRelated(parameterAnnotation.entityType()[0].getName()); + response.addParam(paramResponse); + } + } + response.setObjectName("api"); + s_apiNameDiscoveryResponseMap.put(apiName, response); + } + + for (String apiName : s_apiNameDiscoveryResponseMap.keySet()) { + ApiDiscoveryResponse response = s_apiNameDiscoveryResponseMap.get(apiName); + Set processedParams = new HashSet(); + for (ApiParameterResponse param : response.getParams()) { + if (responseApiNameListMap.containsKey(param.getRelated())) { + List relatedApis = responseApiNameListMap.get(param.getRelated()); + param.setRelated(StringUtils.join(relatedApis, ",")); + } else { + param.setRelated(null); + } + processedParams.add(param); + } + response.setParams(processedParams); + + if (responseApiNameListMap.containsKey(response.getRelated())) { + List relatedApis = responseApiNameListMap.get(response.getRelated()); + relatedApis.remove(apiName); + response.setRelated(StringUtils.join(relatedApis, ",")); + } else { + response.setRelated(null); + } + s_apiNameDiscoveryResponseMap.put(apiName, response); + } + } + + @Override + public ListResponse listApis(User user, String name) { + ListResponse response = new ListResponse(); + List responseList = new ArrayList(); + + if (s_apiAccessCheckers == null) { + ComponentLocator locator = ComponentLocator.getCurrentLocator(); + s_apiAccessCheckers = locator.getAdapters(APIChecker.class); + } + + if (user == null) + return null; + + if (name != null) { + if (!s_apiNameDiscoveryResponseMap.containsKey(name)) + return null; + + for (APIChecker apiChecker : s_apiAccessCheckers) { + try { + apiChecker.checkAccess(user, name); + } catch (Exception ex) { + return null; + } + } + responseList.add(s_apiNameDiscoveryResponseMap.get(name)); + + } else { + for (String apiName : s_apiNameDiscoveryResponseMap.keySet()) { + boolean isAllowed = true; + for (APIChecker apiChecker : s_apiAccessCheckers) { + try { + apiChecker.checkAccess(user, apiName); + } catch (Exception ex) { + isAllowed = false; + } + } + if (isAllowed) + responseList.add(s_apiNameDiscoveryResponseMap.get(apiName)); + } + } + response.setResponses(responseList); + return response; + } + + @Override + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(ListApisCmd.class); + return cmdList; + } +} diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java index db317e06d65..c87c9242010 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java @@ -20,18 +20,18 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.netapp.NetappManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.AssociateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Associate a LUN with a guest IQN", responseObject = AssociateLunCmdResponse.class) +@APICommand(name = "associateLun", description="Associate a LUN with a guest IQN", responseObject = AssociateLunCmdResponse.class) public class AssociateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AssociateLunCmd.class.getName()); private static final String s_name = "associatelunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java index 2e0eb86eb1b..8c89730b978 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java @@ -20,11 +20,11 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a LUN from a pool", responseObject = CreateLunCmdResponse.class) +@APICommand(name = "createLunOnFiler", description="Create a LUN from a pool", responseObject = CreateLunCmdResponse.class) public class CreateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateLunCmd.class.getName()); private static final String s_name = "createlunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java index a301deeed4a..a2d4b96e6dd 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import java.net.UnknownHostException; import java.rmi.ServerException; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -34,7 +34,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateVolumeOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class) +@APICommand(name = "createVolumeOnFiler", description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class) public class CreateVolumeOnFilerCmd extends BaseCmd { private static final String s_name = "createvolumeresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java index 020493b98d4..9e38c5fc097 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java @@ -18,11 +18,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class) +@APICommand(name = "createPool", description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class) public class CreateVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateVolumePoolCmd.class.getName()); private static final String s_name = "createpoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java index de12511f0dd..1105ea53e9d 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class) +@APICommand(name = "deletePool", description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class) public class DeleteVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteVolumePoolCmd.class.getName()); private static final String s_name = "deletepoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java index 76ccd0e5c3d..c5f7b117f5b 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java @@ -20,23 +20,22 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.netapp.NetappManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteLUNCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) +@APICommand(name = "destroyLunOnFiler", description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) public class DestroyLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DestroyLunCmd.class.getName()); diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java index 4bde7f519b8..4ddc0c9f6d0 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java @@ -18,13 +18,10 @@ package com.cloud.api.commands.netapp; import java.rmi.ServerException; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -36,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteVolumeOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class) +@APICommand(name = "destroyVolumeOnFiler", description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class) public class DestroyVolumeOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DestroyVolumeOnFilerCmd.class.getName()); private static final String s_name = "destroyvolumeresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java index 77425cbe5ce..0a6c1a70ef1 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java @@ -18,13 +18,10 @@ package com.cloud.api.commands.netapp; import java.rmi.ServerException; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +32,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DissociateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class) +@APICommand(name = "dissociateLun", description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class) public class DissociateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DissociateLunCmd.class.getName()); private static final String s_name = "dissociatelunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java index 1101648219a..630b14994e7 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java @@ -21,12 +21,12 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +38,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListLunsCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List LUN", responseObject = ListLunsCmdResponse.class) +@APICommand(name = "listLunsOnFiler", description="List LUN", responseObject = ListLunsCmdResponse.class) public class ListLunsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListLunsCmd.class.getName()); diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java index e6467393386..d77f4fad849 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java @@ -21,10 +21,10 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -36,7 +36,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListVolumePoolsCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List Pool", responseObject = ListVolumePoolsCmdResponse.class) +@APICommand(name = "listPools", description="List Pool", responseObject = ListVolumePoolsCmdResponse.class) public class ListVolumePoolsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListVolumePoolsCmd.class.getName()); private static final String s_name = "listpoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java index 389053a36dc..66a96f3a221 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java @@ -19,14 +19,11 @@ package com.cloud.api.commands.netapp; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListVolumesOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class) +@APICommand(name = "listVolumesOnFiler", description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class) public class ListVolumesOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListVolumesOnFilerCmd.class.getName()); private static final String s_name = "listvolumesresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java index 0bca2901dc7..3e32caebef3 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ModifyVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class) +@APICommand(name = "modifyPool", description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class) public class ModifyVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ModifyVolumePoolCmd.class.getName()); private static final String s_name = "modifypoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java index af2e5755516..861bb3cc668 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="netapp_lun") -public class LunVO { +public class LunVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -85,7 +87,7 @@ public class LunVO { this.targetIqn = targetIqn; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java index 7dcb9d3d032..1fdd2502694 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappManagerImpl.java @@ -660,7 +660,7 @@ public class NetappManagerImpl implements NetappManager lun = _lunDao.persist(lun); //Lun id created: 6 digits right justified eg. 000045 - String lunIdStr = lun.getId().toString(); + String lunIdStr = String.valueOf(lun.getId()); String zeroStr = "000000"; int length = lunIdStr.length(); int offset = 6-length; diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java index 04318d00190..abcd20f8262 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="netapp_volume") -public class NetappVolumeVO { +public class NetappVolumeVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -132,7 +134,7 @@ public class NetappVolumeVO { this.volumeSize = volumeSize; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java index 713db46ee54..71e8342e620 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,9 +27,9 @@ import javax.persistence.Table; @Entity @Table(name="netapp_pool") -public class PoolVO { +public class PoolVO implements InternalIdentity { - public Long getId() { + public long getId() { return id; } diff --git a/plugins/hypervisors/kvm/pom.xml b/plugins/hypervisors/kvm/pom.xml index d3eca911a04..8fc8f739460 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -94,6 +94,24 @@ + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + + + copy-dependencies + package + + copy-dependencies + + + target/dependencies + runtime + + + + diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMGuestOsMapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMGuestOsMapper.java index b4771cacb10..bd1573c9fa9 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMGuestOsMapper.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/KVMGuestOsMapper.java @@ -91,6 +91,8 @@ public class KVMGuestOsMapper { s_mapper.put("Fedora 10", "Fedora 10"); s_mapper.put("Fedora 9", "Fedora 9"); s_mapper.put("Fedora 8", "Fedora 8"); + s_mapper.put("Ubuntu 12.04 (32-bit)", "Ubuntu 12.04"); + s_mapper.put("Ubuntu 12.04 (64-bit)", "Ubuntu 12.04"); s_mapper.put("Ubuntu 10.04 (32-bit)", "Ubuntu 10.04"); s_mapper.put("Ubuntu 10.04 (64-bit)", "Ubuntu 10.04"); s_mapper.put("Ubuntu 10.10 (32-bit)", "Ubuntu 10.10"); diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index b52e2d8a0b0..b65b53114bf 100755 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -162,6 +162,8 @@ import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; +import com.cloud.agent.api.storage.ResizeVolumeCommand; +import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.StorageFilerTO; @@ -255,6 +257,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements private String _patchdomrPath; private String _createvmPath; private String _manageSnapshotPath; + private String _resizeVolumePath; private String _createTmplPath; private String _heartBeatPath; private String _securityGroupPath; @@ -534,6 +537,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements "Unable to find the managesnapshot.sh"); } + _resizeVolumePath = Script.findScript(storageScriptsDir, "resizevolume.sh"); + if (_resizeVolumePath == null) { + throw new ConfigurationException( + "Unable to find the resizevolume.sh"); + } + _createTmplPath = Script .findScript(storageScriptsDir, "createtmplt.sh"); if (_createTmplPath == null) { @@ -1062,6 +1071,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements return execute((CleanupNetworkRulesCmd) cmd); } else if (cmd instanceof CopyVolumeCommand) { return execute((CopyVolumeCommand) cmd); + } else if (cmd instanceof ResizeVolumeCommand) { + return execute((ResizeVolumeCommand) cmd); } else if (cmd instanceof CheckNetworkCommand) { return execute((CheckNetworkCommand) cmd); } else { @@ -1268,6 +1279,72 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } + private String getResizeScriptType (KVMStoragePool pool, KVMPhysicalDisk vol) { + StoragePoolType poolType = pool.getType(); + PhysicalDiskFormat volFormat = vol.getFormat(); + + if(pool.getType() == StoragePoolType.CLVM && volFormat == KVMPhysicalDisk.PhysicalDiskFormat.RAW) { + return "CLVM"; + } else if ((poolType == StoragePoolType.NetworkFilesystem + || poolType == StoragePoolType.SharedMountPoint + || poolType == StoragePoolType.Filesystem) + && volFormat == KVMPhysicalDisk.PhysicalDiskFormat.QCOW2 ) { + return "QCOW2"; + } + return null; + } + + /* uses a local script now, eventually support for virStorageVolResize() will maybe work on + qcow2 and lvm and we can do this in libvirt calls */ + public Answer execute(ResizeVolumeCommand cmd) { + String volid = cmd.getPath(); + long newSize = cmd.getNewSize(); + long currentSize = cmd.getCurrentSize(); + String vmInstanceName = cmd.getInstanceName(); + boolean shrinkOk = cmd.getShrinkOk(); + StorageFilerTO spool = cmd.getPool(); + + try { + KVMStoragePool pool = _storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid()); + KVMPhysicalDisk vol = pool.getPhysicalDisk(volid); + String path = vol.getPath(); + String type = getResizeScriptType(pool, vol); + + if (type == null) { + return new ResizeVolumeAnswer(cmd, false, "Unsupported volume format: pool type '" + + pool.getType() + "' and volume format '" + vol.getFormat() + "'"); + } + + s_logger.debug("got to the stage where we execute the volume resize, params:" + + path + "," + currentSize + "," + newSize + "," + type + "," + vmInstanceName + "," + shrinkOk); + final Script resizecmd = new Script(_resizeVolumePath, + _cmdsTimeout, s_logger); + resizecmd.add("-s",String.valueOf(newSize)); + resizecmd.add("-c",String.valueOf(currentSize)); + resizecmd.add("-p",path); + resizecmd.add("-t",type); + resizecmd.add("-r",String.valueOf(shrinkOk)); + resizecmd.add("-v",vmInstanceName); + String result = resizecmd.execute(); + + if (result == null) { + + /* fetch new size as seen from libvirt, don't want to assume anything */ + pool = _storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid()); + long finalSize = pool.getPhysicalDisk(volid).getVirtualSize(); + s_logger.debug("after resize, size reports as " + finalSize + ", requested " + newSize); + return new ResizeVolumeAnswer(cmd, true, "success", finalSize); + } + + return new ResizeVolumeAnswer(cmd, false, result); + } catch (CloudRuntimeException e) { + String error = "failed to resize volume: " + e; + s_logger.debug(error); + return new ResizeVolumeAnswer(cmd, false, error); + } + + } + public Answer execute(DestroyCommand cmd) { VolumeTO vol = cmd.getVolume(); @@ -2901,9 +2978,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements NicTO[] nics = vmSpec.getNics(); for (NicTO nic : nics) { - if (nic.getIsolationUri() != null - && nic.getIsolationUri().getScheme() - .equalsIgnoreCase(IsolationType.Ec2.toString())) { + if (nic.isSecurityGroupEnabled() || ( nic.getIsolationUri() != null + && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString()))) { if (vmSpec.getType() != VirtualMachine.Type.User) { default_network_rules_for_systemvm(conn, vmName); break; diff --git a/plugins/hypervisors/simulator/pom.xml b/plugins/hypervisors/simulator/pom.xml index 15b37900590..a1ab9c08639 100644 --- a/plugins/hypervisors/simulator/pom.xml +++ b/plugins/hypervisors/simulator/pom.xml @@ -27,7 +27,6 @@ org.apache.cloudstack cloud-plugin-hypervisor-simulator - 4.1.0-SNAPSHOT Apache CloudStack Plugin - Hypervisor Simulator Simulator Hypervisor for Cloudstack @@ -42,4 +41,4 @@ ${project.version} - \ No newline at end of file + diff --git a/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java index 4f70ee5bae7..2bed2efec6a 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/SimulatorManagerImpl.java @@ -16,27 +16,12 @@ // under the License. package com.cloud.agent.manager; -import java.util.HashMap; -import java.util.Map; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - import com.cloud.agent.api.*; -import com.cloud.agent.api.storage.*; -import org.apache.log4j.Logger; - import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; -import com.cloud.agent.api.routing.DhcpEntryCommand; -import com.cloud.agent.api.routing.IpAssocCommand; -import com.cloud.agent.api.routing.LoadBalancerConfigCommand; -import com.cloud.agent.api.routing.SavePasswordCommand; -import com.cloud.agent.api.routing.SetFirewallRulesCommand; -import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; -import com.cloud.agent.api.routing.VmDataCommand; +import com.cloud.agent.api.routing.*; +import com.cloud.agent.api.storage.*; import com.cloud.simulator.MockConfigurationVO; import com.cloud.simulator.MockHost; import com.cloud.simulator.MockVMVO; @@ -49,6 +34,12 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine.State; +import org.apache.log4j.Logger; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; +import java.util.HashMap; +import java.util.Map; @Local(value = { SimulatorManager.class }) public class SimulatorManagerImpl implements SimulatorManager { @@ -112,14 +103,12 @@ public class SimulatorManagerImpl implements SimulatorManager { @Override public Answer simulate(Command cmd, String hostGuid) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); - // txn.transitToUserManagedConnection(_concierge.conn()); - try { MockHost host = _mockHost.findByGuid(hostGuid); String cmdName = cmd.toString(); int index = cmdName.lastIndexOf("."); if (index != -1) { - cmdName = cmdName.substring(index + 1); + cmdName = cmdName.substring(index + 1); } MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), cmdName); @@ -129,24 +118,24 @@ public class SimulatorManagerImpl implements SimulatorManager { if (config != null) { Map configParameters = config.getParameters(); for (Map.Entry entry : configParameters.entrySet()) { - if (entry.getKey().equalsIgnoreCase("enabled")) { - info.setEnabled(Boolean.parseBoolean(entry.getValue())); - } else if (entry.getKey().equalsIgnoreCase("timeout")) { - try { - info.setTimeout(Integer.valueOf(entry.getValue())); - } catch (NumberFormatException e) { - s_logger.debug("invalid timeout parameter: " + e.toString()); - } - } else if (entry.getKey().equalsIgnoreCase("wait")) { - try { - int wait = Integer.valueOf(entry.getValue()); - Thread.sleep(wait * 1000); - } catch (NumberFormatException e) { - s_logger.debug("invalid timeout parameter: " + e.toString()); - } catch (InterruptedException e) { - s_logger.debug("thread is interrupted: " + e.toString()); - } - } + if (entry.getKey().equalsIgnoreCase("enabled")) { + info.setEnabled(Boolean.parseBoolean(entry.getValue())); + } else if (entry.getKey().equalsIgnoreCase("timeout")) { + try { + info.setTimeout(Integer.valueOf(entry.getValue())); + } catch (NumberFormatException e) { + s_logger.debug("invalid timeout parameter: " + e.toString()); + } + } else if (entry.getKey().equalsIgnoreCase("wait")) { + try { + int wait = Integer.valueOf(entry.getValue()); + Thread.sleep(wait); + } catch (NumberFormatException e) { + s_logger.debug("invalid timeout parameter: " + e.toString()); + } catch (InterruptedException e) { + s_logger.debug("thread is interrupted: " + e.toString()); + } + } } } diff --git a/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java index 60ce82e2c05..df81249538d 100755 --- a/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java +++ b/plugins/hypervisors/simulator/src/com/cloud/api/commands/ConfigureSimulator.java @@ -19,12 +19,12 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; import com.cloud.agent.manager.SimulatorManager; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="configure simulator", responseObject=SuccessResponse.class) +@APICommand(name = "configureSimulator", description="configure simulator", responseObject=SuccessResponse.class) public class ConfigureSimulator extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ConfigureSimulator.class.getName()); private static final String s_name = "configuresimulatorresponse"; diff --git a/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java index 35aa3010005..c639a556cb7 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java @@ -17,16 +17,17 @@ package com.cloud.server; +import com.cloud.api.commands.ConfigureSimulator; +import com.cloud.utils.PropertiesUtil; + +import java.util.List; +import java.util.Map; + public class ManagementServerSimulatorImpl extends ManagementServerExtImpl { @Override - public String[] getApiConfig() { - String[] apis = super.getApiConfig(); - String[] newapis = new String[apis.length + 1]; - for (int i = 0; i < apis.length; i++) { - newapis[i] = apis[i]; - } - - newapis[apis.length] = "commands-simulator.properties"; - return newapis; + public List> getCommands() { + List> cmdList = super.getCommands(); + cmdList.add(ConfigureSimulator.class); + return cmdList; } } diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java index 3ed862bb69f..5959347e6dd 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.HashMap; import java.util.Map; @@ -28,7 +30,7 @@ import javax.persistence.Table; @Entity @Table(name="mockconfiguration") -public class MockConfigurationVO { +public class MockConfigurationVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java index c86dfa6a2bf..0242135abbc 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name="mockhost") -public class MockHostVO implements MockHost { +public class MockHostVO implements MockHost, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java index 59a81c79abe..2352687ba9f 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name="mocksecstorage") -public class MockSecStorageVO { +public class MockSecStorageVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java index df31fbf277b..d0d77c969ac 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name="mocksecurityrules") -public class MockSecurityRulesVO { +public class MockSecurityRulesVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java index 9c6e84d2714..c8f068a9e29 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java @@ -26,11 +26,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.storage.Storage.StoragePoolType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockstoragepool") -public class MockStoragePoolVO { +public class MockStoragePoolVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java index 3a5aa3d4c10..292f20031c3 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java @@ -24,11 +24,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockvm") -public class MockVMVO implements MockVm{ +public class MockVMVO implements MockVm, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java index 48a12f8ee93..fe337e793f2 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java @@ -27,12 +27,13 @@ import javax.persistence.Table; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockvolume") -public class MockVolumeVO { +public class MockVolumeVO implements InternalIdentity { public enum MockVolumeType { VOLUME, TEMPLATE, diff --git a/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java index 9891bc82556..9f24bbd0cfc 100644 --- a/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/SimulatorRuntimeException.java @@ -18,12 +18,12 @@ package com.cloud.simulator; import com.cloud.utils.SerialVersionUID; -import com.cloud.utils.exception.RuntimeCloudException; +import com.cloud.utils.exception.CloudRuntimeException; /** * wrap exceptions that you know there's no point in dealing with. */ -public class SimulatorRuntimeException extends RuntimeCloudException { +public class SimulatorRuntimeException extends CloudRuntimeException { private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException; diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java index 601ec9d6f4d..3e45ce2a084 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java @@ -19,14 +19,14 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,9 +34,8 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.element.CiscoNexusVSMElementService; import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(responseObject=SuccessResponse.class, description=" delete a Cisco Nexus VSM device") +@APICommand(name = "deleteCiscoNexusVSM", responseObject=SuccessResponse.class, description=" delete a Cisco Nexus VSM device") public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteCiscoNexusVSMCmd.class.getName()); @@ -47,8 +46,8 @@ public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java index 5f911f45c8e..9a7f6ada97c 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java @@ -19,13 +19,12 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -36,7 +35,7 @@ import com.cloud.event.EventTypes; import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.network.CiscoNexusVSMDevice; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="disable a Cisco Nexus VSM device") +@APICommand(name = "disableCiscoNexusVSM", responseObject=CiscoNexusVSMResponse.class, description="disable a Cisco Nexus VSM device") public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisableCiscoNexusVSMCmd.class.getName()); @@ -47,8 +46,8 @@ public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java index 67c0ae3aba4..5dc67212fd3 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java @@ -17,15 +17,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -36,7 +31,7 @@ import com.cloud.user.Account; import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.network.CiscoNexusVSMDevice; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="Enable a Cisco Nexus VSM device") +@APICommand(name = "enableCiscoNexusVSM", responseObject=CiscoNexusVSMResponse.class, description="Enable a Cisco Nexus VSM device") public class EnableCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(EnableCiscoNexusVSMCmd.class.getName()); @@ -47,8 +42,8 @@ public class EnableCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be enabled") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be enabled") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java index bd25258b546..ee6a01bdb8a 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java @@ -17,16 +17,17 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.CiscoNexusVSMResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -38,7 +39,7 @@ import com.cloud.user.Account; import java.util.ArrayList; import java.util.List; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="Retrieves a Cisco Nexus 1000v Virtual Switch Manager device associated with a Cluster") +@APICommand(name = "listCiscoNexusVSMs", responseObject=CiscoNexusVSMResponse.class, description="Retrieves a Cisco Nexus 1000v Virtual Switch Manager device associated with a Cluster") public class ListCiscoNexusVSMsCmd extends BaseListCmd { /** @@ -56,12 +57,12 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long clusterId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java b/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java index e0169d3c8e3..25a824e5796 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java @@ -16,27 +16,29 @@ // under the License. package com.cloud.api.response; -import javax.persistence.Column; - -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.CiscoNexusVSMDevice; + +@EntityReference(value=CiscoNexusVSMDevice.class) public class CiscoNexusVSMResponse extends BaseResponse { @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_ID) @Param(description="device id of the Cisco N1KV VSM device") - private IdentityProxy id = new IdentityProxy("virtual_supervisor_module"); - + private String id; + @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_NAME) @Param(description="device name") private String deviceName; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external Cisco Nexus 1000v Virtual Supervisor Module") private String vsmmgmtIpAddress; - + @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_STATE) @Param(description="device state") private String deviceState; - + @SerializedName(ApiConstants.VSM_MGMT_VLAN_ID) @Param(description="management vlan id of the VSM") private String vsmmgmtvlanid; @@ -48,22 +50,22 @@ public class CiscoNexusVSMResponse extends BaseResponse { @SerializedName(ApiConstants.VSM_STORAGE_VLAN_ID) @Param(description="storage vlan id of the VSM") private int vsmstoragevlanid; - + @SerializedName(ApiConstants.VSM_DOMAIN_ID) @Param(description="The VSM is a switch supervisor. This is the VSM's switch domain id") private String vsmdomainid; - + @SerializedName(ApiConstants.VSM_CONFIG_MODE) @Param(description="The mode of the VSM (standalone/HA)") private String vsmconfigmode; - + @SerializedName(ApiConstants.VSM_CONFIG_STATE) @Param(description="The Config State (Primary/Standby) of the VSM") private String vsmconfigstate; - + @SerializedName(ApiConstants.VSM_DEVICE_STATE) @Param(description="The Device State (Enabled/Disabled) of the VSM") private String vsmdevicestate; // Setter methods. - public void setId(long vsmDeviceId) { - this.id.setValue(vsmDeviceId); + public void setId(String vsmDeviceId) { + this.id = vsmDeviceId; } public void setDeviceName(String deviceName) { @@ -73,39 +75,39 @@ public class CiscoNexusVSMResponse extends BaseResponse { public void setMgmtIpAddress(String ipAddress) { this.vsmmgmtIpAddress = ipAddress; } - + public void setDeviceState(String deviceState) { this.deviceState = deviceState; } - + public void setVSMMgmtVlanId(String vlanId) { this.vsmmgmtvlanid = vlanId; } - + public void setVSMCtrlVlanId(int vlanId) { this.vsmctrlvlanid = vlanId; } - + public void setVSMPktVlanId(int vlanId) { this.vsmpktvlanid = vlanId; } - + public void setVSMStorageVlanId(int vlanId) { this.vsmstoragevlanid = vlanId; } - + public void setVSMDomainId(String domId) { this.vsmdomainid = domId; } - + public void setVSMConfigMode(String configMode) { this.vsmconfigmode = configMode; } - + public void setVSMConfigState(String configState) { this.vsmconfigstate = configState; } - + public void setVSMDeviceState(String devState) { this.vsmdevicestate = devState; } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 0b0f285a960..a444cfec197 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -3705,10 +3705,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, 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 (dskch.getType() == Volume.Type.ROOT) { + // attach volume id to make the name unique + String vmdkName = dskch.getName() + "-" + dskch.getVolumeId(); if (cmd.getTemplateUrl() == null) { // create a root volume for blank VM String dummyVmName = getWorkerName(context, cmd, 0); @@ -3720,16 +3722,15 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Unable to create a dummy VM for volume creation"); } - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getDiskCharacteristics().getName()); + String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName); 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); + VmwareHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo); + vmMo.createDisk(volumeDatastorePath, (int) (dskch.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); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); @@ -3753,41 +3754,40 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa 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); + if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) + dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("create linked clone from template"); - if (!vmTemplate.createLinkedClone(name, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { + if (!vmTemplate.createLinkedClone(vmdkName, 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); + VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName); 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 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(), - String.format("[%s] %s.vmdk", dsMo.getName(), name), dcMo.getMor(), true); + dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), + dcMo.getMor(), dsMo.getMor(), + String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); - 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); + dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), + dcMo.getMor(), dsMo.getMor(), + String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); - s_logger.info("detach disks from volume-wrapper VM " + name); + s_logger.info("detach disks from volume-wrapper VM " + vmdkName); vmMo.detachAllDisks(); - s_logger.info("destroy volume-wrapper VM " + name); + s_logger.info("destroy volume-wrapper VM " + vmdkName); vmMo.destroy(); - String srcFile = String.format("[%s] %s/", dsMo.getName(), name); + String srcFile = String.format("[%s] %s/", dsMo.getName(), vmdkName); 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); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } } else { @@ -3806,12 +3806,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // 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.createDisk(volumeDatastorePath, (int) (dskch.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); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java index c58a6a77a77..19da27116de 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java @@ -16,57 +16,58 @@ // under the License. package com.cloud.network; -public interface CiscoNexusVSMDevice { - +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface CiscoNexusVSMDevice extends InternalIdentity, Identity { + // This tells us whether the VSM is currently enabled or disabled. We may // need this if we would like to carry out any sort of maintenance on the // VSM or CS. public enum VSMDeviceState { Enabled, Disabled - } - + } + // This tells us whether the VSM is currently configured with a standby (HA) // or does not have any standby (Standalone). public enum VSMConfigMode { Standalone, HA } - + // This tells us whether the VSM is currently a primary or a standby VSM. public enum VSMConfigState { Primary, Standby } - long getId(); - public String getvsmName(); - + public long getHostId(); - + public String getUserName(); - + public String getPassword(); public String getipaddr(); - + public int getManagementVlan(); - + public int getControlVlan(); - + public int getPacketVlan(); public int getStorageVlan(); - + public long getvsmDomainId(); - + public VSMConfigMode getvsmConfigMode(); - + public VSMConfigState getvsmConfigState(); - + public VSMDeviceState getvsmDeviceState(); - + public String getUuid(); - + } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java index 05214f5c912..528075ea41a 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java @@ -11,20 +11,16 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network; -import java.util.HashMap; - import java.util.List; -import java.util.Map; import org.apache.log4j.Logger; import com.cloud.agent.api.StartupCommand; -import com.cloud.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterDetailsDao; @@ -33,7 +29,6 @@ import com.cloud.dc.ClusterVSMMapVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.ClusterVSMMapDao; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDetailsDao; @@ -53,7 +48,7 @@ import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { @Inject - CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao; + CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao; @Inject ClusterDao _clusterDao; @Inject @@ -70,9 +65,9 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { PortProfileDao _ppDao; @Inject ConfigurationDao _configDao; - + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class); - + @DB //public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) { public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) { @@ -82,7 +77,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { // First check if the cluster is of type vmware. If not, // throw an exception. VSMs are tightly integrated with vmware clusters. - + ClusterVO cluster = _clusterDao.findById(clusterId); if (cluster == null) { throw new InvalidParameterValueException("Cluster with specified ID not found!"); @@ -95,21 +90,21 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { // Next, check if the cluster already has a VSM associated with it. // If so, throw an exception disallowing this operation. The user must first // delete the current VSM and then only attempt to add the new one. - + if (_clusterVSMDao.findByClusterId(clusterId) != null) { // We can't have two VSMs for the same cluster. Throw exception. throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation."); } // TODO: Confirm whether we should be checking for VSM reachability here. - + // Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to // the VSM. //NetconfHelper (String ip, String username, String password) NetconfHelper netconfClient; try { - netconfClient = new NetconfHelper(ipaddress, username, password); + netconfClient = new NetconfHelper(ipaddress, username, password); } catch(CloudRuntimeException e) { String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username; s_logger.error(msg); @@ -123,7 +118,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { // First, check if VSM already exists in the table "virtual_supervisor_module". // If it's not there already, create it. // If it's there already, return success. - + // TODO - Right now, we only check if the ipaddress matches for both requests. // We must really check whether every field of the VSM matches. Anyway, the // advantage of our approach for now is that existing infrastructure using @@ -136,7 +131,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { throw new CloudRuntimeException(e.getMessage()); } - if (VSMObj == null) { + if (VSMObj == null) { // Create the VSM record. For now, we aren't using the vsmName field. VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password); Transaction txn = Transaction.currentTxn(); @@ -149,7 +144,7 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { throw new CloudRuntimeException(e.getMessage()); } } - + // At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id. long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId(); ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId); @@ -162,22 +157,22 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { txn.rollback(); throw new CloudRuntimeException(e.getMessage()); } - + // Now, get a list of all the ESXi servers in this cluster. // This is effectively a select * from host where cluster_id=clusterId; // All ESXi servers are stored in the host table, and their resource // type is vmwareresource. - + //List hosts = _resourceMgr.listAllHostsInCluster(clusterId); - + //TODO: Activate the code below if we make the Nexus VSM a separate resource. // Iterate through each of the hosts in this list. Each host has a host id. // Given this host id, we can reconfigure the in-memory resource representing // the host via the agent manager. Thus we inject VSM related information // into each host's resource. Also, we first configure each resource's // entries in the database to contain this VSM information before the injection. - - //for (HostVO host : hosts) { + + //for (HostVO host : hosts) { // Create a host details VO object and write it out for this hostid. //Long hostid = new Long(vsmId); //DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString()); @@ -198,28 +193,28 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { //hostDetails.put(ApiConstants.USERNAME, username); //hostDetails.put(ApiConstants.PASSWORD, password); //_agentMrg.send(host.getId(), ) - + return VSMObj; - + } - + @DB - public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException { + public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { // This entry is already not present. Return success. return true; } - + // First, check whether this VSM is part of any non-empty cluster. // Search ClusterVSMMap's table for a list of clusters using this vsmId. - + List clusterList = _clusterVSMDao.listByVSMId(vsmId); - - if (clusterList != null) { + + if (clusterList != null) { for (ClusterVSMMapVO record : clusterList) { // If this cluster id has any hosts in it, fail this operation. - Long clusterId = record.getClusterId(); + Long clusterId = record.getClusterId(); List hosts = _resourceMgr.listAllHostsInCluster(clusterId); if (hosts != null && hosts.size() > 0) { for (Host host: hosts) { @@ -227,26 +222,26 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first"); } - } + } } } } - + // Iterate through the cluster list again, this time, delete the VSM. Transaction txn = Transaction.currentTxn(); try { txn.start(); - // Remove the VSM entry in CiscoNexusVSMDeviceVO's table. + // Remove the VSM entry in CiscoNexusVSMDeviceVO's table. _ciscoNexusVSMDeviceDao.remove(vsmId); - // Remove the current record as well from ClusterVSMMapVO's table. + // Remove the current record as well from ClusterVSMMapVO's table. _clusterVSMDao.removeByVsmId(vsmId); // There are no hosts at this stage in the cluster, so we don't need - // to notify any resources or remove host details. - txn.commit(); + // to notify any resources or remove host details. + txn.commit(); } catch (Exception e) { - s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage()); + s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage()); throw new CloudRuntimeException("Failed to delete VSM"); - } + } return true; } @@ -254,10 +249,10 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { - throw new InvalidParameterValueException("Invalid vsm Id specified"); + throw new InvalidParameterValueException("Invalid vsm Id specified"); } // Else, check if this db record shows that this VSM is enabled or not. - if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) { + if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) { // it's currently disabled. So change it to enabled and write it out to the db. cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled); Transaction txn = Transaction.currentTxn(); @@ -270,18 +265,18 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { throw new CloudRuntimeException(e.getMessage()); } } - + return cisconexusvsm; } - - @DB + + @DB public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) { CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId); if (cisconexusvsm == null) { - throw new InvalidParameterValueException("Invalid vsm Id specified"); + throw new InvalidParameterValueException("Invalid vsm Id specified"); } // Else, check if this db record shows that this VSM is enabled or not. - if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) { + if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) { // it's currently disabled. So change it to enabled and write it out to the db. cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled); Transaction txn = Transaction.currentTxn(); @@ -294,15 +289,15 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { throw new CloudRuntimeException(e.getMessage()); } } - + return cisconexusvsm; } - + @DB public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) { return _ciscoNexusVSMDeviceDao.findById(vsmId); } - + @DB public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) { ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId); @@ -314,12 +309,12 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId()); return result; } - + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { // TODO Auto-generated method stub return null; } - + @DB public boolean vliadateVsmCluster(String vsmIp, String vsmUser, String vsmPassword, long clusterId, String clusterName) throws ResourceInUseException { // Check if we're associating a Cisco Nexus VSM with a vmware cluster. @@ -347,7 +342,9 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase { s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster"); _clusterDao.remove(clusterId); ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id"); - ex.addProxyObject("cluster", clusterList.get(0).getClusterId(), "clusterId"); + // get clusterUuid to report error + ClusterVO cluster = _clusterDao.findById(clusterList.get(0).getClusterId()); + ex.addProxyObject(cluster.getUuid()); throw ex; } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java index af9ff0e1d7c..d24f15def97 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java @@ -26,8 +26,9 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.api.InternalIdentity; /** * CiscoNexusVSMDeviceVO contains information on external Cisco Nexus 1000v VSM devices added into a deployment. @@ -37,7 +38,7 @@ import com.cloud.utils.db.Encrypt; @Entity @Table(name="virtual_supervisor_module") -public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ +public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { // We need to know what properties a VSM has. Put them here. @@ -133,7 +134,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ @Override public int getPacketVlan() { return packetVlan; - } + } @Override public int getStorageVlan() { @@ -197,7 +198,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ public void setPacketVlan(int vlan) { this.packetVlan = vlan; - } + } public void setStorageVlan(int vlan) { this.storageVlan = vlan; @@ -222,7 +223,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ // Constructors. - public CiscoNexusVSMDeviceVO(String vsmIpAddr, String username, String password) { + public CiscoNexusVSMDeviceVO(String vsmIpAddr, String username, String password) { // Set all the VSM's properties here. this.uuid = UUID.randomUUID().toString(); this.setMgmtIpAddr(vsmIpAddr); @@ -234,5 +235,5 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ public CiscoNexusVSMDeviceVO() { this.uuid = UUID.randomUUID().toString(); - } + } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java index bdb235dc761..68388a6fb18 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java @@ -17,6 +17,8 @@ package com.cloud.network.element; +import java.lang.Class; +import java.lang.String; import java.util.List; import java.util.Map; import java.util.ArrayList; @@ -24,6 +26,7 @@ import java.util.Set; import javax.ejb.Local; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import com.cloud.api.commands.DeleteCiscoNexusVSMCmd; @@ -51,7 +54,6 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -import com.cloud.network.element.NetworkElement; import com.cloud.offering.NetworkOffering; import com.cloud.org.Cluster; import com.cloud.utils.component.Manager; @@ -65,18 +67,18 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme private static final Logger s_logger = Logger.getLogger(CiscoNexusVSMElement.class); @Inject - CiscoNexusVSMDeviceDao _vsmDao; + CiscoNexusVSMDeviceDao _vsmDao; @Override public Map> getCapabilities() { return null; } - + @Override public Provider getProvider() { return null; } - + @Override public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) @@ -84,7 +86,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme InsufficientCapacityException { return true; } - + @Override public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, @@ -93,7 +95,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme InsufficientCapacityException { return true; } - + @Override public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, @@ -101,7 +103,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme ResourceUnavailableException { return true; } - + @Override public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, @@ -114,7 +116,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme throws ConcurrentOperationException, ResourceUnavailableException { return true; } - + @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { return true; @@ -126,19 +128,19 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme ResourceUnavailableException { return true; } - + @Override public boolean canEnableIndividualServices() { return true; } - + @Override public boolean verifyServicesCombination(Set services) { return true; } @Override - @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DELETE, eventDescription = "deleting VSM", async = true) + @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DELETE, eventDescription = "deleting VSM", async = true) public boolean deleteCiscoNexusVSM(DeleteCiscoNexusVSMCmd cmd) { boolean result; try { @@ -149,16 +151,16 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme throw new CloudRuntimeException("Failed to delete specified VSM"); } return result; - } + } @Override - @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ENABLE, eventDescription = "deleting VSM", async = true) + @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ENABLE, eventDescription = "deleting VSM", async = true) public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(EnableCiscoNexusVSMCmd cmd) { CiscoNexusVSMDeviceVO result; result = enableCiscoNexusVSM(cmd.getCiscoNexusVSMDeviceId()); return result; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DISABLE, eventDescription = "deleting VSM", async = true) public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(DisableCiscoNexusVSMCmd cmd) { @@ -166,16 +168,16 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme result = disableCiscoNexusVSM(cmd.getCiscoNexusVSMDeviceId()); return result; } - + @Override public List getCiscoNexusVSMs(ListCiscoNexusVSMsCmd cmd) { // If clusterId is defined, then it takes precedence, and we will return - // the VSM associated with this cluster. + // the VSM associated with this cluster. Long clusterId = cmd.getClusterId(); Long zoneId = cmd.getZoneId(); List result = new ArrayList(); - if (clusterId != null && clusterId.longValue() != 0) { + if (clusterId != null && clusterId.longValue() != 0) { // Find the VSM associated with this clusterId and return a list. CiscoNexusVSMDeviceVO vsm = getCiscoVSMbyClusId(cmd.getClusterId()); if (vsm == null) { @@ -184,13 +186,13 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme // Else, add it to a list and return the list. result.add(vsm); return result; - } + } // Else if there is only a zoneId defined, get a list of all vmware clusters // in the zone, and then for each cluster, pull the VSM and prepare a list. if (zoneId != null && zoneId.longValue() != 0) { - ManagementService ref = cmd.getMgmtServiceRef(); + ManagementService ref = cmd.getMgmtServiceRef(); List clusterList = ref.searchForClusters(zoneId, cmd.getStartIndex(), cmd.getPageSizeVal(), "VMware"); - + if (clusterList.size() == 0) { throw new CloudRuntimeException("No VMWare clusters found in the specified zone!"); } @@ -202,27 +204,27 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme } return result; } - + // If neither is defined, we will simply return the entire list of VSMs // configured in the management server. // TODO: Is this a safe thing to do? Only ROOT admin can invoke this call. - result = _vsmDao.listAllVSMs(); + result = _vsmDao.listAllVSMs(); return result; } - + @Override public CiscoNexusVSMResponse createCiscoNexusVSMResponse(CiscoNexusVSMDevice vsmDeviceVO) { CiscoNexusVSMResponse response = new CiscoNexusVSMResponse(); - response.setId(vsmDeviceVO.getId()); + response.setId(vsmDeviceVO.getUuid()); response.setMgmtIpAddress(vsmDeviceVO.getipaddr()); return response; } - + public CiscoNexusVSMResponse createCiscoNexusVSMDetailedResponse(CiscoNexusVSMDevice vsmDeviceVO) { CiscoNexusVSMResponse response = new CiscoNexusVSMResponse(); - response.setId(vsmDeviceVO.getId()); + response.setId(vsmDeviceVO.getUuid()); response.setDeviceName(vsmDeviceVO.getvsmName()); - response.setDeviceState(vsmDeviceVO.getvsmDeviceState().toString()); + response.setDeviceState(vsmDeviceVO.getvsmDeviceState().toString()); response.setMgmtIpAddress(vsmDeviceVO.getipaddr()); // The following values can be null, so check for that. if(vsmDeviceVO.getvsmConfigMode() != null) @@ -238,7 +240,12 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme } @Override - public String getPropertiesFile() { - return "cisconexusvsm_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(ListCiscoNexusVSMsCmd.class); + cmdList.add(EnableCiscoNexusVSMCmd.class); + cmdList.add(DisableCiscoNexusVSMCmd.class); + cmdList.add(DeleteCiscoNexusVSMCmd.class); + return cmdList; } } diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java index 36a12b1b4fa..065d3be0bdd 100644 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java @@ -182,6 +182,8 @@ import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; +import com.cloud.agent.api.storage.ResizeVolumeCommand; +import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; @@ -468,6 +470,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return execute((DeleteStoragePoolCommand) cmd); } else if (clazz == CopyVolumeCommand.class) { return execute((CopyVolumeCommand) cmd); + } else if (clazz == ResizeVolumeCommand.class) { + return execute((ResizeVolumeCommand) cmd); } else if (clazz == AttachVolumeCommand.class) { return execute((AttachVolumeCommand) cmd); } else if (clazz == AttachIsoCommand.class) { @@ -1324,7 +1328,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe NicTO[] nics = vmSpec.getNics(); boolean secGrpEnabled = false; for (NicTO nic : nics) { - if (nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { + if (nic.isSecurityGroupEnabled() || (nic.getIsolationUri() != null + && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString()))) { secGrpEnabled = true; break; } @@ -1342,7 +1347,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe //For user vm, program the rules for each nic if the isolation uri scheme is ec2 NicTO[] nics = vmSpec.getNics(); for (NicTO nic : nics) { - if (nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { + if ( nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null + && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { result = callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", Long.toString(vmSpec.getId())); if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) { @@ -5616,6 +5622,23 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } } + public Answer execute(ResizeVolumeCommand cmd) { + Connection conn = getConnection(); + StorageFilerTO pool = cmd.getPool(); + String volid = cmd.getPath(); + long newSize = cmd.getNewSize(); + + try { + VDI vdi = getVDIbyUuid(conn, volid); + vdi.resize(conn, newSize); + return new ResizeVolumeAnswer(cmd, true, "success", newSize); + } catch (Exception e) { + s_logger.warn("Unable to resize volume",e); + String error = "failed to resize volume:" +e; + return new ResizeVolumeAnswer(cmd, false, error ); + } + } + protected SR getISOSRbyVmName(Connection conn, String vmName) { try { Set srs = SR.getByNameLabel(conn, vmName + "-ISO"); @@ -7682,4 +7705,5 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe return new SetStaticRouteAnswer(cmd, false, null); } } + } diff --git a/plugins/network-elements/dns-notifier/pom.xml b/plugins/network-elements/dns-notifier/pom.xml index 0b4c981af98..ea35d788653 100644 --- a/plugins/network-elements/dns-notifier/pom.xml +++ b/plugins/network-elements/dns-notifier/pom.xml @@ -27,8 +27,7 @@ org.apache.cloudstack cloud-plugin-example-dns-notifier - 4.1.0-SNAPSHOT - CloudStack Dns Notifier Example + Apache CloudStack Plugin - Dns Notifier Example This is sample source code on how to write a plugin for CloudStack install diff --git a/plugins/network-elements/dns-notifier/resources/components-example.xml b/plugins/network-elements/dns-notifier/resources/components-example.xml index 592b01c3d2a..412da0e289e 100755 --- a/plugins/network-elements/dns-notifier/resources/components-example.xml +++ b/plugins/network-elements/dns-notifier/resources/components-example.xml @@ -127,7 +127,7 @@ under the License. - + diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java index 024dcdc09e0..44b98eb2973 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java @@ -29,13 +29,14 @@ import javax.persistence.SecondaryTables; import javax.persistence.Table; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("elastic_lb_vm_map")) @SecondaryTables({ @SecondaryTable(name = "user_ip_address", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "ip_addr_id", referencedColumnName = "id") }) }) -public class ElasticLbVmMapVO { +public class ElasticLbVmMapVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -66,7 +67,7 @@ public class ElasticLbVmMapVO { this.lbId = lbId; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java index 0dc5b14a1a5..aea795d436f 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java @@ -18,7 +18,7 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index 6481d7fa86f..82c6120f266 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -32,6 +32,7 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -46,7 +47,6 @@ import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -299,7 +299,7 @@ ElasticLoadBalancerManager, Manager, VirtualMachineGuru { int srcPort = rule.getSourcePortStart(); String uuid = rule.getUuid(); List destinations = rule.getDestinations(); - LoadBalancerTO lb = new LoadBalancerTO(uuid, elbIp, srcPort, protocol, algorithm, revoked, false, destinations); + LoadBalancerTO lb = new LoadBalancerTO(uuid, elbIp, srcPort, protocol, algorithm, revoked, false, false, destinations); lbs[i++] = lb; } diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java index 3fa61167efa..69a21fc184c 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java @@ -17,23 +17,23 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.user.Account; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds F5 external load balancer appliance.", responseObject = ExternalLoadBalancerResponse.class) +@APICommand(name = "addExternalLoadBalancer", description="Adds F5 external load balancer appliance.", responseObject = ExternalLoadBalancerResponse.class) @Deprecated // API supported only for backward compatibility. public class AddExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddExternalLoadBalancerCmd.class.getName()); @@ -43,8 +43,8 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external load balancer appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external load balancer appliance.") private Long zoneId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external load balancer appliance.") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java index 13c443e7cf0..a5616e0ee73 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java @@ -17,16 +17,11 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +34,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="Adds a F5 BigIP load balancer device") +@APICommand(name = "addF5LoadBalancer", responseObject=F5LoadBalancerResponse.class, description="Adds a F5 BigIP load balancer device") public class AddF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddF5LoadBalancerCmd.class.getName()); @@ -50,8 +45,8 @@ public class AddF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the F5 load balancer appliance.") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java index 9f5217c3280..e796b57cc41 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java @@ -17,16 +17,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +33,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="configures a F5 load balancer device") +@APICommand(name = "configureF5LoadBalancer", responseObject=F5LoadBalancerResponse.class, description="configures a F5 load balancer device") public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureF5LoadBalancerCmd.class.getName()); @@ -50,8 +44,8 @@ public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="F5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required=true, description="F5 load balancer device ID") private Long lbDeviceId; @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the device, Capacity will be interpreted as number of networks device can handle") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java index 2c89a4a6a9d..d3015712596 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java @@ -17,21 +17,17 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.Account; -@Implementation(description="Deletes a F5 external load balancer appliance added in a zone.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteExternalLoadBalancer", description="Deletes a F5 external load balancer appliance added in a zone.", responseObject = SuccessResponse.class) @Deprecated // API supported for backward compatibility. public class DeleteExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteExternalLoadBalancerCmd.class.getName()); @@ -41,8 +37,8 @@ public class DeleteExternalLoadBalancerCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the external loadbalancer appliance.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the external loadbalancer appliance.") private Long id; /////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java index 959819b1588..8b53d70f76d 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java @@ -19,16 +19,16 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCmd; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -39,7 +39,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a F5 load balancer device") +@APICommand(name = "deleteF5LoadBalancer", responseObject=SuccessResponse.class, description=" delete a F5 load balancer device") public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteF5LoadBalancerCmd.class.getName()); private static final String s_name = "deletef5loadbalancerresponse"; @@ -49,8 +49,8 @@ public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required=true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java index acb71b06c0a..72313aa0c0c 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java @@ -20,21 +20,18 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.host.Host; import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; -@Implementation(description="Lists F5 external load balancer appliances added in a zone.", responseObject = HostResponse.class) +@APICommand(name = "listExternalLoadBalancers", description="Lists F5 external load balancer appliances added in a zone.", responseObject = HostResponse.class) @Deprecated // API supported for backward compatibility. public class ListExternalLoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListExternalLoadBalancersCmd.class.getName()); @@ -44,8 +41,8 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="zone Id") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java index f2fa071b53e..bf1164b4d05 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java @@ -22,16 +22,16 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +41,7 @@ import com.cloud.network.Network; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a F5 load balancer device") +@APICommand(name = "listF5LoadBalancerNetworks", responseObject=NetworkResponse.class, description="lists network that are using a F5 load balancer device") public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancerNetworksCmd.class.getName()); @@ -52,8 +52,8 @@ public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="f5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required = true, description="f5 load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java index fe4cb67bd01..c03d55abc0a 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java @@ -20,18 +20,13 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +36,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="lists F5 load balancer devices") +@APICommand(name = "listF5LoadBalancers", responseObject=F5LoadBalancerResponse.class, description="lists F5 load balancer devices") public class ListF5LoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancersCmd.class.getName()); private static final String s_name = "listf5loadbalancerresponse"; @@ -51,12 +46,12 @@ public class ListF5LoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, description="f5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + description="f5 load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java b/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java index dbb962fff03..19e67260b90 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java +++ b/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java @@ -16,24 +16,27 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalLoadBalancerDeviceVO; +@EntityReference(value=ExternalLoadBalancerDeviceVO.class) public class F5LoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_ID) @Param(description="device id of the F5 load balancer") - private IdentityProxy id = new IdentityProxy("external_load_balancer_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this F5 device belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -43,24 +46,21 @@ public class F5LoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) @Param(description="true if device is dedicated for an account") private Boolean dedicatedLoadBalancer; - @SerializedName(ApiConstants.INLINE) @Param(description="true if device is inline with firewall device") - private Boolean inlineLoadBalancer; - @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the load balancer") private String privateInterface; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external load balancer") private String ipAddress; - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { @@ -83,10 +83,6 @@ public class F5LoadBalancerResponse extends BaseResponse { this.dedicatedLoadBalancer = isDedicated; } - public void setInlineMode(boolean inline) { - this.inlineLoadBalancer = inline; - } - public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java index 4c557cc5d46..2e6f6e7a517 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElement.java @@ -11,11 +11,13 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network.element; +import java.lang.Class; +import java.lang.String; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -24,8 +26,10 @@ import java.util.Set; import javax.ejb.Local; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddExternalLoadBalancerCmd; import com.cloud.api.commands.AddF5LoadBalancerCmd; import com.cloud.api.commands.ConfigureF5LoadBalancerCmd; @@ -55,7 +59,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -64,6 +68,7 @@ import com.cloud.network.NetworkExternalLoadBalancerVO; import com.cloud.network.NetworkModel; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -78,7 +83,7 @@ import com.cloud.network.rules.LbStickinessMethod; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.offering.NetworkOffering; import com.cloud.resource.ServerResource; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; @@ -118,7 +123,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan ConfigurationDao _configDao; private boolean canHandle(Network config) { - if ((config.getGuestType() != Network.GuestType.Isolated && config.getGuestType() != Network.GuestType.Shared) || config.getTrafficType() != TrafficType.Guest) { + if (config.getGuestType() != Network.GuestType.Isolated || config.getTrafficType() != TrafficType.Guest) { s_logger.trace("Not handling network with Type " + config.getGuestType() + " and traffic type " + config.getTrafficType()); return false; } @@ -173,7 +178,8 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public boolean validateLBRule(Network network, LoadBalancingRule rule) { - return true; + String algo = rule.getAlgorithm(); + return (algo.equals("roundrobin") || algo.equals("leastconn")); } @Override @@ -207,6 +213,9 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional"); + // Support inline mode with firewall + lbCapabilities.put(Capability.InlineMode, "true"); + LbStickinessMethod method; List methodList = new ArrayList(); method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http"); @@ -255,8 +264,17 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } @Override - public String getPropertiesFile() { - return "f5bigip_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(AddExternalLoadBalancerCmd.class); + cmdList.add(AddF5LoadBalancerCmd.class); + cmdList.add(ConfigureF5LoadBalancerCmd.class); + cmdList.add(DeleteExternalLoadBalancerCmd.class); + cmdList.add(DeleteF5LoadBalancerCmd.class); + cmdList.add(ListExternalLoadBalancersCmd.class); + cmdList.add(ListF5LoadBalancerNetworksCmd.class); + cmdList.add(ListF5LoadBalancersCmd.class); + return cmdList; } @Override @@ -437,9 +455,12 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan Host lbHost = _hostDao.findById(lbDeviceVO.getHostId()); Map lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId()); - response.setId(lbDeviceVO.getId()); + response.setId(lbDeviceVO.getUuid()); response.setIpAddress(lbHost.getPrivateIpAddress()); - response.setPhysicalNetworkId(lbDeviceVO.getPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setDeviceName(lbDeviceVO.getDeviceName()); @@ -449,7 +470,6 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } else { response.setDeviceCapacity(lbDeviceVO.getCapacity()); } - response.setInlineMode(lbDeviceVO.getIsInLineMode()); response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice()); response.setProvider(lbDeviceVO.getProviderName()); response.setDeviceState(lbDeviceVO.getState().name()); @@ -470,6 +490,15 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public IpDeployer getIpDeployer(Network network) { + ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network); + if (lbDevice == null) { + s_logger.error("Cannot find external load balanacer for network " + network.getName()); + s_logger.error("Make F5 as dummy ip deployer, since we likely met this when clean up resource after shutdown network"); + return this; + } + if (_networkManager.isNetworkInlineMode(network)) { + return getIpDeployerForInlineMode(network); + } return this; } } diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java index 24c76753b47..951bc3cc3b1 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java @@ -30,7 +30,7 @@ import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.host.Host; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.Network; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.component.PluggableService; @SuppressWarnings("deprecation") diff --git a/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java b/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java index a45dd92ca98..c9c3711bfc1 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java +++ b/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java @@ -119,7 +119,6 @@ public class F5BigIpResource implements ServerResource { private String _privateInterface; private Integer _numRetries; private String _guid; - private boolean _inline; private Interfaces _interfaces; private LocalLBVirtualServerBindingStub _virtualServerApi; @@ -180,8 +179,6 @@ public class F5BigIpResource implements ServerResource { throw new ConfigurationException("Unable to find the guid"); } - _inline = Boolean.parseBoolean((String) params.get("inline")); - login(); return true; @@ -292,45 +289,48 @@ public class F5BigIpResource implements ServerResource { } private synchronized Answer execute(IpAssocCommand cmd, int numRetries) { - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; - try { - IpAddressTO[] ips = cmd.getIpAddresses(); - for (IpAddressTO ip : ips) { - long guestVlanTag = Long.valueOf(ip.getVlanId()); - String vlanSelfIp = _inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); - String vlanNetmask = ip.getVlanNetmask(); - - // Delete any existing guest VLAN with this tag, self IP, and netmask - deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); - - if (ip.isAdd()) { - // Add a new guest VLAN - addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); + String[] results = new String[cmd.getIpAddresses().length]; + int i = 0; + try { + IpAddressTO[] ips = cmd.getIpAddresses(); + for (IpAddressTO ip : ips) { + long guestVlanTag = Long.valueOf(ip.getVlanId()); + // It's a hack, using isOneToOneNat field for indicate if it's inline or not + boolean inline = ip.isOneToOneNat(); + String vlanSelfIp = inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); + String vlanNetmask = ip.getVlanNetmask(); + + // Delete any existing guest VLAN with this tag, self IP, and netmask + deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); + + if (ip.isAdd()) { + // Add a new guest VLAN + addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); + } + + saveConfiguration(); + results[i++] = ip.getPublicIp() + " - success"; } - - saveConfiguration(); - results[i++] = ip.getPublicIp() + " - success"; - } - - } catch (ExecutionException e) { - s_logger.error("Failed to execute IPAssocCommand due to " + e); - - if (shouldRetry(numRetries)) { - return retry(cmd, numRetries); - } else { - results[i++] = IpAssocAnswer.errorResult; - } - } - - return new IpAssocAnswer(cmd, results); - } + + } catch (ExecutionException e) { + s_logger.error("Failed to execute IPAssocCommand due to " + e); + + if (shouldRetry(numRetries)) { + return retry(cmd, numRetries); + } else { + results[i++] = IpAssocAnswer.errorResult; + } + } + + return new IpAssocAnswer(cmd, results); + } private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) { try { long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers(); for (LoadBalancerTO loadBalancer : loadBalancers) { + boolean inline = loadBalancer.isInline(); LbProtocol lbProtocol; try { if (loadBalancer.getProtocol() == null) { @@ -351,7 +351,7 @@ public class F5BigIpResource implements ServerResource { throw new ExecutionException("Got invalid algorithm: " + loadBalancer.getAlgorithm()); } - String srcIp = _inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); + String srcIp = inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); int srcPort = loadBalancer.getSrcPort(); String virtualServerName = genVirtualServerName(lbProtocol, srcIp, srcPort); @@ -363,6 +363,8 @@ public class F5BigIpResource implements ServerResource { } } + // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members + deleteVirtualServerAndDefaultPool(virtualServerName); if (!loadBalancer.isRevoked() && destinationsToAdd) { // Add the pool addPool(virtualServerName, lbAlgorithm); @@ -371,20 +373,14 @@ public class F5BigIpResource implements ServerResource { List activePoolMembers = new ArrayList(); for (DestinationTO destination : loadBalancer.getDestinations()) { if (!destination.isRevoked()) { - String destIp = _inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); + String destIp = inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); addPoolMember(virtualServerName, destIp, destination.getDestPort()); activePoolMembers.add(destIp + "-" + destination.getDestPort()); } } - // Delete any pool members that aren't in the current list of destinations - deleteInactivePoolMembers(virtualServerName, activePoolMembers); - // Add the virtual server addVirtualServer(virtualServerName, lbProtocol, srcIp, srcPort, loadBalancer.getStickinessPolicies()); - } else { - // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members - deleteVirtualServerAndDefaultPool(virtualServerName); } } @@ -421,7 +417,7 @@ public class F5BigIpResource implements ServerResource { } } - private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { + private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { try { String vlanName = genVlanName(vlanTag); List allVlans = getVlans(); @@ -444,7 +440,7 @@ public class F5BigIpResource implements ServerResource { } } - if (_inline) { + if (inline) { List allRouteDomains = getRouteDomains(); if (!allRouteDomains.contains(vlanTag)) { long[] routeDomainIds = genLongArray(vlanTag); @@ -481,7 +477,7 @@ public class F5BigIpResource implements ServerResource { } - private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { + private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { try { // Delete all virtual servers and pools that use this guest VLAN deleteVirtualServersInGuestVlan(vlanSelfIp, vlanNetmask); @@ -496,7 +492,7 @@ public class F5BigIpResource implements ServerResource { } } - if (_inline) { + if (inline) { List allRouteDomains = getRouteDomains(); if (allRouteDomains.contains(vlanTag)) { s_logger.debug("Deleting route domain " + vlanTag); @@ -969,9 +965,7 @@ public class F5BigIpResource implements ServerResource { for (LocalLBVirtualServerVirtualServerStatisticEntry entry : stats.getStatistics()) { String virtualServerIp = entry.getVirtual_server().getAddress(); - if (_inline) { - virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); - } + virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); long[] bytesSentAndReceived = answer.ipBytes.get(virtualServerIp); diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java index 9b55af644ac..cda27fb8960 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -16,23 +16,23 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.user.Account; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "addExternalFirewall", description="Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class) public class AddExternalFirewallCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddExternalFirewallCmd.class.getName()); private static final String s_name = "addexternalfirewallresponse"; @@ -41,8 +41,8 @@ public class AddExternalFirewallCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external firewall appliance.") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java index 6872c8eabfe..a2ad4e5ce2b 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java @@ -16,16 +16,16 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +38,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="Adds a SRX firewall device") +@APICommand(name = "addSrxFirewall", responseObject=SrxFirewallResponse.class, description="Adds a SRX firewall device") public class AddSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddSrxFirewallCmd.class.getName()); private static final String s_name = "addsrxfirewallresponse"; @@ -48,8 +48,8 @@ public class AddSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the SRX appliance.") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java index d5d90ff1196..482fcc8c0c7 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java @@ -18,14 +18,13 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +37,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="Configures a SRX firewall device") +@APICommand(name = "configureSrxFirewall", responseObject=SrxFirewallResponse.class, description="Configures a SRX firewall device") public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureSrxFirewallCmd.class.getName()); @@ -49,8 +48,8 @@ public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, required=true, description="SRX firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required=true, description="SRX firewall device ID") private Long fwDeviceId; @Parameter(name=ApiConstants.FIREWALL_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the firewall device, Capacity will be interpreted as number of networks device can handle") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java index 8a0af1f05bb..5cdc9e3c92c 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java @@ -16,21 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.Account; -@Implementation(description="Deletes an external firewall appliance.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteExternalFirewall", description="Deletes an external firewall appliance.", responseObject = SuccessResponse.class) public class DeleteExternalFirewallCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteExternalFirewallCmd.class.getName()); private static final String s_name = "deleteexternalfirewallresponse"; @@ -39,8 +39,8 @@ public class DeleteExternalFirewallCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the external firewall appliance.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the external firewall appliance.") private Long id; /////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java index d741c0ca3b9..1dc792a723a 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java @@ -18,15 +18,15 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -37,7 +37,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a SRX firewall device") +@APICommand(name = "deleteSrxFirewall", responseObject=SuccessResponse.class, description=" delete a SRX firewall device") public class DeleteSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteSrxFirewallCmd.class.getName()); private static final String s_name = "deletesrxfirewallresponse"; @@ -47,8 +47,8 @@ public class DeleteSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, required=true, description="srx firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required=true, description="srx firewall device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java index 111df728095..65aa92ba818 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java @@ -19,20 +19,21 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.host.Host; import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; -@Implementation(description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "listExternalFirewalls", description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class) public class ListExternalFirewallsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); private static final String s_name = "listexternalfirewallsresponse"; @@ -41,8 +42,8 @@ public class ListExternalFirewallsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="zone Id") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java index 43a5dff0508..9c2b3962a6f 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java @@ -19,18 +19,13 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import com.cloud.api.response.SrxFirewallResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +35,7 @@ import com.cloud.network.Network; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using SRX firewall device") +@APICommand(name = "listSrxFirewallNetworks", responseObject=NetworkResponse.class, description="lists network that are using SRX firewall device") public class ListSrxFirewallNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSrxFirewallNetworksCmd.class.getName()); @@ -51,8 +46,8 @@ public class ListSrxFirewallNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required = true, description="netscaler load balancer device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java index a4f68566a25..6508cc83c7d 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java @@ -19,17 +19,12 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -40,7 +35,7 @@ import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="lists SRX firewall devices in a physical network") +@APICommand(name = "listSrxFirewalls", responseObject=SrxFirewallResponse.class, description="lists SRX firewall devices in a physical network") public class ListSrxFirewallsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSrxFirewallsCmd.class.getName()); @@ -51,12 +46,12 @@ public class ListSrxFirewallsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, description="SRX firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + description="SRX firewall device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java index 08242bdb372..56aab70f2f3 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java @@ -16,26 +16,29 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalFirewallDeviceVO; +@EntityReference(value=ExternalFirewallDeviceVO.class) @SuppressWarnings("unused") public class SrxFirewallResponse extends BaseResponse { @SerializedName(ApiConstants.FIREWALL_DEVICE_ID) @Param(description="device id of the SRX firewall") - private IdentityProxy id = new IdentityProxy("external_firewall_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this SRX firewall belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.FIREWALL_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.FIREWALL_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -43,7 +46,7 @@ public class SrxFirewallResponse extends BaseResponse { private Long deviceCapacity; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; @@ -72,12 +75,12 @@ public class SrxFirewallResponse extends BaseResponse { @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java index c6cac55a705..5038cc801ac 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java @@ -11,11 +11,12 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network.element; +import java.lang.String; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -24,8 +25,10 @@ import java.util.Set; import javax.ejb.Local; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddSrxFirewallCmd; import com.cloud.api.commands.ConfigureSrxFirewallCmd; @@ -55,7 +58,7 @@ import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.ExternalFirewallDeviceManagerImpl; import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -63,6 +66,7 @@ import com.cloud.network.Network.Service; import com.cloud.network.NetworkExternalFirewallVO; import com.cloud.network.NetworkModel; import com.cloud.network.NetworkVO; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -76,10 +80,11 @@ import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.resource.JuniperSrxResource; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ServerResource; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; @@ -92,7 +97,7 @@ import com.cloud.vm.VirtualMachineProfile; PortForwardingServiceProvider.class, IpDeployer.class, SourceNatServiceProvider.class, RemoteAccessVPNServiceProvider.class}) public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceManagerImpl implements SourceNatServiceProvider, FirewallServiceProvider, - PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService { + PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService, StaticNatServiceProvider { private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); @@ -127,8 +132,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan private boolean canHandle(Network network, Service service) { DataCenter zone = _configMgr.getZone(network.getDataCenterId()); - if ((zone.getNetworkType() == NetworkType.Advanced && !(network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared )) - || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { + if ((zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() != Network.GuestType.Isolated) || (zone.getNetworkType() == NetworkType.Basic && network.getGuestType() != Network.GuestType.Shared)) { s_logger.trace("Element " + getProvider().getName() + "is not handling network type = " + network.getGuestType()); return false; } @@ -270,7 +274,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan // Set capabilities for Firewall service Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); + firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); firewallCapabilities.put(Capability.MultipleIps, "true"); firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); capabilities.put(Service.Firewall, firewallCapabilities); @@ -304,7 +308,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan return false; } - return applyFirewallRules(network, rules); + return applyPortForwardingRules(network, rules); } @Override @@ -331,7 +335,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan @Override public boolean canEnableIndividualServices() { - return false; + return true; } @Override @@ -401,8 +405,17 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan } @Override - public String getPropertiesFile() { - return "junipersrx_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(AddExternalFirewallCmd.class); + cmdList.add(AddSrxFirewallCmd.class); + cmdList.add(ConfigureSrxFirewallCmd.class); + cmdList.add(DeleteExternalFirewallCmd.class); + cmdList.add(DeleteSrxFirewallCmd.class); + cmdList.add(ListExternalFirewallsCmd.class); + cmdList.add(ListSrxFirewallNetworksCmd.class); + cmdList.add(ListSrxFirewallsCmd.class); + return cmdList; } @Override @@ -511,8 +524,11 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan Map fwDetails = _hostDetailDao.findDetails(fwDeviceVO.getHostId()); Host fwHost = _hostDao.findById(fwDeviceVO.getHostId()); - response.setId(fwDeviceVO.getId()); - response.setPhysicalNetworkId(fwDeviceVO.getPhysicalNetworkId()); + response.setId(fwDeviceVO.getUuid()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(fwDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setDeviceName(fwDeviceVO.getDeviceName()); if (fwDeviceVO.getCapacity() == 0) { long defaultFwCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalFirewallCapacity.key()), 50); @@ -536,6 +552,10 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan @Override public boolean verifyServicesCombination(Set services) { + if (!services.contains(Service.Firewall)) { + s_logger.warn("SRX must be used as Firewall Service Provider in the network"); + return false; + } return true; } @@ -549,4 +569,12 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan // return true, as IP will be associated as part of static NAT/port forwarding rule configuration return true; } + + @Override + public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { + if (!canHandle(config, Service.StaticNat)) { + return false; + } + return applyStaticNatRules(config, rules); + } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java index 6d07d303128..d5f53843ca1 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java @@ -30,7 +30,7 @@ import com.cloud.api.response.SrxFirewallResponse; import com.cloud.host.Host; import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.Network; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.utils.component.PluggableService; public interface JuniperSRXFirewallElementService extends PluggableService { diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java index ebb3de6c850..f823ab8af4f 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java @@ -55,6 +55,7 @@ import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; +import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; @@ -64,6 +65,7 @@ import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; +import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.resource.ServerResource; import com.cloud.utils.NumbersUtil; @@ -75,7 +77,6 @@ public class JuniperSrxResource implements ServerResource { private String _name; private String _zoneId; - private String _physicalNetworkId; private String _ip; private String _username; private String _password; @@ -89,6 +90,7 @@ public class JuniperSrxResource implements ServerResource { private Integer _timeoutInSeconds; private String _publicZone; private String _privateZone; + private String _publicZoneInputFilterName; private String _publicInterface; private String _usageInterface; private String _privateInterface; @@ -159,6 +161,9 @@ public class JuniperSrxResource implements ServerResource { ACCESS_PROFILE_ADD("access-profile-add.xml"), ACCESS_PROFILE_GETONE("access-profile-getone.xml"), ACCESS_PROFILE_GETALL("access-profile-getall.xml"), + FIREWALL_FILTER_TERM_ADD("firewall-filter-term-add.xml"), + FIREWALL_FILTER_TERM_GETONE("firewall-filter-term-getone.xml"), + TEMPLATE_ENTRY("template-entry.xml"), OPEN_CONFIGURATION("open-configuration.xml"), CLOSE_CONFIGURATION("close-configuration.xml"), COMMIT("commit.xml"), @@ -231,12 +236,74 @@ public class JuniperSrxResource implements ServerResource { } } + public class FirewallFilterTerm { + private String name; + private List sourceCidrs; + private String destIp; + private String portRange; + private String protocol; + private String icmpType; + private String icmpCode; + private String countName; + + private FirewallFilterTerm(String name, List sourceCidrs, String destIp, String protocol, Integer startPort, Integer endPort, + Integer icmpType, Integer icmpCode, String countName) { + this.name = name; + this.sourceCidrs = sourceCidrs; + this.destIp = destIp; + this.protocol = protocol; + + if (protocol.equals("tcp") || protocol.equals("udp")) { + this.portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort); + } else if (protocol.equals("icmp")) { + this.icmpType = String.valueOf(icmpType); + this.icmpCode = String.valueOf(icmpCode); + } else { + assert protocol.equals("any"); + } + this.countName = countName; + + } + + public String getName() { + return name; + } + + public List getSourceCidrs() { + return sourceCidrs; + } + + public String getDestIp() { + return destIp; + } + + public String getPortRange() { + return portRange; + } + + public String getProtocol() { + return protocol; + } + + public String getIcmpType() { + return icmpType; + } + + public String getIcmpCode() { + return icmpCode; + } + + public String getCountName() { + return countName; + } + } + private enum SrxCommand { LOGIN, OPEN_CONFIGURATION, CLOSE_CONFIGURATION, COMMIT, ROLLBACK, CHECK_IF_EXISTS, CHECK_IF_IN_USE, ADD, DELETE, GET_ALL; } private enum Protocol { - tcp, udp, any; + tcp, udp, icmp, any; } private enum RuleMatchCondition { @@ -277,6 +344,8 @@ public class JuniperSrxResource implements ServerResource { return execute((SetStaticNatRulesCommand) cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { return execute((SetPortForwardingRulesCommand) cmd); + } else if (cmd instanceof SetFirewallRulesCommand) { + return execute((SetFirewallRulesCommand) cmd); } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { return execute((ExternalNetworkResourceUsageCommand) cmd); } else if (cmd instanceof RemoteAccessVpnCfgCommand) { @@ -300,11 +369,6 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to find zone"); } - _physicalNetworkId = (String) params.get("physicalNetworkId"); - if (_physicalNetworkId == null) { - throw new ConfigurationException("Unable to find physical network id in the configuration parameters"); - } - _ip = (String) params.get("ip"); if (_ip == null) { throw new ConfigurationException("Unable to find IP"); @@ -325,8 +389,6 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to find public interface."); } - _usageInterface = (String) params.get("usageinterface"); - _privateInterface = (String) params.get("privateinterface"); if (_privateInterface == null) { throw new ConfigurationException("Unable to find private interface."); @@ -364,6 +426,8 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to open a connection to the SRX."); } + _publicZoneInputFilterName = _publicZone; + _usageFilterVlanInput = new UsageFilter("vlan-input", null, "vlan-input"); _usageFilterVlanOutput = new UsageFilter("vlan-output", null, "vlan-output"); _usageFilterIPInput = new UsageFilter(_publicZone, "destination-address", "-i"); @@ -712,6 +776,50 @@ public class JuniperSrxResource implements ServerResource { s_logger.debug(msg); } + + /* security policies */ + private synchronized Answer execute(SetFirewallRulesCommand cmd) { + refreshSrxConnection(); + return execute(cmd, _numRetries); + } + + private Answer execute(SetFirewallRulesCommand cmd, int numRetries) { + FirewallRuleTO[] rules = cmd.getRules(); + try { + openConfiguration(); + + for (FirewallRuleTO rule : rules) { + int startPort = 0, endPort = 0; + if (rule.getSrcPortRange() != null) { + startPort = rule.getSrcPortRange()[0]; + endPort = rule.getSrcPortRange()[1]; + } + FirewallFilterTerm term = new FirewallFilterTerm(genIpIdentifier(rule.getSrcIp()) + "-" + String.valueOf(rule.getId()), rule.getSourceCidrList(), + rule.getSrcIp(), rule.getProtocol(), startPort, endPort, + rule.getIcmpType(), rule.getIcmpCode(), genIpIdentifier(rule.getSrcIp()) + _usageFilterIPInput.getCounterIdentifier()); + if (!rule.revoked()) { + manageFirewallFilter(SrxCommand.ADD, term, _publicZoneInputFilterName); + } else { + manageFirewallFilter(SrxCommand.DELETE, term, _publicZoneInputFilterName); + } + } + + commitConfiguration(); + return new Answer(cmd); + } catch (ExecutionException e) { + s_logger.error(e); + closeConfiguration(); + + if (numRetries > 0 && refreshSrxConnection()) { + int numRetriesRemaining = numRetries - 1; + s_logger.debug("Retrying SetFirewallRulesCommand. Number of retries remaining: " + numRetriesRemaining); + return execute(cmd, numRetriesRemaining); + } else { + return new Answer(cmd, e); + } + } + } + /* * Static NAT */ @@ -766,7 +874,6 @@ public class JuniperSrxResource implements ServerResource { private void addStaticNatRule(Long publicVlanTag, String publicIp, String privateIp, List rules) throws ExecutionException { manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); manageStaticNatRule(SrxCommand.ADD, publicIp, privateIp); - manageUsageFilter(SrxCommand.ADD, _usageFilterIPInput, publicIp, null, genIpFilterTermName(publicIp)); manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); // Add a new security policy with the current set of applications @@ -778,7 +885,6 @@ public class JuniperSrxResource implements ServerResource { private void removeStaticNatRule(Long publicVlanTag, String publicIp, String privateIp) throws ExecutionException { manageStaticNatRule(SrxCommand.DELETE, publicIp, privateIp); manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); - manageUsageFilter(SrxCommand.DELETE, _usageFilterIPInput, publicIp, null, genIpFilterTermName(publicIp)); // Remove any existing security policy and clean up applications removeSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp); @@ -2781,6 +2887,108 @@ public class JuniperSrxResource implements ServerResource { } } + private String genNameValueEntry(String name, String value) { + String xml = SrxXml.TEMPLATE_ENTRY.getXml(); + xml = replaceXmlValue(xml, "name", name); + xml = replaceXmlValue(xml, "value", value); + return xml; + } + + private String genMultipleEntries(String name, List values) { + String result = ""; + for (String value : values) { + result = result + genNameValueEntry(name, value); + } + return result; + } + + private String genPortRangeEntry(String protocol, String portRange) { + String result = ""; + result = result + genNameValueEntry("protocol", protocol); + result = result + genNameValueEntry("destination-port", portRange); + return result; + } + + private String genIcmpEntries(String icmpType, String icmpCode) { + String result = ""; + result = result + genNameValueEntry("protocol", "icmp"); + if (icmpType.equals("-1")) { + result = result + genNameValueEntry("icmp-type", "0-255"); + } else { + result = result + genNameValueEntry("icmp-type", icmpType); + } + if (icmpCode.equals("-1")) { + result = result + genNameValueEntry("icmp-code", "0-255"); + } else { + result = result + genNameValueEntry("icmp-code", icmpCode); + } + return result; + } + + private boolean manageFirewallFilter(SrxCommand command, FirewallFilterTerm term, String filterName) throws ExecutionException { + String xml; + + switch(command) { + + case CHECK_IF_EXISTS: + xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); + xml = setDelete(xml, false); + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + return sendRequestAndCheckResponse(command, xml, "name", term.getName()); + + case ADD: + if (manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { + return true; + } + + xml = SrxXml.FIREWALL_FILTER_TERM_ADD.getXml(); + + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + xml = replaceXmlValue(xml, "source-address-entries", genMultipleEntries("source-address", term.getSourceCidrs())); + xml = replaceXmlValue(xml, "dest-ip-address", term.getDestIp()); + + String protocol = term.getProtocol(); + if (protocol.equals("tcp") || protocol.equals("udp")) { + xml = replaceXmlValue(xml, "protocol-options", genPortRangeEntry(protocol, term.getPortRange())); + } else if (protocol.equals("icmp")) { + xml = replaceXmlValue(xml, "protocol-options", genIcmpEntries(term.getIcmpType(), term.getIcmpCode())); + } else { + assert protocol.equals("any"); + xml = replaceXmlValue(xml, "protocol-options", ""); + } + xml = replaceXmlValue(xml, "count-name", term.getCountName()); + + if (!sendRequestAndCheckResponse(command, xml)) { + throw new ExecutionException("Failed to add firewall filter: " + term.getName()); + } else { + return true; + } + + case DELETE: + if (!manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { + return true; + } + + xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); + xml = setDelete(xml, true); + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + + if (!sendRequestAndCheckResponse(command, xml)) { + throw new ExecutionException("Failed to delete firewall filter: " + term.getName()); + } else { + return true; + } + + default: + s_logger.debug("Unrecognized command."); + return false; + + } + } + /* * Usage */ @@ -2913,6 +3121,10 @@ public class JuniperSrxResource implements ServerResource { } UsageFilter filter = getUsageFilter(counterName); + if (filter == null) { + s_logger.debug("Failed to parse counter name in usage answer: " + counterName); + return; + } String usageAnswerKey = getUsageAnswerKey(filter, counterName); Map bytesMap = getBytesMap(answer, filter, usageAnswerKey); updateBytesMap(bytesMap, filter, usageAnswerKey, byteCount); @@ -2981,6 +3193,11 @@ public class JuniperSrxResource implements ServerResource { } private boolean checkResponse(String xmlResponse, boolean errorKeyAndValue, String key, String value) { + if (xmlResponse == null) { + s_logger.error("Failed to communicate with SRX!"); + return false; + } + if (!xmlResponse.contains("authentication-response")) { s_logger.debug("Checking response: " + xmlResponse); } else { diff --git a/plugins/network-elements/midokura-midonet/src/com/cloud/network/element/MidokuraMidonetElement.java b/plugins/network-elements/midokura-midonet/src/com/cloud/network/element/MidokuraMidonetElement.java index 56734669020..a45c5c0a47c 100644 --- a/plugins/network-elements/midokura-midonet/src/com/cloud/network/element/MidokuraMidonetElement.java +++ b/plugins/network-elements/midokura-midonet/src/com/cloud/network/element/MidokuraMidonetElement.java @@ -38,15 +38,10 @@ import com.cloud.vm.VirtualMachineProfile; import org.apache.log4j.Logger; import javax.ejb.Local; +import java.lang.Class; import java.util.Map; import java.util.Set; -/** - * User: tomoe - * Date: 8/8/12 - * Time: 1:38 PM - */ - @Local(value = NetworkElement.class) public class MidokuraMidonetElement extends AdapterBase implements ConnectivityProvider, PluggableService { private static final Logger s_logger = Logger.getLogger(MidokuraMidonetElement.class); @@ -126,7 +121,7 @@ public class MidokuraMidonetElement extends AdapterBase implements ConnectivityP } @Override - public String getPropertiesFile() { + public List> getCommands() { // TODO: implement this. return null; } diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java index 1a88de2cb6c..9d902975723 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java @@ -15,15 +15,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -36,7 +31,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="Adds a netscaler load balancer device") +@APICommand(name = "addNetscalerLoadBalancer", responseObject=NetscalerLoadBalancerResponse.class, description="Adds a netscaler load balancer device") public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddNetscalerLoadBalancerCmd.class.getName()); @@ -47,8 +42,8 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the netscaler load balancer appliance.") diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java index de1a7c84ef5..e0ec73ad501 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java @@ -16,17 +16,11 @@ package com.cloud.api.commands; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PodResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +33,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="configures a netscaler load balancer device") +@APICommand(name = "configureNetscalerLoadBalancer", responseObject=NetscalerLoadBalancerResponse.class, description="configures a netscaler load balancer device") public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureNetscalerLoadBalancerCmd.class.getName()); @@ -50,8 +44,8 @@ public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="Netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + required=true, description="Netscaler load balancer device ID") private Long lbDeviceId; @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the device, Capacity will be interpreted as number of networks device can handle") @@ -63,8 +57,8 @@ public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { @Parameter (name=ApiConstants.INLINE, type=CommandType.BOOLEAN, required=false, description="true if netscaler load balancer is intended to be used in in-line with firewall, false if netscaler load balancer will side-by-side with firewall") private Boolean inline; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_IDS, type=CommandType.LIST, required=false, description="Used when NetScaler device is provider of EIP service." + + @Parameter(name=ApiConstants.POD_IDS, type=CommandType.LIST, collectionType = CommandType.UUID, entityType = PodResponse.class, + required=false, description="Used when NetScaler device is provider of EIP service." + " This parameter represents the list of pod's, for which there exists a policy based route on datacenter L3 router to " + "route pod's subnet IP to a NetScaler device.") private List podIds; diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java index b063fdf6396..ec7faab39d4 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java @@ -17,15 +17,15 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -36,7 +36,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a netscaler load balancer device") +@APICommand(name = "deleteNetscalerLoadBalancer", responseObject=SuccessResponse.class, description=" delete a netscaler load balancer device") public class DeleteNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetscalerLoadBalancerCmd.class.getName()); @@ -47,8 +47,8 @@ public class DeleteNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + required=true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java index c0c5950d57e..52476df8316 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java @@ -19,16 +19,16 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +38,7 @@ import com.cloud.network.Network; import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a netscaler load balancer device") +@APICommand(name = "listNetscalerLoadBalancerNetworks", responseObject=NetworkResponse.class, description="lists network that are using a netscaler load balancer device") public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetscalerLoadBalancerNetworksCmd.class.getName()); @@ -49,8 +49,8 @@ public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + required = true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java index 98fe6e95df7..bf679fa51c1 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java @@ -17,17 +17,17 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -38,7 +38,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="lists netscaler load balancer devices") +@APICommand(name = "listNetscalerLoadBalancers", responseObject=NetscalerLoadBalancerResponse.class, description="lists netscaler load balancer devices") public class ListNetscalerLoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetscalerLoadBalancersCmd.class.getName()); @@ -49,12 +49,12 @@ public class ListNetscalerLoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java index bbbfca515a1..40be29e560b 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java @@ -18,28 +18,29 @@ package com.cloud.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalLoadBalancerDeviceVO; +@EntityReference(value=ExternalLoadBalancerDeviceVO.class) @SuppressWarnings("unused") public class NetscalerLoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_ID) @Param(description="device id of the netscaler load balancer") - private IdentityProxy id = new IdentityProxy("external_load_balancer_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this netscaler device belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -49,12 +50,9 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) @Param(description="true if device is dedicated for an account") private Boolean dedicatedLoadBalancer; - @SerializedName(ApiConstants.INLINE) @Param(description="true if device is inline with firewall device") - private Boolean inlineLoadBalancer; - @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the load balancer") private String privateInterface; @@ -65,13 +63,13 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { " This parameter represents the list of pod's, for which there exists a policy based route on datacenter L3 router to " + "route pod's subnet IP to a NetScaler device.") private List podIds; - - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { @@ -94,10 +92,6 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { this.deviceState = deviceState; } - public void setInlineMode(boolean inline) { - this.inlineLoadBalancer = inline; - } - public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java b/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java index f28078749d2..be0bd2f8c23 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -31,7 +33,7 @@ import javax.persistence.Table; */ @Entity @Table(name="netscaler_pod_ref") -public class NetScalerPodVO { +public class NetScalerPodVO implements InternalIdentity { @Column(name="external_load_balancer_device_id") private long netscalerDeviceId; diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java index 18bee328e0d..c2dc1e059d0 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/element/NetscalerElement.java @@ -11,11 +11,12 @@ // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the +// KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.network.element; +import java.lang.Class; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; @@ -26,6 +27,7 @@ import java.util.Set; import javax.ejb.Local; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -35,7 +37,9 @@ import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; + +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddNetscalerLoadBalancerCmd; import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd; import com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd; @@ -65,7 +69,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.IpAddress; import com.cloud.network.NetScalerPodVO; import com.cloud.network.Network; @@ -76,6 +80,7 @@ import com.cloud.network.NetworkExternalLoadBalancerVO; import com.cloud.network.NetworkModel; import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -149,8 +154,7 @@ StaticNatServiceProvider { private boolean canHandle(Network config, Service service) { DataCenter zone = _dcDao.findById(config.getDataCenterId()); - boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && - (config.getGuestType() == Network.GuestType.Isolated || config.getGuestType() == Network.GuestType.Shared) && config.getTrafficType() == TrafficType.Guest); + boolean handleInAdvanceZone = (zone.getNetworkType() == NetworkType.Advanced && config.getGuestType() == Network.GuestType.Isolated && config.getTrafficType() == TrafficType.Guest); boolean handleInBasicZone = (zone.getNetworkType() == NetworkType.Basic && config.getGuestType() == Network.GuestType.Shared && config.getTrafficType() == TrafficType.Guest); if (!(handleInAdvanceZone || handleInBasicZone)) { @@ -353,18 +357,17 @@ StaticNatServiceProvider { public ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(ConfigureNetscalerLoadBalancerCmd cmd) { Long lbDeviceId = cmd.getLoadBalancerDeviceId(); Boolean dedicatedUse = cmd.getLoadBalancerDedicated(); - Boolean inline = cmd.getLoadBalancerInline(); Long capacity = cmd.getLoadBalancerCapacity(); List podIds = cmd.getPodIds(); try { - return configureNetscalerLoadBalancer(lbDeviceId, capacity, inline, dedicatedUse, podIds); + return configureNetscalerLoadBalancer(lbDeviceId, capacity, dedicatedUse, podIds); } catch (Exception e) { throw new CloudRuntimeException("failed to configure netscaler device due to " + e.getMessage()); } } @DB - private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(long lbDeviceId, Long capacity, Boolean inline, Boolean dedicatedUse, List newPodsConfig) { + private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(long lbDeviceId, Long capacity, Boolean dedicatedUse, List newPodsConfig) { ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); Map lbDetails = _detailsDao.findDetails(lbDeviceVo.getHostId()); @@ -404,7 +407,7 @@ StaticNatServiceProvider { } String deviceName = lbDeviceVo.getDeviceName(); - if (dedicatedUse != null || capacity != null || inline != null) { + if (dedicatedUse != null || capacity != null) { if (NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName) || NetworkDevice.NetscalerMPXLoadBalancer.getName().equalsIgnoreCase(deviceName)) { if (dedicatedUse != null && dedicatedUse == true) { @@ -422,13 +425,6 @@ StaticNatServiceProvider { if (dedicatedUse != null && dedicatedUse == true) { throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated"); } - - if (inline != null) { - boolean _setInline = Boolean.parseBoolean(lbDetails.get("inline")); - if (inline != _setInline) { - throw new CloudRuntimeException("There are networks already using this netscaler device to change the device inline or side-by-side configuration"); - } - } } } @@ -444,14 +440,6 @@ StaticNatServiceProvider { lbDeviceVo.setIsDedicatedDevice(dedicatedUse); } - if (inline != null && inline == true) { - lbDeviceVo.setIsInlineMode(true); - lbDetails.put("inline", "true"); - } else { - lbDeviceVo.setIsInlineMode(false); - lbDetails.put("inline", "false"); - } - Transaction txn = Transaction.currentTxn(); txn.start(); @@ -477,8 +465,14 @@ StaticNatServiceProvider { } @Override - public String getPropertiesFile() { - return "netscalerloadbalancer_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(AddNetscalerLoadBalancerCmd.class); + cmdList.add(ConfigureNetscalerLoadBalancerCmd.class); + cmdList.add(DeleteNetscalerLoadBalancerCmd.class); + cmdList.add(ListNetscalerLoadBalancerNetworksCmd.class); + cmdList.add(ListNetscalerLoadBalancersCmd.class); + return cmdList; } @Override @@ -540,9 +534,12 @@ StaticNatServiceProvider { Host lbHost = _hostDao.findById(lbDeviceVO.getHostId()); Map lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId()); - response.setId(lbDeviceVO.getId()); + response.setId(lbDeviceVO.getUuid()); response.setIpAddress(lbHost.getPrivateIpAddress()); - response.setPhysicalNetworkId(lbDeviceVO.getPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setDeviceName(lbDeviceVO.getDeviceName()); @@ -552,7 +549,6 @@ StaticNatServiceProvider { } else { response.setDeviceCapacity(lbDeviceVO.getCapacity()); } - response.setInlineMode(lbDeviceVO.getIsInLineMode()); response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice()); response.setProvider(lbDeviceVO.getProviderName()); response.setDeviceState(lbDeviceVO.getState().name()); @@ -620,13 +616,13 @@ StaticNatServiceProvider { // NetScaler can only act as Lb and Static Nat service provider if (services != null && !services.isEmpty() && !netscalerServices.containsAll(services)) { - s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + services + " is not supported."); String servicesList = ""; for (Service service : services) { servicesList += service.getName() + " "; } - s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + servicesList + " is not supported."); s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + services + " is not supported."); @@ -644,6 +640,14 @@ StaticNatServiceProvider { @Override public IpDeployer getIpDeployer(Network network) { + ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network); + if (lbDevice == null) { + s_logger.error("Cannot find external load balanacer for network " + network.getName()); + return null; + } + if (_networkMgr.isNetworkInlineMode(network)) { + return getIpDeployerForInlineMode(network); + } return this; } @@ -690,7 +694,7 @@ StaticNatServiceProvider { List destinations = rule.getDestinations(); if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { - LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, destinations, rule.getStickinessPolicies()); + LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, rule.getStickinessPolicies()); if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java index d11d16a5c9f..afb01353e1e 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java @@ -86,7 +86,7 @@ import com.cloud.agent.api.to.LoadBalancerTO.CounterTO; import com.cloud.agent.api.to.LoadBalancerTO.DestinationTO; import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host; import com.cloud.host.Host.Type; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java index ef12bf62605..1734ce2ff3d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java @@ -16,32 +16,24 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Adds a Nicira NVP device") +@APICommand(name = "addNiciraNvpDevice", responseObject=NiciraNvpDeviceResponse.class, description="Adds a Nicira NVP device") public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(AddNiciraNvpDeviceCmd.class.getName()); private static final String s_name = "addniciranvpdeviceresponse"; @@ -51,8 +43,8 @@ public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.HOST_NAME, type=CommandType.STRING, required = true, description="Hostname of ip address of the Nicira NVP Controller.") diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java index 9cc8d626bb5..12544410599 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java @@ -16,17 +16,17 @@ // under the License. package com.cloud.api.commands; +import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -37,7 +37,7 @@ import com.cloud.network.element.NiciraNvpElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a nicira nvp device") +@APICommand(name = "deleteNiciraNvpDevice", responseObject=SuccessResponse.class, description=" delete a nicira nvp device") public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(DeleteNiciraNvpDeviceCmd.class.getName()); private static final String s_name = "deleteniciranvpdeviceresponse"; @@ -47,8 +47,8 @@ public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required=true, description="Nicira device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + required=true, description="Nicira device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java index e8456cfa8f7..bea417d3687 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java @@ -19,30 +19,28 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a nicira nvp device") +@APICommand(name = "listNiciraNvpDeviceNetworks", responseObject=NetworkResponse.class, description="lists network that are using a nicira nvp device") public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNiciraNvpDeviceNetworksCmd.class.getName()); @@ -53,8 +51,8 @@ public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required = true, description="nicira nvp device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + required = true, description="nicira nvp device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java index f38cb16c8e9..04aab2a296a 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java @@ -19,17 +19,17 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -40,7 +40,7 @@ import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices") +@APICommand(name = "listNiciraNvpDevices", responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices") public class ListNiciraNvpDevicesCmd extends BaseListCmd { private static final Logger s_logger = Logger.getLogger(ListNiciraNvpDevicesCmd.class.getName()); private static final String s_name = "listniciranvpdeviceresponse"; @@ -50,12 +50,12 @@ public class ListNiciraNvpDevicesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, description="nicira nvp device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + description="nicira nvp device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java index e50be813879..097ecd975b2 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java @@ -16,39 +16,42 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; +import com.cloud.network.NiciraNvpDeviceVO; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=NiciraNvpDeviceVO.class) public class NiciraNvpDeviceResponse extends BaseResponse { @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID) @Param(description="device id of the Nicire Nvp") - private IdentityProxy id = new IdentityProxy("external_nicira_nvp_devices"); - + private String id; + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this Nirica Nvp belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME) @Param(description="device name") private String deviceName; - + @SerializedName(ApiConstants.HOST_NAME) @Param(description="the controller Ip address") private String hostName; - + @SerializedName(ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID) @Param(description="the transport zone Uuid") private String transportZoneUuid; - + @SerializedName(ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID) @Param(description="this L3 gateway service Uuid") private String l3GatewayServiceUuid; - - public void setId(long nvpDeviceId) { - this.id.setValue(nvpDeviceId); + + public void setId(String nvpDeviceId) { + this.id = nvpDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProviderName(String providerName) { @@ -59,13 +62,7 @@ public class NiciraNvpDeviceResponse extends BaseResponse { this.deviceName = deviceName; } - public void setId(IdentityProxy id) { - this.id = id; - } - public void setPhysicalNetworkId(IdentityProxy physicalNetworkId) { - this.physicalNetworkId = physicalNetworkId; - } public void setHostName(String hostName) { this.hostName = hostName; @@ -77,6 +74,6 @@ public class NiciraNvpDeviceResponse extends BaseResponse { public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { this.l3GatewayServiceUuid = l3GatewayServiceUuid; - } - + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java index af6620c722d..a1097b9ef1f 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; @@ -27,7 +29,7 @@ import javax.persistence.Table; @Entity @Table(name="external_nicira_nvp_devices") -public class NiciraNvpDeviceVO { +public class NiciraNvpDeviceVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java index 0779e691e70..4c948cc965b 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="nicira_nvp_nic_map") -public class NiciraNvpNicMappingVO { +public class NiciraNvpNicMappingVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java index 037ba699fc0..ced880fe619 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="nicira_nvp_router_map") -public class NiciraNvpRouterMappingVO { +public class NiciraNvpRouterMappingVO implements InternalIdentity { //FIXME the ddl for this table should be in one of the upgrade scripts @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java index de6a6293e60..de03fa26f25 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java @@ -27,6 +27,7 @@ import java.util.UUID; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.utils.PropertiesUtil; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -48,10 +49,10 @@ import com.cloud.agent.api.FindLogicalSwitchPortAnswer; import com.cloud.agent.api.FindLogicalSwitchPortCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupNiciraNvpCommand; -import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer; import com.cloud.agent.api.UpdateLogicalSwitchPortCommand; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddNiciraNvpDeviceCmd; import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd; import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd; @@ -71,7 +72,7 @@ import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.Network; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; @@ -84,6 +85,7 @@ import com.cloud.network.NetworkManager; import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.NiciraNvpNicMappingVO; import com.cloud.network.NiciraNvpRouterMappingVO; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -96,13 +98,9 @@ import com.cloud.network.dao.NiciraNvpRouterMappingDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.guru.NiciraNvpGuestNetworkGuru; import com.cloud.network.resource.NiciraNvpResource; -import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNat; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.offering.NetworkOffering; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; @@ -457,14 +455,14 @@ public class NiciraNvpElement extends AdapterBase implements } DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); - DeleteLogicalRouterAnswer answer = + DeleteLogicalRouterAnswer answer = (DeleteLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); if (answer.getResult() == false) { s_logger.error("Failed to delete LogicalRouter for network " + network.getDisplayText()); return false; } - + _niciraNvpRouterMappingDao.remove(routermapping.getId()); } @@ -522,7 +520,7 @@ public class NiciraNvpElement extends AdapterBase implements // L3 Support : Generic? capabilities.put(Service.Gateway, null); - + // L3 Support : SourceNat Map sourceNatCapabilities = new HashMap(); sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, @@ -532,16 +530,21 @@ public class NiciraNvpElement extends AdapterBase implements // L3 Support : Port Forwarding capabilities.put(Service.PortForwarding, null); - + // L3 support : StaticNat capabilities.put(Service.StaticNat, null); - + return capabilities; } @Override - public String getPropertiesFile() { - return "nicira-nvp_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(AddNiciraNvpDeviceCmd.class); + cmdList.add(DeleteNiciraNvpDeviceCmd.class); + cmdList.add(ListNiciraNvpDeviceNetworksCmd.class); + cmdList.add(ListNiciraNvpDevicesCmd.class); + return cmdList; } @Override @@ -593,8 +596,8 @@ public class NiciraNvpElement extends AdapterBase implements params.put("adminpass", cmd.getPassword()); params.put("transportzoneuuid", cmd.getTransportzoneUuid()); // FIXME What to do with multiple isolation types - params.put("transportzoneisotype", - physicalNetwork.getIsolationMethods().get(0).toLowerCase()); + params.put("transportzoneisotype", + physicalNetwork.getIsolationMethods().get(0).toLowerCase()); if (cmd.getL3GatewayServiceUuid() != null) { params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid()); } @@ -638,11 +641,14 @@ public class NiciraNvpElement extends AdapterBase implements NiciraNvpDeviceVO niciraNvpDeviceVO) { HostVO niciraNvpHost = _hostDao.findById(niciraNvpDeviceVO.getHostId()); _hostDao.loadDetails(niciraNvpHost); - + NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse(); response.setDeviceName(niciraNvpDeviceVO.getDeviceName()); - response.setPhysicalNetworkId(niciraNvpDeviceVO.getPhysicalNetworkId()); - response.setId(niciraNvpDeviceVO.getId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(niciraNvpDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + response.setId(niciraNvpDeviceVO.getUuid()); response.setProviderName(niciraNvpDeviceVO.getProviderName()); response.setHostName(niciraNvpHost.getDetail("ip")); response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid")); @@ -802,7 +808,7 @@ public class NiciraNvpElement extends AdapterBase implements /** * From interface IpDeployer - * + * * @param network * @param ipAddress * @param services @@ -826,7 +832,7 @@ public class NiciraNvpElement extends AdapterBase implements NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); _hostDao.loadDetails(niciraNvpHost); - + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao .findByNetworkId(network.getId()); if (routermapping == null) { @@ -834,12 +840,12 @@ public class NiciraNvpElement extends AdapterBase implements + network.getDisplayText()); return false; } - + List cidrs = new ArrayList(); for (PublicIpAddress ip : ipAddress) { cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); } - ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), + ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); //FIXME answer can be null if the host is down @@ -848,7 +854,7 @@ public class NiciraNvpElement extends AdapterBase implements else { s_logger.debug("No need to provision ip addresses as we are not providing L3 services."); } - + return true; } @@ -872,7 +878,7 @@ public class NiciraNvpElement extends AdapterBase implements } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao .findByNetworkId(network.getId()); if (routermapping == null) { @@ -881,23 +887,23 @@ public class NiciraNvpElement extends AdapterBase implements return false; } - List staticNatRules = new ArrayList(); + List staticNatRules = new ArrayList(); for (StaticNat rule : rules) { IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); // Force the nat rule into the StaticNatRuleTO, no use making a new TO object // we only need the source and destination ip. Unfortunately no mention if a rule // is new. - StaticNatRuleTO ruleTO = new StaticNatRuleTO(1, - sourceIp.getAddress().addr(), 0, 65535, + StaticNatRuleTO ruleTO = new StaticNatRuleTO(1, + sourceIp.getAddress().addr(), 0, 65535, rule.getDestIpAddress(), 0, 65535, "any", rule.isForRevoke(), false); staticNatRules.add(ruleTO); } - - ConfigureStaticNatRulesOnLogicalRouterCommand cmd = + + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); - + return answer.getResult(); } @@ -910,7 +916,7 @@ public class NiciraNvpElement extends AdapterBase implements if (!canHandle(network, Service.PortForwarding)) { return false; } - + List devices = _niciraNvpDao .listByPhysicalNetwork(network.getPhysicalNetworkId()); if (devices.isEmpty()) { @@ -920,7 +926,7 @@ public class NiciraNvpElement extends AdapterBase implements } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao .findByNetworkId(network.getId()); if (routermapping == null) { @@ -928,19 +934,19 @@ public class NiciraNvpElement extends AdapterBase implements + network.getDisplayText()); return false; } - - List portForwardingRules = new ArrayList(); + + List portForwardingRules = new ArrayList(); for (PortForwardingRule rule : rules) { IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId()); Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); PortForwardingRuleTO ruleTO = new PortForwardingRuleTO((PortForwardingRule) rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); portForwardingRules.add(ruleTO); } - - ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = + + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); - + return answer.getResult(); } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java index 43ac806ed94..b66f75c15e4 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java @@ -17,6 +17,8 @@ package com.cloud.network.ovs.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name=("ovs_tunnel_interface")) -public class OvsTunnelInterfaceVO { +public class OvsTunnelInterfaceVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java index d995c1c02af..4c99002f332 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java @@ -17,6 +17,8 @@ package com.cloud.network.ovs.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name=("ovs_tunnel_network")) -public class OvsTunnelNetworkVO { +public class OvsTunnelNetworkVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/plugins/pom.xml b/plugins/pom.xml index 820e76fc0e9..a42ae2967b1 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -32,6 +32,8 @@ test + api/discovery + acl/static-role-based deployment-planners/user-concentrated-pod deployment-planners/user-dispersing host-allocators/random diff --git a/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java index 43874f61cb7..358605a8c2e 100644 --- a/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java @@ -17,12 +17,10 @@ package com.cloud.server.auth; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.ejb.Local; -import javax.naming.AuthenticationException; import javax.naming.ConfigurationException; import javax.naming.Context; import javax.naming.NamingEnumeration; @@ -35,14 +33,12 @@ import javax.naming.directory.SearchResult; import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; -import com.cloud.api.ApiConstants.LDAPParams; -import com.cloud.configuration.Config; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.server.ManagementServer; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; diff --git a/pom.xml b/pom.xml index f3740326024..c440a660322 100644 --- a/pom.xml +++ b/pom.xml @@ -65,9 +65,10 @@ build213-svnkit-1.3-patch 1.5.0 1.7.1 + 14.0-rc1 5.6.100-1-SNAPSHOT 3.1 - 4.1 + 4.2.1 5.1.21 1.3.1 3.1.3 @@ -85,6 +86,7 @@ 1.3.21.1 2.6 1.4 + 0.9.8 @@ -242,7 +244,6 @@ dist/console-proxy/js/jquery.js scripts/vm/systemvm/id_rsa.cloud tools/devcloud/basebuild/puppet-devcloudinitial/files/network.conf - tools/devcloud/devcloud.cfg ui/lib/flot/jquery.colorhelpers.js ui/lib/flot/jquery.flot.crosshair.js ui/lib/flot/jquery.flot.fillbetween.js @@ -369,6 +370,7 @@ developer tools/apidoc tools/devcloud + tools/devcloud-kvm tools/marvin tools/cli diff --git a/python/lib/cloudutils/utilities.py b/python/lib/cloudutils/utilities.py index adf81fcbd4c..3f5f2a9dc8b 100755 --- a/python/lib/cloudutils/utilities.py +++ b/python/lib/cloudutils/utilities.py @@ -96,6 +96,10 @@ def writeProgressBar(msg, result): output = "[%-6s]\n"%"Failed" sys.stdout.write(output) sys.stdout.flush() + +class UnknownSystemException(Exception): + "This Excption is raised if the current operating enviornment is unknown" + pass class Distribution: def __init__(self): @@ -120,7 +124,7 @@ class Distribution: self.arch = bash("uname -m").getStdout() else: - self.distro = "Unknown" + raise UnknownSystemException def getVersion(self): return self.distro diff --git a/scripts/network/juniper/firewall-filter-term-add.xml b/scripts/network/juniper/firewall-filter-term-add.xml new file mode 100644 index 00000000000..e7f3a63f8e8 --- /dev/null +++ b/scripts/network/juniper/firewall-filter-term-add.xml @@ -0,0 +1,43 @@ + + + + + + +%filter-name% + +%term-name% + +%source-address-entries% + +%dest-ip-address% + +%protocol-options% + + +%count-name% + + + + + + + + diff --git a/scripts/network/juniper/firewall-filter-term-getone.xml b/scripts/network/juniper/firewall-filter-term-getone.xml new file mode 100644 index 00000000000..2c7e10dd354 --- /dev/null +++ b/scripts/network/juniper/firewall-filter-term-getone.xml @@ -0,0 +1,32 @@ + + + + + + +%filter-name% + +%term-name% + + + + + + diff --git a/scripts/network/juniper/template-entry.xml b/scripts/network/juniper/template-entry.xml new file mode 100644 index 00000000000..ab92d6d7d7d --- /dev/null +++ b/scripts/network/juniper/template-entry.xml @@ -0,0 +1,21 @@ + +<%name%> +%value% + diff --git a/scripts/storage/qcow2/resizevolume.sh b/scripts/storage/qcow2/resizevolume.sh new file mode 100644 index 00000000000..2de1f9ec5ca --- /dev/null +++ b/scripts/storage/qcow2/resizevolume.sh @@ -0,0 +1,253 @@ +#!/usr/bin/env bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + + +# resizevolume.sh -- resize a volume + +usage() { + printf "Usage: %s: -c -s -p -v -t -r \n" $(basename $0) >&2 +} + +getdevmappername() { + local path=$1 + local devmappername=`readlink -f $path |cut -d/ -f3` + if [[ $devmappername =~ "dm-" ]] + then + dmname=$devmappername + return 0 + else + return 1; + fi +} + +getdevmappersize() { + local dm=$1 + if [ ! -e "/sys/block/${dm}/size" ] + then + log "unable to find ${dm} in /sys/block" 1 + exit 1 + fi + actualsize=$((`cat /sys/block/${dm}/size`*512)); + + if [[ -z "$actualsize" ]] + then + log "unable to find actual size of ${dm}" 1 + exit 1 + fi + return 0 +} + +# log "message" 1 <-- prints to stdout as well as log, to pass error up to cloudstack +# log "message" prints only to log file +# variable shouldwelog controls whether we print to log file +log() { + local d=`date` + local msg=${1} + local stdout=${2} + + if [ ! -z "$stdout" ] + then + echo $1 + fi + + if [ $shouldwelog -eq 1 ] + then + echo "$d - $1" >> /var/log/cloud/agent/resizevolume.log + fi +} + +failshrink() { + # if this is a shrink operation, fail if commands will shrink the volume and we haven't signed of on shrinking + if [ $actualsize -gt $newsize ] + then + if [ "$shrink" == "false" ] + then + log "result would shrink the volume from $actualsize to $newsize, but confirmation to shrink wasn't passed. Shrink='$shrink'" 1 + exit 1 + fi + fi +} + +notifyqemu() { + #move this back into cloudstack libvirt calls once the libvirt java bindings support block resize + #we try to inform hypervisor of new size, but don't fail if we can't + if `virsh help 2>/dev/null | grep -q blockresize` + then + if `virsh domstate $vmname >/dev/null 2>&1` + then + sizeinkb=$(($newsize/1024)) + virsh blockresize --domain $vmname --path $path --size $sizeinkb >/dev/null 2>&1 + retval=$? + if [ -z $retval ] || [ $retval -ne 0 ] + then + log "failed to live resize $path to size of $sizeinkb kb" 1 + else + liveresize='true' + fi + fi + fi +} + +resizelvm() { + local dmname='' + local actualsize='' + local liveresize='false' + + ##### sanity checks ##### + if ! `lvresize --version > /dev/null 2>&1` + then + log "unable to resolve executable 'lvresize'" 1 + exit 1 + fi + + if ! `virsh --version > /dev/null 2>&1` + then + log "unable to resolve executable 'virsh'" 1 + exit 1 + fi + ##### end sanity ##### + + if ! getdevmappername $path + then + log "unable to resolve a device mapper dev from $path" 1 + exit 1 + fi + + getdevmappersize $dmname + + if [ $actualsize -ne $currentsize ] + then + log "disk isn't the size we think it is: cloudstack said $currentsize, disk said $actualsize." + fi + + # if this is a shrink operation, fail if commands will shrink the volume and we haven't signed of on shrinking + failshrink + + output=`lvresize -f -L ${newsize}B $path 2>&1` + retval=$? + + if [ -z $retval ] || [ $retval -ne 0 ] + then + log "lvresize failed: $output " 1 + exit 1 + fi + + #move this back into cloudstack libvirt calls once the libvirt java bindings support block resize + #we try to inform hypervisor of new size, but don't fail if we can't + notifyqemu + + log "performed successful resize - dm:$dmname currentsize:$currentsize newsize:$newsize path:$path type:$ptype vmname:$vmname live:$liveresize shrink:$shrink" +} + +resizeqcow2() { + + ##### sanity checks ##### + if [ ! -e "$path" ] + then + log "unable to find file $path" 1 + exit 1 + fi + + if ! `qemu-img info /dev/null > /dev/null 2>&1` + then + log "unable to resolve executable 'qemu-img'" 1 + exit 1 + fi + + if ! `virsh --version > /dev/null 2>&1` + then + log "unable to resolve executable 'virsh'" 1 + exit 1 + fi + ##### end sanity ##### + + $actualsize=`qemu-img info $path | grep "virtual size" | sed -re 's/^.*\(([0-9]+).*$/\1/g'` + + if [ $actualsize -ne $currentsize ] + then + log "disk isn't the size we think it is: cloudstack said $currentsize, disk said $actualsize." + fi + + # if this is a shrink operation, fail if commands will shrink the volume and we haven't signed of on shrinking + failshrink + + output=`qemu-img resize $path $newsize 2>&1` + retval=$? + + if [ -z $retval ] || [ $retval -ne 0 ] + then + log "qemu-img resize failed: $output" 1 + exit 1 + fi + + #move this back into cloudstack libvirt calls once the libvirt java bindings support block resize + #we try to inform hypervisor of new size, but don't fail if we can't + notifyqemu + + log "performed successful resize - currentsize:$currentsize newsize:$newsize path:$path type:$ptype vmname:$vmname live:$liveresize shrink:$shrink" +} + +sflag= +cflag= +pflag= +vflag= +tflag= +rflag= + +while getopts 'c:s:v:p:t:r:' OPTION +do + case $OPTION in + s) sflag=1 + newsize="$OPTARG" + ;; + c) cflag=1 + currentsize="$OPTARG" + ;; + v) vflag=1 + vmname="$OPTARG" + ;; + p) dflag=1 + path="$OPTARG" + ;; + t) tflag=1 + ptype="$OPTARG" + ;; + r) rflag=1 + shrink="$OPTARG" + ;; + ?) usage + exit 2 + ;; + esac +done + +shouldwelog=1 #set this to 1 while debugging to get output in /var/log/cloud/agent/resizevolume.log + +if [ "$ptype" == "CLVM" ] +then + resizelvm +elif [ "$ptype" == "QCOW2" ] +then + resizeqcow2 +else + echo "unsupported type $ptype" + exit 1; +fi + +exit 0 diff --git a/server/pom.xml b/server/pom.xml index 5ae926f9111..64bd2a206da 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -42,9 +42,15 @@ httpcore ${cs.httpcore.version} + + org.apache.httpcomponents + httpclient + ${cs.httpcore.version} + mysql mysql-connector-java + ${cs.mysql.version} provided @@ -98,6 +104,7 @@ com/cloud/storage/dao/* com/cloud/vm/dao/* com/cloud/vpc/* + com/cloud/api/ListPerfTest.java diff --git a/server/src/com/cloud/acl/DomainChecker.java b/server/src/com/cloud/acl/DomainChecker.java index ca7be9293b7..24f632ba9be 100755 --- a/server/src/com/cloud/acl/DomainChecker.java +++ b/server/src/com/cloud/acl/DomainChecker.java @@ -18,10 +18,11 @@ package com.cloud.acl; import javax.ejb.Local; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.api.BaseCmd; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; -import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.PermissionDeniedException; import com.cloud.network.Network; @@ -39,7 +40,7 @@ import com.cloud.user.dao.AccountDao; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.component.Inject; -@Local(value=SecurityChecker.class) +@Local(value = SecurityChecker.class) public class DomainChecker extends AdapterBase implements SecurityChecker { @Inject DomainDao _domainDao; @@ -52,14 +53,14 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { protected DomainChecker() { super(); } - + @Override public boolean checkAccess(Account caller, Domain domain) throws PermissionDeniedException { if (caller.getState() != Account.State.enabled) { throw new PermissionDeniedException(caller + " is disabled."); } long domainId = domain.getId(); - + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { if (caller.getDomainId() != domainId) { throw new PermissionDeniedException(caller + " does not have permission to operate within domain id=" + domain.getId()); @@ -67,7 +68,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } else if (!_domainDao.isChildDomain(caller.getDomainId(), domainId)) { throw new PermissionDeniedException(caller + " does not have permission to operate within domain id=" + domain.getId()); } - + return true; } @@ -83,15 +84,15 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { @Override public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException { if (entity instanceof VirtualMachineTemplate) { - - VirtualMachineTemplate template = (VirtualMachineTemplate)entity; + + VirtualMachineTemplate template = (VirtualMachineTemplate) entity; Account owner = _accountDao.findById(template.getAccountId()); // validate that the template is usable by the account if (!template.isPublicTemplate()) { if (BaseCmd.isRootAdmin(caller.getType()) || (owner.getId() == caller.getId())) { return true; } - + // since the current account is not the owner of the template, check the launch permissions table to see if the // account can launch a VM from this template LaunchPermissionVO permission = _launchPermissionDao.findByTemplateAndAccount(template.getId(), caller.getId()); @@ -106,31 +107,31 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } } } - + return true; } else if (entity instanceof Network && accessType != null && accessType == AccessType.UseNetwork) { - _networkMgr.checkNetworkPermissions(caller, (Network)entity); + _networkMgr.checkNetworkPermissions(caller, (Network) entity); } else { if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { Account account = _accountDao.findById(entity.getAccountId()); - + if (account != null && account.getType() == Account.ACCOUNT_TYPE_PROJECT) { //only project owner can delete/modify the project if (accessType != null && accessType == AccessType.ModifyProject) { if (!_projectMgr.canModifyProjectAccount(caller, account.getId())) { throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity); } - } else if (!_projectMgr.canAccessProjectAccount(caller, account.getId())){ + } else if (!_projectMgr.canAccessProjectAccount(caller, account.getId())) { throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity); } } else { if (caller.getId() != entity.getAccountId()) { throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity); } - } + } } } - + return true; } @@ -140,168 +141,142 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { return checkAccess(account, entity, null); } - @Override - public boolean checkAccess(Account account, DiskOffering dof) throws PermissionDeniedException - { - if(account == null || dof.getDomainId() == null) - {//public offering - return true; - } - else - { - //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN) - { - return true; - } - //if account is normal user or domain admin - //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for disk offering) - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - { - if(account.getDomainId() == dof.getDomainId()) - { - return true; //disk offering and account at exact node - } - else - { - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true) - { - if(domainRecord.getId() == dof.getDomainId()) - { - //found as a child - return true; - } - if(domainRecord.getParent() != null) { + @Override + public boolean checkAccess(Account account, DiskOffering dof) throws PermissionDeniedException { + if (account == null || dof.getDomainId() == null) {//public offering + return true; + } else { + //admin has all permissions + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + return true; + } + //if account is normal user or domain admin + //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for disk offering) + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == dof.getDomainId()) { + return true; //disk offering and account at exact node + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == dof.getDomainId()) { + //found as a child + return true; + } + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; } - } - } - } - } - } - //not found - return false; - } + } + } + } + } + } + //not found + return false; + } - @Override - public boolean checkAccess(Account account, ServiceOffering so) throws PermissionDeniedException - { - if(account == null || so.getDomainId() == null) - {//public offering - return true; - } - else - { - //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN) - { - return true; - } - //if account is normal user or domain admin - //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for service offering) - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - { - if(account.getDomainId() == so.getDomainId()) - { - return true; //service offering and account at exact node - } - else - { - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true) - { - if(domainRecord.getId() == so.getDomainId()) - { - //found as a child - return true; - } - if(domainRecord.getParent() != null) { + @Override + public boolean checkAccess(Account account, ServiceOffering so) throws PermissionDeniedException { + if (account == null || so.getDomainId() == null) {//public offering + return true; + } else { + //admin has all permissions + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + return true; + } + //if account is normal user or domain admin + //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for service offering) + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == so.getDomainId()) { + return true; //service offering and account at exact node + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == so.getDomainId()) { + //found as a child + return true; + } + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; } - } - } - } - } - } - //not found - return false; - } - - @Override - public boolean checkAccess(Account account, DataCenter zone) throws PermissionDeniedException { - if(account == null || zone.getDomainId() == null){//public zone - return true; - }else{ - //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN){ - return true; - } - //if account is normal user - //check if account's domain is a child of zone's domain - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_PROJECT){ - if(account.getDomainId() == zone.getDomainId()){ - return true; //zone and account at exact node - }else{ - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true){ - if(domainRecord.getId() == zone.getDomainId()){ - //found as a child - return true; - } - if(domainRecord.getParent() != null) { + } + } + } + } + } + //not found + return false; + } + + @Override + public boolean checkAccess(Account account, DataCenter zone) throws PermissionDeniedException { + if (account == null || zone.getDomainId() == null) {//public zone + return true; + } else { + //admin has all permissions + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + return true; + } + //if account is normal user + //check if account's domain is a child of zone's domain + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + if (account.getDomainId() == zone.getDomainId()) { + return true; //zone and account at exact node + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == zone.getDomainId()) { + //found as a child + return true; + } + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; } - } - } - } - //not found - return false; - } - //if account is domain admin - //check if the account's domain is either child of zone's domain, or if zone's domain is child of account's domain - else if(account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ - if(account.getDomainId() == zone.getDomainId()){ - return true; //zone and account at exact node - }else{ - DomainVO zoneDomainRecord = _domainDao.findById(zone.getDomainId()); - DomainVO accountDomainRecord = _domainDao.findById(account.getDomainId()); - if(accountDomainRecord != null) - { - DomainVO localRecord = accountDomainRecord; - while(true){ - if(localRecord.getId() == zone.getDomainId()){ - //found as a child - return true; - } - if(localRecord.getParent() != null) { + } + } + } + //not found + return false; + } + //if account is domain admin + //check if the account's domain is either child of zone's domain, or if zone's domain is child of account's domain + else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == zone.getDomainId()) { + return true; //zone and account at exact node + } else { + Domain zoneDomainRecord = _domainDao.findById(zone.getDomainId()); + Domain accountDomainRecord = _domainDao.findById(account.getDomainId()); + if (accountDomainRecord != null) { + Domain localRecord = accountDomainRecord; + while (true) { + if (localRecord.getId() == zone.getDomainId()) { + //found as a child + return true; + } + if (localRecord.getParent() != null) { localRecord = _domainDao.findById(localRecord.getParent()); } else { break; } - } - } - //didn't find in upper tree - if(zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())){ - return true; - } - } - //not found - return false; - } - } - return false; - } + } + } + //didn't find in upper tree + if (zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())) { + return true; + } + } + //not found + return false; + } + } + return false; + } } diff --git a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index 1b6dc44a1a3..ca0bf5cb60d 100755 --- a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -53,6 +53,7 @@ import com.cloud.agent.api.TransferAgentCommand; import com.cloud.agent.transport.Request; import com.cloud.agent.transport.Request.Version; import com.cloud.agent.transport.Response; +import com.cloud.api.ApiDBUtils; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ClusteredAgentRebalanceService; @@ -92,13 +93,13 @@ import com.cloud.utils.nio.Task; public class ClusteredAgentManagerImpl extends AgentManagerImpl implements ClusterManagerListener, ClusteredAgentRebalanceService { final static Logger s_logger = Logger.getLogger(ClusteredAgentManagerImpl.class); private static final ScheduledExecutorService s_transferExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Cluster-AgentTransferExecutor")); - private final long rebalanceTimeOut = 300000; // 5 mins - after this time remove the agent from the transfer list + private final long rebalanceTimeOut = 300000; // 5 mins - after this time remove the agent from the transfer list public final static long STARTUP_DELAY = 5000; public final static long SCAN_INTERVAL = 90000; // 90 seconds, it takes 60 sec for xenserver to fail login public final static int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 5; // 5 seconds public long _loadSize = 100; - protected Set _agentToTransferIds = new HashSet(); + protected Set _agentToTransferIds = new HashSet(); @Inject protected ClusterManager _clusterMgr = null; @@ -111,10 +112,10 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust protected ManagementServerHostDao _mshostDao; @Inject protected HostTransferMapDao _hostTransferDao; - + @Inject(adapter = AgentLoadBalancerPlanner.class) protected Adapters _lbPlanners; - + @Inject protected AgentManager _agentMgr; @@ -127,7 +128,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust _peers = new HashMap(7); _sslEngines = new HashMap(7); _nodeId = _clusterMgr.getManagementNodeId(); - + s_logger.info("Configuring ClusterAgentManagerImpl. management server node id(msid): " + _nodeId); ConfigurationDao configDao = ComponentLocator.getCurrentLocator().getDao(ConfigurationDao.class); @@ -138,7 +139,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust ClusteredAgentAttache.initialize(this); _clusterMgr.registerListener(this); - + return super.configure(name, xmlParams); } @@ -172,7 +173,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust List hosts = _hostDao.findAndUpdateDirectAgentToLoad(cutSeconds, _loadSize, _nodeId); List appliances = _hostDao.findAndUpdateApplianceToLoad(cutSeconds, _nodeId); hosts.addAll(appliances); - + if (hosts != null && hosts.size() > 0) { s_logger.debug("Found " + hosts.size() + " unmanaged direct hosts, processing connect for them..."); for (HostVO host : hosts) { @@ -273,12 +274,12 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event, boolean transitState) { return handleDisconnect(attache, event, false, true); } - + @Override protected boolean handleDisconnectWithInvestigation(AgentAttache attache, Status.Event event) { return handleDisconnect(attache, event, true, true); } - + protected boolean handleDisconnect(AgentAttache agent, Status.Event event, boolean investigate, boolean broadcast) { boolean res; if (!investigate) { @@ -316,7 +317,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } } - + //don't process disconnect if the disconnect came for the host via delayed cluster notification, //but the host has already reconnected to the current management server if (!attache.forForward()) { @@ -324,7 +325,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust + hostId +" as the host is directly connected to the current management server " + _nodeId); return true; } - + return super.handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, false); } @@ -346,7 +347,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.debug("cannot propagate agent reconnect because agent is not available", e); return false; } - + return super.reconnect(hostId); } @@ -408,7 +409,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public String findPeer(long hostId) { return _clusterMgr.getPeerName(hostId); } - + public SSLEngine getSSLEngine(String peerName) { return _sslEngines.get(peerName); } @@ -516,7 +517,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } if (agent == null) { AgentUnavailableException ex = new AgentUnavailableException("Host with specified id is not in the right state: " + host.getStatus(), hostId); - ex.addProxyObject(host, hostId, "hostId"); + ex.addProxyObject(ApiDBUtils.findHostById(hostId).getUuid()); throw ex; } @@ -535,11 +536,11 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } _timer.cancel(); - + //cancel all transfer tasks s_transferExecutor.shutdownNow(); cleanupTransferMap(_nodeId); - + return super.stop(); } @@ -705,7 +706,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } return result; } - + @Override public void scheduleRebalanceAgents() { _timer.schedule(new AgentLoadBalancerTask(), 30000); @@ -743,7 +744,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } } - + public void startRebalanceAgents() { s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); @@ -762,7 +763,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } return; } - + if (avLoad == 0L) { if (s_logger.isDebugEnabled()) { s_logger.debug("As calculated average load is less than 1, rounding it to 1"); @@ -772,7 +773,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust for (ManagementServerHostVO node : allMS) { if (node.getMsid() != _nodeId) { - + List hostsToRebalance = new ArrayList(); for (AgentLoadBalancerPlanner lbPlanner : _lbPlanners) { hostsToRebalance = lbPlanner.getHostsToRebalance(node.getMsid(), avLoad); @@ -783,20 +784,20 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } - + if (hostsToRebalance != null && !hostsToRebalance.isEmpty()) { s_logger.debug("Found " + hostsToRebalance.size() + " hosts to rebalance from management server " + node.getMsid()); for (HostVO host : hostsToRebalance) { long hostId = host.getId(); s_logger.debug("Asking management server " + node.getMsid() + " to give away host id=" + hostId); boolean result = true; - + if (_hostTransferDao.findById(hostId) != null) { s_logger.warn("Somebody else is already rebalancing host id: " + hostId); continue; } - HostTransferMapVO transfer = null; + HostTransferMapVO transfer = null; try { transfer = _hostTransferDao.startAgentTransfering(hostId, node.getMsid(), _nodeId); Answer[] answer = sendRebalanceCommand(node.getMsid(), hostId, node.getMsid(), _nodeId, Event.RequestAgentRebalance); @@ -862,7 +863,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust for (Iterator iterator = _agentToTransferIds.iterator(); iterator.hasNext();) { Long hostId = iterator.next(); AgentAttache attache = findAttache(hostId); - + // if the thread: // 1) timed out waiting for the host to reconnect // 2) recipient management server is not active any more @@ -878,22 +879,22 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust _hostTransferDao.completeAgentTransfer(hostId); continue; } - + if (transferMap.getInitialOwner() != _nodeId || attache == null || attache.forForward()) { s_logger.debug("Management server " + _nodeId + " doesn't own host id=" + hostId + " any more, skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; } - + ManagementServerHostVO ms = _mshostDao.findByMsid(transferMap.getFutureOwner()); if (ms != null && ms.getState() != ManagementServerHost.State.Up) { s_logger.debug("Can't transfer host " + hostId + " as it's future owner is not in UP state: " + ms + ", skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); continue; - } - + } + if (attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { iterator.remove(); try { @@ -902,9 +903,9 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Failed to submit rebalance task for host id=" + hostId + "; postponing the execution"); continue; } - + } else { - s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + " and listener queue size is " + attache.getNonRecurringListenersSize()); + s_logger.debug("Agent " + hostId + " can't be transfered yet as its request queue size is " + attache.getQueueSize() + " and listener queue size is " + attache.getNonRecurringListenersSize()); } } } else { @@ -920,16 +921,16 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } }; } - - + + private boolean setToWaitForRebalance(final long hostId, long currentOwnerId, long futureOwnerId) { s_logger.debug("Adding agent " + hostId + " to the list of agents to transfer"); synchronized (_agentToTransferIds) { return _agentToTransferIds.add(hostId); } } - - + + protected boolean rebalanceHost(final long hostId, long currentOwnerId, long futureOwnerId) throws AgentUnavailableException{ boolean result = true; @@ -949,7 +950,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Host " + hostId + " failed to connect to the management server " + futureOwnerId + " as a part of rebalance process", ex); result = false; } - + if (result) { s_logger.debug("Successfully transfered host id=" + hostId + " to management server " + futureOwnerId); finishRebalance(hostId, futureOwnerId, Event.RebalanceCompleted); @@ -957,7 +958,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Failed to transfer host id=" + hostId + " to management server " + futureOwnerId); finishRebalance(hostId, futureOwnerId, Event.RebalanceFailed); } - + } else if (futureOwnerId == _nodeId) { HostVO host = _hostDao.findById(hostId); try { @@ -976,15 +977,15 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } result = loadDirectlyConnectedHost(host, true); } else { - s_logger.warn("Failed to disconnect " + host.getId() + "(" + host.getName() + + s_logger.warn("Failed to disconnect " + host.getId() + "(" + host.getName() + " as a part of rebalance process without notification"); } - + } catch (Exception ex) { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process due to:", ex); result = false; } - + if (result) { s_logger.debug("Successfully loaded directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); } else { @@ -994,7 +995,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust return result; } - + protected void finishRebalance(final long hostId, long futureOwnerId, Event event){ @@ -1002,21 +1003,21 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (s_logger.isDebugEnabled()) { s_logger.debug("Finishing rebalancing for the agent " + hostId + " with event " + event); } - + AgentAttache attache = findAttache(hostId); if (attache == null || !(attache instanceof ClusteredAgentAttache)) { s_logger.debug("Unable to find forward attache for the host id=" + hostId + ", assuming that the agent disconnected already"); _hostTransferDao.completeAgentTransfer(hostId); return; - } - + } + ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)attache; - + if (success) { //1) Set transfer mode to false - so the agent can start processing requests normally forwardAttache.setTransferMode(false); - + //2) Get all transfer requests and route them to peer Request requestToTransfer = forwardAttache.getRequestToTransfer(); while (requestToTransfer != null) { @@ -1025,20 +1026,20 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust if (!routeResult) { logD(requestToTransfer.getBytes(), "Failed to route request to peer"); } - + requestToTransfer = forwardAttache.getRequestToTransfer(); } - + s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance to " + futureOwnerId); - + } else { failRebalance(hostId); } - + s_logger.debug("Management server " + _nodeId + " completed agent " + hostId + " rebalance"); _hostTransferDao.completeAgentTransfer(hostId); } - + protected void failRebalance(final long hostId){ try { s_logger.debug("Management server " + _nodeId + " failed to rebalance agent " + hostId); @@ -1048,15 +1049,15 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust s_logger.warn("Failed to reconnect host id=" + hostId + " as a part of failed rebalance task cleanup"); } } - + protected boolean startRebalance(final long hostId) { HostVO host = _hostDao.findById(hostId); - + if (host == null || host.getRemoved() != null) { s_logger.warn("Unable to find host record, fail start rebalancing process"); return false; - } - + } + synchronized (_agents) { ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { @@ -1081,27 +1082,27 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust _hostTransferDao.startAgentTransfer(hostId); return true; } - + protected void cleanupTransferMap(long msId) { List hostsJoingingCluster = _hostTransferDao.listHostsJoiningCluster(msId); - + for (HostTransferMapVO hostJoingingCluster : hostsJoingingCluster) { _hostTransferDao.remove(hostJoingingCluster.getId()); } - + List hostsLeavingCluster = _hostTransferDao.listHostsLeavingCluster(msId); for (HostTransferMapVO hostLeavingCluster : hostsLeavingCluster) { _hostTransferDao.remove(hostLeavingCluster.getId()); } } - - + + protected class RebalanceTask implements Runnable { Long hostId = null; Long currentOwnerId = null; Long futureOwnerId = null; - - + + public RebalanceTask(long hostId, long currentOwnerId, long futureOwnerId) { this.hostId = hostId; this.currentOwnerId = currentOwnerId; @@ -1122,5 +1123,5 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } } } - + } diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java index 3909f13ea94..a4c0facc97d 100755 --- a/server/src/com/cloud/alert/AlertManagerImpl.java +++ b/server/src/com/cloud/alert/AlertManagerImpl.java @@ -70,7 +70,6 @@ import com.cloud.storage.StoragePoolVO; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index d2abc29a888..dfdeb9c0957 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -17,13 +17,62 @@ package com.cloud.api; import java.util.ArrayList; -import java.util.Hashtable; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; + +import com.cloud.api.query.dao.AccountJoinDao; +import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.HostJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.StoragePoolJoinDao; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.dao.VolumeJoinDao; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; +import com.cloud.async.dao.AsyncJobDao; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; @@ -44,6 +93,8 @@ import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; +import com.cloud.event.Event; +import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; @@ -64,37 +115,61 @@ import com.cloud.network.NetworkModel; import com.cloud.network.NetworkProfile; import com.cloud.network.NetworkRuleConfigVO; import com.cloud.network.NetworkVO; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.Site2SiteCustomerGatewayVO; import com.cloud.network.Networks.TrafficType; import com.cloud.network.as.AutoScalePolicy; import com.cloud.network.as.AutoScalePolicyConditionMapVO; +import com.cloud.network.as.AutoScalePolicyVO; import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; +import com.cloud.network.as.AutoScaleVmGroupVO; +import com.cloud.network.as.AutoScaleVmProfileVO; import com.cloud.network.as.ConditionVO; import com.cloud.network.as.CounterVO; import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; import com.cloud.network.as.dao.AutoScalePolicyDao; +import com.cloud.network.as.dao.AutoScaleVmGroupDao; import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; +import com.cloud.network.as.dao.AutoScaleVmProfileDao; import com.cloud.network.as.dao.ConditionDao; import com.cloud.network.as.dao.CounterDao; import com.cloud.network.dao.FirewallRulesCidrsDao; +import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.NetworkDomainDao; import com.cloud.network.dao.NetworkRuleConfigDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; +import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; +import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; import com.cloud.network.dao.Site2SiteVpnGatewayDao; import com.cloud.network.dao.Site2SiteCustomerGatewayDao; +import com.cloud.network.router.VirtualRouter; +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.dao.SecurityGroupDao; +import com.cloud.network.vpc.StaticRouteVO; +import com.cloud.network.vpc.VpcGatewayVO; import com.cloud.network.vpc.VpcManager; +import com.cloud.network.vpc.VpcOffering; +import com.cloud.network.vpc.VpcVO; +import com.cloud.network.vpc.dao.StaticRouteDao; +import com.cloud.network.vpc.dao.VpcGatewayDao; +import com.cloud.network.vpc.dao.VpcOfferingDao; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.projects.Project; +import com.cloud.projects.ProjectAccount; +import com.cloud.projects.ProjectInvitation; import com.cloud.projects.ProjectService; import com.cloud.resource.ResourceManager; import com.cloud.server.Criteria; @@ -112,6 +187,7 @@ import com.cloud.storage.Snapshot; import com.cloud.storage.SnapshotVO; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; +import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StorageStats; import com.cloud.storage.UploadVO; @@ -119,6 +195,7 @@ import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateS3VO; import com.cloud.storage.VMTemplateSwiftVO; import com.cloud.storage.VMTemplateVO; +import com.cloud.storage.Volume; import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeHostVO; import com.cloud.storage.VolumeVO; @@ -126,6 +203,7 @@ import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.UploadDao; import com.cloud.storage.dao.VMTemplateDao; @@ -135,12 +213,14 @@ import com.cloud.storage.dao.VMTemplateS3Dao; import com.cloud.storage.dao.VMTemplateSwiftDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeHostDao; +import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.user.Account; import com.cloud.user.AccountDetailsDao; import com.cloud.user.AccountVO; import com.cloud.user.ResourceLimitService; import com.cloud.user.SSHKeyPairVO; import com.cloud.user.User; +import com.cloud.user.UserAccount; import com.cloud.user.UserStatisticsVO; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; @@ -153,6 +233,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.InstanceGroup; import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.NicProfile; import com.cloud.vm.UserVmDetailVO; @@ -164,9 +245,9 @@ import com.cloud.vm.VmStats; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.UserVmData; import com.cloud.vm.dao.UserVmDetailsDao; import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.network.vpc.dao.VpcDao; public class ApiDBUtils { private static ManagementServer _ms; @@ -185,12 +266,14 @@ public class ApiDBUtils { private static DiskOfferingDao _diskOfferingDao; private static DomainDao _domainDao; private static DomainRouterDao _domainRouterDao; + private static DomainRouterJoinDao _domainRouterJoinDao; private static GuestOSDao _guestOSDao; private static GuestOSCategoryDao _guestOSCategoryDao; private static HostDao _hostDao; private static IPAddressDao _ipAddressDao; private static LoadBalancerDao _loadBalancerDao; private static SecurityGroupDao _securityGroupDao; + private static SecurityGroupJoinDao _securityGroupJoinDao; private static NetworkRuleConfigDao _networkRuleConfigDao; private static HostPodDao _podDao; private static ServiceOfferingDao _serviceOfferingDao; @@ -205,6 +288,7 @@ public class ApiDBUtils { private static UserDao _userDao; private static UserStatisticsDao _userStatsDao; private static UserVmDao _userVmDao; + private static UserVmJoinDao _userVmJoinDao; private static VlanDao _vlanDao; private static VolumeDao _volumeDao; private static Site2SiteVpnGatewayDao _site2SiteVpnGatewayDao; @@ -213,6 +297,7 @@ public class ApiDBUtils { private static DataCenterDao _zoneDao; private static NetworkOfferingDao _networkOfferingDao; private static NetworkDao _networkDao; + private static PhysicalNetworkDao _physicalNetworkDao; private static ConfigurationService _configMgr; private static ConfigurationDao _configDao; private static ConsoleProxyDao _consoleProxyDao; @@ -233,7 +318,32 @@ public class ApiDBUtils { private static AutoScalePolicyConditionMapDao _asPolicyConditionMapDao; private static AutoScaleVmGroupPolicyMapDao _asVmGroupPolicyMapDao; private static AutoScalePolicyDao _asPolicyDao; + private static AutoScaleVmProfileDao _asVmProfileDao; + private static AutoScaleVmGroupDao _asVmGroupDao; private static CounterDao _counterDao; + private static ResourceTagJoinDao _tagJoinDao; + private static EventJoinDao _eventJoinDao; + private static InstanceGroupJoinDao _vmGroupJoinDao; + private static UserAccountJoinDao _userAccountJoinDao; + private static ProjectJoinDao _projectJoinDao; + private static ProjectAccountJoinDao _projectAccountJoinDao; + private static ProjectInvitationJoinDao _projectInvitationJoinDao; + private static HostJoinDao _hostJoinDao; + private static VolumeJoinDao _volJoinDao; + private static StoragePoolJoinDao _poolJoinDao; + private static AccountJoinDao _accountJoinDao; + private static AsyncJobJoinDao _jobJoinDao; + + private static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; + private static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; + private static FirewallRulesDao _firewallRuleDao; + private static StaticRouteDao _staticRouteDao; + private static VpcGatewayDao _vpcGatewayDao; + private static VpcDao _vpcDao; + private static VpcOfferingDao _vpcOfferingDao; + private static SnapshotPolicyDao _snapshotPolicyDao; + private static AsyncJobDao _asyncJobDao; + static { _ms = (ManagementServer) ComponentLocator.getComponent(ManagementServer.Name); ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); @@ -252,6 +362,7 @@ public class ApiDBUtils { _diskOfferingDao = locator.getDao(DiskOfferingDao.class); _domainDao = locator.getDao(DomainDao.class); _domainRouterDao = locator.getDao(DomainRouterDao.class); + _domainRouterJoinDao = locator.getDao(DomainRouterJoinDao.class); _guestOSDao = locator.getDao(GuestOSDao.class); _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _hostDao = locator.getDao(HostDao.class); @@ -271,6 +382,7 @@ public class ApiDBUtils { _userDao = locator.getDao(UserDao.class); _userStatsDao = locator.getDao(UserStatisticsDao.class); _userVmDao = locator.getDao(UserVmDao.class); + _userVmJoinDao = locator.getDao(UserVmJoinDao.class); _vlanDao = locator.getDao(VlanDao.class); _volumeDao = locator.getDao(VolumeDao.class); _site2SiteVpnGatewayDao = locator.getDao(Site2SiteVpnGatewayDao.class); @@ -278,8 +390,10 @@ public class ApiDBUtils { _volumeHostDao = locator.getDao(VolumeHostDao.class); _zoneDao = locator.getDao(DataCenterDao.class); _securityGroupDao = locator.getDao(SecurityGroupDao.class); + _securityGroupJoinDao = locator.getDao(SecurityGroupJoinDao.class); _networkOfferingDao = locator.getDao(NetworkOfferingDao.class); _networkDao = locator.getDao(NetworkDao.class); + _physicalNetworkDao = locator.getDao(PhysicalNetworkDao.class); _configDao = locator.getDao(ConfigurationDao.class); _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); _firewallCidrsDao = locator.getDao(FirewallRulesCidrsDao.class); @@ -299,8 +413,30 @@ public class ApiDBUtils { _asPolicyConditionMapDao = locator.getDao(AutoScalePolicyConditionMapDao.class); _counterDao = locator.getDao(CounterDao.class); _asVmGroupPolicyMapDao = locator.getDao(AutoScaleVmGroupPolicyMapDao.class); - _asVmGroupPolicyMapDao = locator.getDao(AutoScaleVmGroupPolicyMapDao.class); - _counterDao = locator.getDao(CounterDao.class); + _tagJoinDao = locator.getDao(ResourceTagJoinDao.class); + _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); + _eventJoinDao = locator.getDao(EventJoinDao.class); + _userAccountJoinDao = locator.getDao(UserAccountJoinDao.class); + _projectJoinDao = locator.getDao(ProjectJoinDao.class); + _projectAccountJoinDao = locator.getDao(ProjectAccountJoinDao.class); + _projectInvitationJoinDao = locator.getDao(ProjectInvitationJoinDao.class); + _hostJoinDao = locator.getDao(HostJoinDao.class); + _volJoinDao = locator.getDao(VolumeJoinDao.class); + _poolJoinDao = locator.getDao(StoragePoolJoinDao.class); + _accountJoinDao = locator.getDao(AccountJoinDao.class); + _jobJoinDao = locator.getDao(AsyncJobJoinDao.class); + + _physicalNetworkTrafficTypeDao = locator.getDao(PhysicalNetworkTrafficTypeDao.class); + _physicalNetworkServiceProviderDao = locator.getDao(PhysicalNetworkServiceProviderDao.class); + _firewallRuleDao = locator.getDao(FirewallRulesDao.class); + _staticRouteDao = locator.getDao(StaticRouteDao.class); + _vpcGatewayDao = locator.getDao(VpcGatewayDao.class); + _asVmProfileDao = locator.getDao(AutoScaleVmProfileDao.class); + _asVmGroupDao = locator.getDao(AutoScaleVmGroupDao.class); + _vpcDao = locator.getDao(VpcDao.class); + _vpcOfferingDao = locator.getDao(VpcOfferingDao.class); + _snapshotPolicyDao = locator.getDao(SnapshotPolicyDao.class); + _asyncJobDao = locator.getDao(AsyncJobDao.class); // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned _statsCollector = StatsCollector.getInstance(); @@ -351,7 +487,7 @@ public class ApiDBUtils { return _ms.getVersion(); } - public static List searchForUserVMs(Criteria c, List permittedAccounts) { + public static List searchForUserVMs(Criteria c, List permittedAccounts) { return _userVmMgr.searchForUserVMs(c, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), null, false, permittedAccounts, false, null, null).first(); } @@ -374,6 +510,10 @@ public class ApiDBUtils { return _resourceLimitMgr.findCorrectResourceLimitForAccount(account, type); } + public static long findCorrectResourceLimit(Long limit, short accountType, ResourceType type) { + return _resourceLimitMgr.findCorrectResourceLimitForAccount(accountType, limit, type); + } + public static AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { return _asyncMgr.findInstancePendingAsyncJob(instanceType, instanceId); } @@ -405,8 +545,8 @@ public class ApiDBUtils { return _storageMgr.getStoragePoolTags(poolId); } - public static boolean isLocalStorageActiveOnHost(Host host) { - return _storageMgr.isLocalStorageActiveOnHost(host); + public static boolean isLocalStorageActiveOnHost(Long hostId) { + return _storageMgr.isLocalStorageActiveOnHost(hostId); } public static InstanceGroupVO findInstanceGroupForVM(long vmId) { @@ -472,7 +612,7 @@ public class ApiDBUtils { public static DomainVO findDomainByIdIncludingRemoved(Long domainId) { return _domainDao.findByIdIncludingRemoved(domainId); } - + public static boolean isChildDomain(long parentId, long childId) { return _domainDao.isChildDomain(parentId, childId); } @@ -613,11 +753,11 @@ public class ApiDBUtils { public static Site2SiteVpnGatewayVO findVpnGatewayById(Long vpnGatewayId) { return _site2SiteVpnGatewayDao.findById(vpnGatewayId); } - - public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { - return _site2SiteCustomerGatewayDao.findById(customerGatewayId); + + public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { + return _site2SiteCustomerGatewayDao.findById(customerGatewayId); } - + public static List listUsersByAccount(long accountId) { return _userDao.listByAccount(accountId); } @@ -694,6 +834,14 @@ public class ApiDBUtils { return _vlanDao.listVlansByNetworkId(networkId); } + public static PhysicalNetworkVO findPhysicalNetworkById(long id) { + return _physicalNetworkDao.findById(id); + } + + public static PhysicalNetworkTrafficTypeVO findPhysicalNetworkTrafficTypeById(long id) { + return _physicalNetworkTrafficTypeDao.findById(id); + } + public static NetworkVO findNetworkById(long id) { return _networkDao.findById(id); } @@ -760,10 +908,6 @@ public class ApiDBUtils { return _firewallCidrsDao.getSourceCidrs(id); } - public static Hashtable listVmDetails(Hashtable vmData){ - return _userVmDao.listVmDetails(vmData); - } - public static Account getProjectOwner(long projectId) { return _projectMgr.getProjectOwner(projectId); } @@ -771,11 +915,11 @@ public class ApiDBUtils { public static Project findProjectByProjectAccountId(long projectAccountId) { return _projectMgr.findByProjectAccountId(projectAccountId); } - + public static Project findProjectByProjectAccountIdIncludingRemoved(long projectAccountId) { return _projectMgr.findByProjectAccountIdIncludingRemoved(projectAccountId); } - + public static Project findProjectById(long projectId) { return _projectMgr.getProject(projectId); } @@ -829,15 +973,15 @@ public class ApiDBUtils { public static String getHaTag() { return _haMgr.getHaTag(); } - + public static Map> listVpcOffServices(long vpcOffId) { return _vpcMgr.getVpcOffSvcProvidersMap(vpcOffId); } - + public static List listVpcNetworks(long vpcId) { return _networkModel.listNetworksByVpc(vpcId); } - + public static boolean canUseForDeploy(Network network) { return _networkModel.canUseForDeploy(network); } @@ -845,7 +989,7 @@ public class ApiDBUtils { public static String getUuid(String resourceId, TaggedResourceType resourceType) { return _taggedResourceService.getUuid(resourceId, resourceType); } - + public static boolean isOfferingForVpc(NetworkOffering offering) { boolean vpcProvider = _configMgr.isOfferingForVpc(offering); return vpcProvider; @@ -903,4 +1047,356 @@ public class ApiDBUtils { public static CounterVO getCounter(long counterId) { return _counterDao.findById(counterId); - }} + } + + public static ConditionVO findConditionById(long conditionId){ + return _asConditionDao.findById(conditionId); + } + + public static PhysicalNetworkServiceProviderVO findPhysicalNetworkServiceProviderById(long providerId){ + return _physicalNetworkServiceProviderDao.findById(providerId); + } + + public static FirewallRuleVO findFirewallRuleById(long ruleId){ + return _firewallRuleDao.findById(ruleId); + } + + public static StaticRouteVO findStaticRouteById(long routeId){ + return _staticRouteDao.findById(routeId); + } + + public static VpcGatewayVO findVpcGatewayById(long gatewayId){ + return _vpcGatewayDao.findById(gatewayId); + } + + public static AutoScalePolicyVO findAutoScalePolicyById(long policyId){ + return _asPolicyDao.findById(policyId); + } + + public static AutoScaleVmProfileVO findAutoScaleVmProfileById(long profileId){ + return _asVmProfileDao.findById(profileId); + } + + public static AutoScaleVmGroupVO findAutoScaleVmGroupById(long groupId){ + return _asVmGroupDao.findById(groupId); + } + + public static GuestOSCategoryVO findGuestOsCategoryById(long catId){ + return _guestOSCategoryDao.findById(catId); + } + + public static VpcVO findVpcById(long vpcId){ + return _vpcDao.findById(vpcId); + } + + public static SnapshotPolicy findSnapshotPolicyById(long policyId){ + return _snapshotPolicyDao.findById(policyId); + } + + public static VpcOffering findVpcOfferingById(long offeringId){ + return _vpcOfferingDao.findById(offeringId); + } + + + public static AsyncJob findAsyncJobById(long jobId){ + return _asyncJobDao.findById(jobId); + } + + public static String findJobInstanceUuid(AsyncJob job){ + if ( job == null ) + return null; + String jobInstanceId = null; + if (job.getInstanceType() == AsyncJob.Type.Volume) { + VolumeVO volume = ApiDBUtils.findVolumeById(job.getInstanceId()); + if (volume != null) { + jobInstanceId = volume.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Template || job.getInstanceType() == AsyncJob.Type.Iso) { + VMTemplateVO template = ApiDBUtils.findTemplateById(job.getInstanceId()); + if (template != null) { + jobInstanceId = template.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.VirtualMachine || job.getInstanceType() == AsyncJob.Type.ConsoleProxy + || job.getInstanceType() == AsyncJob.Type.SystemVm || job.getInstanceType() == AsyncJob.Type.DomainRouter) { + VMInstanceVO vm = ApiDBUtils.findVMInstanceById(job.getInstanceId()); + if (vm != null) { + jobInstanceId = vm.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Snapshot) { + Snapshot snapshot = ApiDBUtils.findSnapshotById(job.getInstanceId()); + if (snapshot != null) { + jobInstanceId = snapshot.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Host) { + Host host = ApiDBUtils.findHostById(job.getInstanceId()); + if (host != null) { + jobInstanceId = host.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.StoragePool) { + StoragePoolVO spool = ApiDBUtils.findStoragePoolById(job.getInstanceId()); + if (spool != null) { + jobInstanceId = spool.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.IpAddress) { + IPAddressVO ip = ApiDBUtils.findIpAddressById(job.getInstanceId()); + if (ip != null) { + jobInstanceId = ip.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.SecurityGroup) { + SecurityGroup sg = ApiDBUtils.findSecurityGroupById(job.getInstanceId()); + if (sg != null) { + jobInstanceId = sg.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PhysicalNetwork) { + PhysicalNetworkVO pnet = ApiDBUtils.findPhysicalNetworkById(job.getInstanceId()); + if (pnet != null) { + jobInstanceId = pnet.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.TrafficType) { + PhysicalNetworkTrafficTypeVO trafficType = ApiDBUtils.findPhysicalNetworkTrafficTypeById(job.getInstanceId()); + if (trafficType != null) { + jobInstanceId = trafficType.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PhysicalNetworkServiceProvider) { + PhysicalNetworkServiceProvider sp = ApiDBUtils.findPhysicalNetworkServiceProviderById(job.getInstanceId()); + if (sp != null) { + jobInstanceId = sp.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.FirewallRule) { + FirewallRuleVO fw = ApiDBUtils.findFirewallRuleById(job.getInstanceId()); + if (fw != null) { + jobInstanceId = fw.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Account) { + Account acct = ApiDBUtils.findAccountById(job.getInstanceId()); + if (acct != null) { + jobInstanceId = acct.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.User) { + User usr = ApiDBUtils.findUserById(job.getInstanceId()); + if (usr != null) { + jobInstanceId = usr.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.StaticRoute) { + StaticRouteVO route = ApiDBUtils.findStaticRouteById(job.getInstanceId()); + if (route != null) { + jobInstanceId = route.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PrivateGateway) { + VpcGatewayVO gateway = ApiDBUtils.findVpcGatewayById(job.getInstanceId()); + if (gateway != null) { + jobInstanceId = gateway.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Counter) { + CounterVO counter = ApiDBUtils.getCounter(job.getInstanceId()); + if (counter != null) { + jobInstanceId = counter.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Condition) { + ConditionVO condition = ApiDBUtils.findConditionById(job.getInstanceId()); + if (condition != null) { + jobInstanceId = condition.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScalePolicy) { + AutoScalePolicyVO policy = ApiDBUtils.findAutoScalePolicyById(job.getInstanceId()); + if (policy != null) { + jobInstanceId = policy.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScaleVmProfile) { + AutoScaleVmProfileVO profile = ApiDBUtils.findAutoScaleVmProfileById(job.getInstanceId()); + if (profile != null) { + jobInstanceId = profile.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScaleVmGroup) { + AutoScaleVmGroupVO group = ApiDBUtils.findAutoScaleVmGroupById(job.getInstanceId()); + if (group != null) { + jobInstanceId = group.getUuid(); + } + } else if (job.getInstanceType() != AsyncJob.Type.None) { + // TODO : when we hit here, we need to add instanceType -> UUID + // entity table mapping + assert (false); + } + return jobInstanceId; + } + + /////////////////////////////////////////////////////////////////////// + // Newly Added Utility Methods for List API refactoring // + /////////////////////////////////////////////////////////////////////// + + public static DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO vr, Account caller) { + return _domainRouterJoinDao.newDomainRouterResponse(vr, caller); + } + + public static DomainRouterResponse fillRouterDetails(DomainRouterResponse vrData, DomainRouterJoinVO vr){ + return _domainRouterJoinDao.setDomainRouterResponse(vrData, vr); + } + + public static List newDomainRouterView(VirtualRouter vr){ + return _domainRouterJoinDao.newDomainRouterView(vr); + } + + public static UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller) { + return _userVmJoinDao.newUserVmResponse(objectName, userVm, details, caller); + } + + public static UserVmResponse fillVmDetails(UserVmResponse vmData, UserVmJoinVO vm){ + return _userVmJoinDao.setUserVmResponse(vmData, vm); + } + + public static List newUserVmView(UserVm... userVms){ + return _userVmJoinDao.newUserVmView(userVms); + } + + public static SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller) { + return _securityGroupJoinDao.newSecurityGroupResponse(vsg, caller); + } + + public static SecurityGroupResponse fillSecurityGroupDetails(SecurityGroupResponse vsgData, SecurityGroupJoinVO sg){ + return _securityGroupJoinDao.setSecurityGroupResponse(vsgData, sg); + } + + public static List newSecurityGroupView(SecurityGroup sg){ + return _securityGroupJoinDao.newSecurityGroupView(sg); + } + + public static List findSecurityGroupViewById(Long sgId){ + return _securityGroupJoinDao.searchByIds(sgId); + } + + public static ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO vsg, boolean keyValueOnly) { + return _tagJoinDao.newResourceTagResponse(vsg, keyValueOnly); + } + + public static ResourceTagJoinVO newResourceTagView(ResourceTag sg){ + return _tagJoinDao.newResourceTagView(sg); + } + + public static ResourceTagJoinVO findResourceTagViewById(Long tagId){ + List tags = _tagJoinDao.searchByIds(tagId); + if ( tags != null && tags.size() > 0 ){ + return tags.get(0); + } + else{ + return null; + } + } + + public static EventResponse newEventResponse(EventJoinVO ve) { + return _eventJoinDao.newEventResponse(ve); + } + + public static EventJoinVO newEventView(Event e){ + return _eventJoinDao.newEventView(e); + } + + public static InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO ve) { + return _vmGroupJoinDao.newInstanceGroupResponse(ve); + } + + public static InstanceGroupJoinVO newInstanceGroupView(InstanceGroup e){ + return _vmGroupJoinDao.newInstanceGroupView(e); + } + + public static UserResponse newUserResponse(UserAccountJoinVO usr) { + return _userAccountJoinDao.newUserResponse(usr); + } + + public static UserAccountJoinVO newUserView(User usr){ + return _userAccountJoinDao.newUserView(usr); + } + + public static UserAccountJoinVO newUserView(UserAccount usr){ + return _userAccountJoinDao.newUserView(usr); + } + + public static ProjectResponse newProjectResponse(ProjectJoinVO proj) { + return _projectJoinDao.newProjectResponse(proj); + } + + public static ProjectResponse fillProjectDetails(ProjectResponse rsp, ProjectJoinVO proj){ + return _projectJoinDao.setProjectResponse(rsp,proj); + } + + public static List newProjectView(Project proj){ + return _projectJoinDao.newProjectView(proj); + } + + public static List findUserViewByAccountId(Long accountId){ + return _userAccountJoinDao.searchByAccountId(accountId); + } + + public static ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj) { + return _projectAccountJoinDao.newProjectAccountResponse(proj); + } + + public static ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj) { + return _projectAccountJoinDao.newProjectAccountView(proj); + } + + public static ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO proj) { + return _projectInvitationJoinDao.newProjectInvitationResponse(proj); + } + + public static ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj) { + return _projectInvitationJoinDao.newProjectInvitationView(proj); + } + + public static HostResponse newHostResponse(HostJoinVO vr, EnumSet details) { + return _hostJoinDao.newHostResponse(vr, details); + } + + public static HostResponse fillHostDetails(HostResponse vrData, HostJoinVO vr){ + return _hostJoinDao.setHostResponse(vrData, vr); + } + + public static List newHostView(Host vr){ + return _hostJoinDao.newHostView(vr); + } + + public static VolumeResponse newVolumeResponse(VolumeJoinVO vr) { + return _volJoinDao.newVolumeResponse(vr); + } + + + public static VolumeResponse fillVolumeDetails(VolumeResponse vrData, VolumeJoinVO vr){ + return _volJoinDao.setVolumeResponse(vrData, vr); + } + + public static List newVolumeView(Volume vr){ + return _volJoinDao.newVolumeView(vr); + } + + public static StoragePoolResponse newStoragePoolResponse(StoragePoolJoinVO vr) { + return _poolJoinDao.newStoragePoolResponse(vr); + } + + public static StoragePoolResponse fillStoragePoolDetails(StoragePoolResponse vrData, StoragePoolJoinVO vr){ + return _poolJoinDao.setStoragePoolResponse(vrData, vr); + } + + public static List newStoragePoolView(StoragePool vr){ + return _poolJoinDao.newStoragePoolView(vr); + } + + + public static AccountResponse newAccountResponse(AccountJoinVO ve) { + return _accountJoinDao.newAccountResponse(ve); + } + + public static AccountJoinVO newAccountView(Account e){ + return _accountJoinDao.newAccountView(e); + } + + public static AccountJoinVO findAccountViewById(Long accountId) { + return _accountJoinDao.findByIdIncludingRemoved(accountId); + } + + public static AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO ve) { + return _jobJoinDao.newAsyncJobResponse(ve); + } + + public static AsyncJobJoinVO newAsyncJobView(AsyncJob e){ + return _jobJoinDao.newAsyncJobView(e); + } +} diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 9fd0b2e9f06..55d7f429ca1 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -24,15 +24,22 @@ import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; +import com.cloud.dao.EntityManager; +import com.cloud.utils.ReflectUtil; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.acl.Role; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.commands.ListEventsCmd; +import org.apache.cloudstack.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import com.cloud.async.AsyncCommandQueued; import com.cloud.async.AsyncJobManager; import com.cloud.configuration.Config; @@ -43,40 +50,45 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.dao.NetworkDao; import com.cloud.server.ManagementServer; +import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; +import com.cloud.user.AccountManager; import com.cloud.user.UserContext; import com.cloud.utils.DateUtil; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; import com.cloud.utils.component.PluggableService; +import com.cloud.utils.db.GenericDao; import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.uuididentity.dao.IdentityDao; -/** - * A class that dispatches API commands to the appropriate manager for execution. - */ +// ApiDispatcher: A class that dispatches API commands to the appropriate manager for execution. public class ApiDispatcher { private static final Logger s_logger = Logger.getLogger(ApiDispatcher.class.getName()); ComponentLocator _locator; - AsyncJobManager _asyncMgr; - IdentityDao _identityDao; Long _createSnapshotQueueSizeLimit; + @Inject private AsyncJobManager _asyncMgr = null; + @Inject private AccountManager _accountMgr = null; + @Inject EntityManager _entityMgr = null; + Map> _daoNameMap = new HashMap>(); // singleton class - private static ApiDispatcher s_instance = new ApiDispatcher(); + private static ApiDispatcher s_instance = ApiDispatcher.getInstance(); public static ApiDispatcher getInstance() { + if (s_instance == null) { + s_instance = ComponentLocator.inject(ApiDispatcher.class); + } return s_instance; } - private ApiDispatcher() { + protected ApiDispatcher() { + super(); _locator = ComponentLocator.getLocator(ManagementServer.Name); - _asyncMgr = _locator.getManager(AsyncJobManager.class); - _identityDao = _locator.getDao(IdentityDao.class); ConfigurationDao configDao = _locator.getDao(ConfigurationDao.class); Map configs = configDao.getConfiguration(); String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key()); @@ -89,12 +101,12 @@ public class ApiDispatcher { _createSnapshotQueueSizeLimit = snapshotLimit; } } + _daoNameMap.put("com.cloud.network.Network", NetworkDao.class); + _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class); } public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) { - - setupParameters(cmd, params); - plugService(cmd); + processParameters(cmd, params); try { UserContext ctx = UserContext.current(); @@ -135,10 +147,32 @@ public class ApiDispatcher { } } + private void doAccessChecks(BaseCmd cmd, List entitiesToAccess) { + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.getActiveAccountById(cmd.getEntityOwnerId()); + + if(cmd instanceof BaseAsyncCreateCmd) { + //check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); + } + + if(!entitiesToAccess.isEmpty()){ + //check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); + for(Object entity : entitiesToAccess) { + if (entity instanceof ControlledEntity) { + _accountMgr.checkAccess(caller, null, true, (ControlledEntity) entity); + } + else if (entity instanceof InfrastructureEntity) { + //FIXME: Move this code in adapter, remove code from Account manager + } + } + } + } + public void dispatch(BaseCmd cmd, Map params) { - setupParameters(cmd, params); - ApiDispatcher.plugService(cmd); try { + processParameters(cmd, params); UserContext ctx = UserContext.current(); ctx.setAccountId(cmd.getEntityOwnerId()); if (cmd instanceof BaseAsyncCmd) { @@ -155,9 +189,9 @@ public class ApiDispatcher { } else { queueSizeLimit = 1L; } - + if (queueSizeLimit != null) { - _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), + _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit); } else { s_logger.trace("The queue size is unlimited, skipping the synchronizing"); @@ -175,13 +209,12 @@ public class ApiDispatcher { InvalidParameterValueException ref = (InvalidParameterValueException) t; ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + " db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + " uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -189,19 +222,18 @@ public class ApiDispatcher { // Also copy over the cserror code. ex.setCSErrorCode(ref.getCSErrorCode()); throw ex; - } else if(t instanceof IllegalArgumentException) { + } else if(t instanceof IllegalArgumentException) { throw new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); - } else if (t instanceof PermissionDeniedException) { + } else if (t instanceof PermissionDeniedException) { PermissionDeniedException ref = (PermissionDeniedException)t; ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info("PermissionDenied: " + t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info("PermissionDenied: " + t.getMessage()); @@ -209,17 +241,16 @@ public class ApiDispatcher { // Also copy over the cserror code. ex.setCSErrorCode(ref.getCSErrorCode()); throw ex; - } else if (t instanceof AccountLimitException) { + } else if (t instanceof AccountLimitException) { AccountLimitException ref = (AccountLimitException)t; ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -227,17 +258,16 @@ public class ApiDispatcher { // Also copy over the cserror code. ex.setCSErrorCode(ref.getCSErrorCode()); throw ex; - } else if (t instanceof InsufficientCapacityException) { + } else if (t instanceof InsufficientCapacityException) { InsufficientCapacityException ref = (InsufficientCapacityException)t; ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -249,13 +279,13 @@ public class ApiDispatcher { ResourceAllocationException ref = (ResourceAllocationException)t; ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.warn("Exception: " + t.getMessage() + "db_id: " + id.getValue()); + String id = idList.get(i); + ex.addProxyObject(id); + s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); } } else { s_logger.warn("Exception: ", t); @@ -267,13 +297,13 @@ public class ApiDispatcher { ResourceUnavailableException ref = (ResourceUnavailableException)t; ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.warn("Exception: " + t.getMessage() + "db_id: " + id.getValue()); + String id = idList.get(i); + ex.addProxyObject(id); + s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); } } else { s_logger.warn("Exception: ", t); @@ -281,7 +311,7 @@ public class ApiDispatcher { // Also copy over the cserror code. ex.setCSErrorCode(ref.getCSErrorCode()); throw ex; - } else if (t instanceof AsyncCommandQueued) { + } else if (t instanceof AsyncCommandQueued) { throw (AsyncCommandQueued) t; } else if (t instanceof ServerApiException) { s_logger.warn(t.getClass() + " : " + ((ServerApiException) t).getDescription()); @@ -293,14 +323,16 @@ public class ApiDispatcher { ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, t.getMessage()); } else { ex = new ServerApiException(BaseCmd.INTERNAL_ERROR, BaseCmd.USER_ERROR_MESSAGE); - } + } ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; } } } - public static void setupParameters(BaseCmd cmd, Map params) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static void processParameters(BaseCmd cmd, Map params) { + List entitiesToAccess = new ArrayList(); Map unpackedParams = cmd.unpackParams(params); if (cmd instanceof BaseListCmd) { @@ -311,7 +343,7 @@ public class ApiDispatcher { } if ((unpackedParams.get(ApiConstants.PAGE) == null) && (pageSize != null && pageSize != BaseListCmd.PAGESIZE_UNLIMITED)) { - ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); + ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, "\"page\" parameter is required when \"pagesize\" is specified"); ex.setCSErrorCode(CSExceptionErrorCode.getCSErrCode(ex.getClass().getName())); throw ex; } else if (pageSize == null && (unpackedParams.get(ApiConstants.PAGE) != null)) { @@ -319,27 +351,22 @@ public class ApiDispatcher { } } - Field[] fields = cmd.getClass().getDeclaredFields(); - Class superClass = cmd.getClass().getSuperclass(); - while (BaseCmd.class.isAssignableFrom(superClass)) { - Field[] superClassFields = superClass.getDeclaredFields(); - if (superClassFields != null) { - Field[] tmpFields = new Field[fields.length + superClassFields.length]; - System.arraycopy(fields, 0, tmpFields, 0, fields.length); - System.arraycopy(superClassFields, 0, tmpFields, fields.length, superClassFields.length); - fields = tmpFields; - } - superClass = superClass.getSuperclass(); - } + Field[] fields = ReflectUtil.getAllFieldsForClass(cmd.getClass(), + new Class[] {BaseCmd.class}); for (Field field : fields) { + PlugService plugServiceAnnotation = field.getAnnotation(PlugService.class); + if(plugServiceAnnotation != null){ + plugService(field, cmd); + } + Parameter parameterAnnotation = field.getAnnotation(Parameter.class); if ((parameterAnnotation == null) || !parameterAnnotation.expose()) { continue; } - IdentityMapper identityMapper = field.getAnnotation(IdentityMapper.class); - + //TODO: Annotate @Validate on API Cmd classes, FIXME how to process Validate + Validate validateAnnotation = field.getAnnotation(Validate.class); Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { @@ -351,7 +378,7 @@ public class ApiDispatcher { // marshall the parameter into the correct type and set the field value try { - setFieldValue(field, cmd, paramObj, parameterAnnotation, identityMapper); + setFieldValue(field, cmd, paramObj, parameterAnnotation); } catch (IllegalArgumentException argEx) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to execute API command " + cmd.getCommandName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); @@ -369,16 +396,162 @@ public class ApiDispatcher { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage()); } catch (CloudRuntimeException cloudEx) { // FIXME: Better error message? This only happens if the API command is not executable, which typically -// means + //means // there was // and IllegalAccessException setting one of the parameters. throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } + + //check access on the resource this field points to + try { + ACL checkAccess = field.getAnnotation(ACL.class); + CommandType fieldType = parameterAnnotation.type(); + + if (checkAccess != null) { + // Verify that caller can perform actions in behalf of vm owner + //acumulate all Controlled Entities together. + + //parse the array of resource types and in case of map check access on key or value or both as specified in @acl + //implement external dao for classes that need findByName + //for maps, specify access to be checkd on key or value. + + // find the controlled entity DBid by uuid + if (parameterAnnotation.entityType() != null) { + Class[] entityList = parameterAnnotation.entityType()[0].getAnnotation(EntityReference.class).value(); + + for (Class entity : entityList) { + // Check if the parameter type is a single + // Id or list of id's/name's + switch (fieldType) { + case LIST: + CommandType listType = parameterAnnotation.collectionType(); + switch (listType) { + case LONG: + case UUID: + List listParam = (List) field.get(cmd); + for (Long entityId : listParam) { + Object entityObj = s_instance._entityMgr.findById(entity, entityId); + entitiesToAccess.add(entityObj); + } + break; + /* + * case STRING: List listParam = + * new ArrayList(); listParam = + * (List)field.get(cmd); for(String + * entityName: listParam){ + * ControlledEntity entityObj = + * (ControlledEntity + * )daoClassInstance(entityId); + * entitiesToAccess.add(entityObj); } + * break; + */ + default: + break; + } + break; + case LONG: + case UUID: + Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd)); + entitiesToAccess.add(entityObj); + break; + default: + break; + } + + if (ControlledEntity.class.isAssignableFrom(entity)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("ControlledEntity name is:" + entity.getName()); + } + } + + if (InfrastructureEntity.class.isAssignableFrom(entity)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("InfrastructureEntity name is:" + entity.getName()); + } + } + } + + } + + } + + } catch (IllegalArgumentException e) { + s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } catch (IllegalAccessException e) { + s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } + } + + //check access on the entities. + s_instance.doAccessChecks(cmd, entitiesToAccess); + + } + + private static Long translateUuidToInternalId(String uuid, Parameter annotation) + { + if (uuid.equals("-1")) { + // FIXME: This is to handle a lot of hardcoded special cases where -1 is sent + // APITODO: Find and get rid of all hardcoded params in API Cmds and service layer + return -1L; + } + Long internalId = null; + // If annotation's empty, the cmd existed before 3.x try conversion to long + boolean isPre3x = annotation.since().isEmpty(); + // Match against Java's UUID regex to check if input is uuid string + boolean isUuid = uuid.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + // Enforce that it's uuid for newly added apis from version 3.x + if (!isPre3x && !isUuid) + return null; + // Allow both uuid and internal id for pre3x apis + if (isPre3x && !isUuid) { + try { + internalId = Long.parseLong(uuid); + } catch(NumberFormatException e) { + // In case regex failed, and it's still uuid string + internalId = null; + } + if (internalId != null) + return internalId; + } + // There may be multiple entities defined on the @EntityReference of a Response.class + // UUID CommandType would expect only one entityType, so use the first entityType + Class[] entities = annotation.entityType()[0].getAnnotation(EntityReference.class).value(); + // Go through each entity which is an interface to a VO class and get a VO object + // Try to getId() for the object using reflection, break on first non-null value + for (Class entity: entities) { + // findByUuid returns one VO object using uuid, use reflect to get the Id + Object objVO = s_instance._entityMgr.findByUuid(entity, uuid); + if (objVO == null) { + continue; + } + // Invoke the getId method, get the internal long ID + // If that fails hide exceptions as the uuid may not exist + try { + internalId = (Long) ((InternalIdentity)objVO).getId(); + } catch (IllegalArgumentException e) { + } catch (NullPointerException e) { + } + // Return on first non-null Id for the uuid entity + if (internalId != null) + break; + } + if (internalId == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Object entity with uuid=" + uuid + " does not exist in the database."); + } + if (annotation.required()) { + throw new InvalidParameterValueException("Invalid parameter with uuid=" + uuid + + ". Entity not found, or an annotation bug."); + } + } + return internalId; } @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation, IdentityMapper identityMapper) throws IllegalArgumentException, ParseException { + private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation) throws IllegalArgumentException, ParseException { try { field.setAccessible(true); CommandType fieldType = annotation.type(); @@ -387,9 +560,9 @@ public class ApiDispatcher { field.set(cmdObj, Boolean.valueOf(paramObj.toString())); break; case DATE: - // This piece of code is for maintaining backward compatibility and support both the date formats(Bug -// 9724) - // Do the date massaging for ListEventsCmd only + // This piece of code is for maintaining backward compatibility + // and support both the date formats(Bug 9724) + // Do the date messaging for ListEventsCmd only if (cmdObj instanceof ListEventsCmd) { boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString()); if (isObjInNewDateFormat) { @@ -402,9 +575,9 @@ public class ApiDispatcher { synchronized (format) { Date date = format.parse(paramObj.toString()); if (field.getName().equals("startDate")) { - date = massageDate(date, 0, 0, 0); + date = messageDate(date, 0, 0, 0); } else if (field.getName().equals("endDate")) { - date = massageDate(date, 23, 59, 59); + date = messageDate(date, 23, 59, 59); } field.set(cmdObj, date); } @@ -433,40 +606,43 @@ public class ApiDispatcher { field.set(cmdObj, Integer.valueOf(paramObj.toString())); } break; - case LIST: - List listParam = new ArrayList(); - StringTokenizer st = new StringTokenizer(paramObj.toString(), ","); - while (st.hasMoreTokens()) { - String token = st.nextToken(); - CommandType listType = annotation.collectionType(); - switch (listType) { - case INTEGER: - listParam.add(Integer.valueOf(token)); - break; - case LONG: { - Long val = null; - if (identityMapper != null) - val = s_instance._identityDao.getIdentityId(identityMapper, token); - else - val = Long.valueOf(token); - - listParam.add(val); + case LIST: + List listParam = new ArrayList(); + StringTokenizer st = new StringTokenizer(paramObj.toString(), ","); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + CommandType listType = annotation.collectionType(); + switch (listType) { + case INTEGER: + listParam.add(Integer.valueOf(token)); + break; + case UUID: + if (token.isEmpty()) + break; + Long internalId = translateUuidToInternalId(token, annotation); + listParam.add(internalId); + break; + case LONG: { + listParam.add(Long.valueOf(token)); + } + break; + case SHORT: + listParam.add(Short.valueOf(token)); + case STRING: + listParam.add(token); + break; + } } - break; - case SHORT: - listParam.add(Short.valueOf(token)); - case STRING: - listParam.add(token); - break; - } - } - field.set(cmdObj, listParam); + field.set(cmdObj, listParam); + break; + case UUID: + if (paramObj.toString().isEmpty()) + break; + Long internalId = translateUuidToInternalId(paramObj.toString(), annotation); + field.set(cmdObj, internalId); break; case LONG: - if (identityMapper != null) - field.set(cmdObj, s_instance._identityDao.getIdentityId(identityMapper, paramObj.toString())); - else - field.set(cmdObj, Long.valueOf(paramObj.toString())); + field.set(cmdObj, Long.valueOf(paramObj.toString())); break; case SHORT: field.set(cmdObj, Short.valueOf(paramObj.toString())); @@ -497,7 +673,7 @@ public class ApiDispatcher { return matcher.matches(); } - private static Date massageDate(Date date, int hourOfDay, int minute, int second) { + private static Date messageDate(Date date, int hourOfDay, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, hourOfDay); @@ -506,47 +682,28 @@ public class ApiDispatcher { return cal.getTime(); } - public static void plugService(BaseCmd cmd) { - - if (!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())) { - return; - } - Class clazz = cmd.getClass(); + public static void plugService(Field field, BaseCmd cmd) { ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - do { - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - PlugService plugService = field.getAnnotation(PlugService.class); - if (plugService == null) { - continue; - } - Class fc = field.getType(); - Object instance = null; - if (PluggableService.class.isAssignableFrom(fc)) { - instance = locator.getPluggableService(fc); - } - if (instance == null) { - throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + clazz.getSimpleName()); - } + Class fc = field.getType(); + Object instance = null; + if (PluggableService.class.isAssignableFrom(fc)) { + instance = locator.getPluggableService(fc); + } - try { - field.setAccessible(true); - field.set(cmd, instance); - } catch (IllegalArgumentException e) { - s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName()); - throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]"); - } catch (IllegalAccessException e) { - s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); - throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); - } - } - clazz = clazz.getSuperclass(); - } while (clazz != Object.class && clazz != null); - } - - - public static Long getIdentiyId(String tableName, String token) { - return s_instance._identityDao.getIdentityId(tableName, token); + if (instance == null) { + throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + cmd.getClass().getSimpleName()); + } + + try { + field.setAccessible(true); + field.set(cmd, instance); + } catch (IllegalArgumentException e) { + s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName() + ", field " + field.getName()); + throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [Illegal argumet at field " + field.getName() + "]"); + } catch (IllegalAccessException e) { + s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } } } diff --git a/server/src/com/cloud/api/ApiGsonHelper.java b/server/src/com/cloud/api/ApiGsonHelper.java index 503ff13db3a..6163860f0c8 100644 --- a/server/src/com/cloud/api/ApiGsonHelper.java +++ b/server/src/com/cloud/api/ApiGsonHelper.java @@ -17,7 +17,8 @@ package com.cloud.api; import com.google.gson.GsonBuilder; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ResponseObject; + import java.util.Map; public class ApiGsonHelper { @@ -26,7 +27,6 @@ public class ApiGsonHelper { s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); s_gBuilder.setVersion(1.3); s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter()); - s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter()); s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter()); } diff --git a/server/src/com/cloud/api/ApiResponseGsonHelper.java b/server/src/com/cloud/api/ApiResponseGsonHelper.java index 0b578793344..6bccf9a12af 100644 --- a/server/src/com/cloud/api/ApiResponseGsonHelper.java +++ b/server/src/com/cloud/api/ApiResponseGsonHelper.java @@ -17,20 +17,19 @@ package com.cloud.api; import com.google.gson.GsonBuilder; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ResponseObject; /** * The ApiResonseGsonHelper is different from ApiGsonHelper - it registeres one more adapter for String type required for api response encoding */ public class ApiResponseGsonHelper { private static final GsonBuilder s_gBuilder; - + static { s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); s_gBuilder.setVersion(1.3); s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter()); s_gBuilder.registerTypeAdapter(String.class, new EncodedStringTypeAdapter()); - s_gBuilder.registerTypeAdapter(IdentityProxy.class, new IdentityTypeAdapter()); } public static GsonBuilder getBuilder() { diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 8f9837f54a5..c346a6b86f1 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -21,107 +21,123 @@ import static java.util.Collections.singletonList; import java.text.DecimalFormat; import java.util.ArrayList; -import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ResponseGenerator; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.response.AccountResponse; + +import com.cloud.api.query.ViewResponseHelper; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.ControlledViewEntity; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.AutoScalePolicyResponse; -import com.cloud.api.response.AutoScaleVmGroupResponse; -import com.cloud.api.response.AutoScaleVmProfileResponse; -import com.cloud.api.response.CapabilityResponse; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ConditionResponse; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.ControlledEntityResponse; -import com.cloud.api.response.CounterResponse; -import com.cloud.api.response.CreateCmdResponse; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ExtractResponse; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.LBStickinessPolicyResponse; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.NetworkACLResponse; -import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.api.response.NetworkResponse; -import com.cloud.api.response.NicResponse; -import com.cloud.api.response.PhysicalNetworkResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.api.response.PrivateGatewayResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.api.response.S3Response; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SecurityGroupResultObject; -import com.cloud.api.response.SecurityGroupRuleResponse; -import com.cloud.api.response.SecurityGroupRuleResultObject; -import com.cloud.api.response.ServiceOfferingResponse; -import com.cloud.api.response.ServiceResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; -import com.cloud.api.response.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StaticRouteResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.SwiftResponse; -import com.cloud.api.response.SystemVmInstanceResponse; -import com.cloud.api.response.SystemVmResponse; -import com.cloud.api.response.TemplatePermissionsResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.TrafficTypeResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; -import com.cloud.api.response.VlanIpRangeResponse; -import com.cloud.api.response.VolumeResponse; -import com.cloud.api.response.VpcOfferingResponse; -import com.cloud.api.response.VpcResponse; -import com.cloud.api.response.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.CapabilityResponse; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.ControlledEntityResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ControlledViewEntityResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.LBStickinessPolicyResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ServiceResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SwiftResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + +import org.apache.cloudstack.api.response.S3Response; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Configuration; import com.cloud.configuration.Resource.ResourceOwnerType; -import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.dc.ClusterVO; @@ -136,7 +152,6 @@ import com.cloud.dc.VlanVO; import com.cloud.domain.Domain; import com.cloud.event.Event; import com.cloud.host.Host; -import com.cloud.host.HostStats; import com.cloud.host.HostVO; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.network.IPAddressVO; @@ -146,33 +161,33 @@ import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkProfile; +import com.cloud.network.NetworkVO; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkTrafficType; +import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.network.Site2SiteCustomerGatewayVO; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; -import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VpnUser; import com.cloud.network.as.AutoScalePolicy; import com.cloud.network.as.AutoScaleVmGroup; import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.AutoScaleVmProfileVO; import com.cloud.network.as.Condition; import com.cloud.network.as.ConditionVO; import com.cloud.network.as.Counter; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.security.SecurityGroup; -import com.cloud.network.security.SecurityGroupRules; -import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.SecurityRule; import com.cloud.network.security.SecurityRule.SecurityRuleType; import com.cloud.network.vpc.PrivateGateway; @@ -189,12 +204,10 @@ import com.cloud.projects.ProjectInvitation; import com.cloud.server.Criteria; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.S3; import com.cloud.storage.Snapshot; -import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.TemplateType; @@ -211,31 +224,21 @@ import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.template.VirtualMachineTemplate; -import com.cloud.test.PodZoneConfig; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -import com.cloud.user.UserStatisticsVO; -import com.cloud.user.UserVO; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.InstanceGroup; -import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmDetailVO; -import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VmStats; -import com.cloud.vm.dao.UserVmData; -import com.cloud.vm.dao.UserVmData.NicData; -import com.cloud.vm.dao.UserVmData.SecurityGroupData; public class ApiResponseHelper implements ResponseGenerator { @@ -244,215 +247,42 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public UserResponse createUserResponse(User user) { - UserResponse userResponse = new UserResponse(); - Account account = ApiDBUtils.findAccountById(user.getAccountId()); - userResponse.setAccountName(account.getAccountName()); - userResponse.setAccountType(account.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(account.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState().toString()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setObjectName("user"); - - return userResponse; + UserAccountJoinVO vUser = ApiDBUtils.newUserView(user); + return ApiDBUtils.newUserResponse(vUser); } + + // this method is used for response generation via createAccount (which creates an account + user) @Override public AccountResponse createUserAccountResponse(UserAccount user) { - return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); + return ApiDBUtils.newAccountResponse(ApiDBUtils.findAccountViewById(user.getAccountId())); } @Override public AccountResponse createAccountResponse(Account account) { - boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); - AccountResponse accountResponse = new AccountResponse(); - accountResponse.setId(account.getId()); - accountResponse.setName(account.getAccountName()); - accountResponse.setAccountType(account.getType()); - accountResponse.setDomainId(account.getDomainId()); - accountResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - accountResponse.setState(account.getState().toString()); - accountResponse.setNetworkDomain(account.getNetworkDomain()); - accountResponse.setDefaultZone(account.getDefaultZoneId()); - - // get network stat - List stats = ApiDBUtils.listUserStatsBy(account.getId()); - if (stats == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); - } - - Long bytesSent = 0L; - Long bytesReceived = 0L; - for (UserStatisticsVO stat : stats) { - Long rx = stat.getNetBytesReceived() + stat.getCurrentBytesReceived(); - Long tx = stat.getNetBytesSent() + stat.getCurrentBytesSent(); - bytesReceived = bytesReceived + Long.valueOf(rx); - bytesSent = bytesSent + Long.valueOf(tx); - } - accountResponse.setBytesReceived(bytesReceived); - accountResponse.setBytesSent(bytesSent); - - // Get resource limits and counts - - Long vmLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.user_vm, account.getId()); - String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); - Long vmTotal = ApiDBUtils.getResourceCount(ResourceType.user_vm, account.getId()); - String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); - accountResponse.setVmLimit(vmLimitDisplay); - accountResponse.setVmTotal(vmTotal); - accountResponse.setVmAvailable(vmAvail); - - Long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId()); - String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); - Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); - - Long ips = ipLimit - ipTotal; - // check how many free ips are left, and if it's less than max allowed number of ips from account - use this - // value - Long ipsLeft = ApiDBUtils.countFreePublicIps(); - boolean unlimited = true; - if (ips.longValue() > ipsLeft.longValue()) { - ips = ipsLeft; - unlimited = false; - } - - String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); - - accountResponse.setIpLimit(ipLimitDisplay); - accountResponse.setIpTotal(ipTotal); - accountResponse.setIpAvailable(ipAvail); - - Long volumeLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.volume, account.getId()); - String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); - Long volumeTotal = ApiDBUtils.getResourceCount(ResourceType.volume, account.getId()); - String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); - accountResponse.setVolumeLimit(volumeLimitDisplay); - accountResponse.setVolumeTotal(volumeTotal); - accountResponse.setVolumeAvailable(volumeAvail); - - Long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.snapshot, account.getId()); - String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); - Long snapshotTotal = ApiDBUtils.getResourceCount(ResourceType.snapshot, account.getId()); - String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); - accountResponse.setSnapshotLimit(snapshotLimitDisplay); - accountResponse.setSnapshotTotal(snapshotTotal); - accountResponse.setSnapshotAvailable(snapshotAvail); - - Long templateLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.template, account.getId()); - String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); - Long templateTotal = ApiDBUtils.getResourceCount(ResourceType.template, account.getId()); - String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); - accountResponse.setTemplateLimit(templateLimitDisplay); - accountResponse.setTemplateTotal(templateTotal); - accountResponse.setTemplateAvailable(templateAvail); - - // Get stopped and running VMs - int vmStopped = 0; - int vmRunning = 0; - - List permittedAccounts = new ArrayList(); - permittedAccounts.add(account.getId()); - - List virtualMachines = ApiDBUtils.searchForUserVMs(new Criteria(), permittedAccounts); - - // get Running/Stopped VMs - for (Iterator iter = virtualMachines.iterator(); iter.hasNext();) { - // count how many stopped/running vms we have - UserVm vm = iter.next(); - - if (vm.getState() == State.Stopped) { - vmStopped++; - } else if (vm.getState() == State.Running) { - vmRunning++; - } - } - - accountResponse.setVmStopped(vmStopped); - accountResponse.setVmRunning(vmRunning); - accountResponse.setObjectName("account"); - - //get resource limits for projects - Long projectLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.project, account.getId()); - String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); - Long projectTotal = ApiDBUtils.getResourceCount(ResourceType.project, account.getId()); - String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); - accountResponse.setProjectLimit(projectLimitDisplay); - accountResponse.setProjectTotal(projectTotal); - accountResponse.setProjectAvailable(projectAvail); - - //get resource limits for networks - Long networkLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.network, account.getId()); - String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); - Long networkTotal = ApiDBUtils.getResourceCount(ResourceType.network, account.getId()); - String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); - accountResponse.setNetworkLimit(networkLimitDisplay); - accountResponse.setNetworkTotal(networkTotal); - accountResponse.setNetworkAvailable(networkAvail); - - //get resource limits for vpcs - Long vpcLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.vpc, account.getId()); - String vpcLimitDisplay = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit); - Long vpcTotal = ApiDBUtils.getResourceCount(ResourceType.vpc, account.getId()); - String vpcAvail = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit - vpcTotal); - accountResponse.setNetworkLimit(vpcLimitDisplay); - accountResponse.setNetworkTotal(vpcTotal); - accountResponse.setNetworkAvailable(vpcAvail); - - // adding all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - accountResponse.setUsers(userResponseList); - accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); - return accountResponse; + AccountJoinVO vUser = ApiDBUtils.newAccountView(account); + return ApiDBUtils.newAccountResponse(vUser); } - - + + @Override public UserResponse createUserResponse(UserAccount user) { - Account account = UserContext.current().getCaller(); - UserResponse userResponse = new UserResponse(); - userResponse.setAccountName(user.getAccountName()); - userResponse.setAccountType(user.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(user.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(user.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setAccountId((user.getAccountId())); - userResponse.setIsCallerChildDomain(ApiDBUtils.isChildDomain(account.getDomainId(), user.getDomainId())); - userResponse.setObjectName("user"); - return userResponse; + UserAccountJoinVO vUser = ApiDBUtils.newUserView(user); + return ApiDBUtils.newUserResponse(vUser); } @Override public DomainResponse createDomainResponse(Domain domain) { DomainResponse domainResponse = new DomainResponse(); domainResponse.setDomainName(domain.getName()); - domainResponse.setId(domain.getId()); + domainResponse.setId(domain.getUuid()); domainResponse.setLevel(domain.getLevel()); domainResponse.setNetworkDomain(domain.getNetworkDomain()); - domainResponse.setParentDomainId(domain.getParent()); + Domain parentDomain = ApiDBUtils.findDomainById(domain.getParent()); + if (parentDomain != null) { + domainResponse.setParentDomainId(parentDomain.getUuid()); + } StringBuilder domainPath = new StringBuilder("ROOT"); (domainPath.append(domain.getPath())).deleteCharAt(domainPath.length() - 1); domainResponse.setPath(domainPath.toString()); @@ -469,14 +299,17 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public DiskOfferingResponse createDiskOfferingResponse(DiskOffering offering) { DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); - diskOfferingResponse.setId(offering.getId()); + diskOfferingResponse.setId(offering.getUuid()); diskOfferingResponse.setName(offering.getName()); diskOfferingResponse.setDisplayText(offering.getDisplayText()); diskOfferingResponse.setCreated(offering.getCreated()); diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); if (offering.getDomainId() != null) { - diskOfferingResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - diskOfferingResponse.setDomainId(offering.getDomainId()); + Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); + if (domain != null) { + diskOfferingResponse.setDomain(domain.getName()); + diskOfferingResponse.setDomainId(domain.getUuid()); + } } diskOfferingResponse.setTags(offering.getTags()); diskOfferingResponse.setCustomized(offering.isCustomized()); @@ -525,7 +358,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ServiceOfferingResponse createServiceOfferingResponse(ServiceOffering offering) { ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); - offeringResponse.setId(offering.getId()); + offeringResponse.setId(offering.getUuid()); offeringResponse.setName(offering.getName()); offeringResponse.setIsSystemOffering(offering.getSystemUse()); offeringResponse.setDefaultUse(offering.getDefaultUse()); @@ -540,8 +373,11 @@ public class ApiResponseHelper implements ResponseGenerator { offeringResponse.setLimitCpuUse(offering.getLimitCpuUse()); offeringResponse.setTags(offering.getTags()); if (offering.getDomainId() != null) { - offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - offeringResponse.setDomainId(offering.getDomainId()); + Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); + if (domain != null) { + offeringResponse.setDomain(domain.getName()); + offeringResponse.setDomainId(domain.getUuid()); + } } offeringResponse.setNetworkRate(offering.getRateMbps()); offeringResponse.setHostTag(offering.getHostTag()); @@ -565,15 +401,15 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public SnapshotResponse createSnapshotResponse(Snapshot snapshot) { SnapshotResponse snapshotResponse = new SnapshotResponse(); - snapshotResponse.setId(snapshot.getId()); + snapshotResponse.setId(snapshot.getUuid()); populateOwner(snapshotResponse, snapshot); VolumeVO volume = findVolumeById(snapshot.getVolumeId()); String snapshotTypeStr = snapshot.getType().name(); snapshotResponse.setSnapshotType(snapshotTypeStr); - snapshotResponse.setVolumeId(snapshot.getVolumeId()); if (volume != null) { + snapshotResponse.setVolumeId(volume.getUuid()); snapshotResponse.setVolumeName(volume.getName()); snapshotResponse.setVolumeType(volume.getVolumeType().name()); } @@ -598,8 +434,11 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public SnapshotPolicyResponse createSnapshotPolicyResponse(SnapshotPolicy policy) { SnapshotPolicyResponse policyResponse = new SnapshotPolicyResponse(); - policyResponse.setId(policy.getId()); - policyResponse.setVolumeId(policy.getVolumeId()); + policyResponse.setId(policy.getUuid()); + Volume vol = ApiDBUtils.findVolumeById(policy.getVolumeId()); + if (vol != null) { + policyResponse.setVolumeId(vol.getUuid()); + } policyResponse.setSchedule(policy.getSchedule()); policyResponse.setIntervalType(policy.getInterval()); policyResponse.setMaxSnaps(policy.getMaxSnaps()); @@ -616,132 +455,16 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public HostResponse createHostResponse(Host host, EnumSet details) { - HostResponse hostResponse = new HostResponse(); - hostResponse.setId(host.getId()); - hostResponse.setCapabilities(host.getCapabilities()); - hostResponse.setClusterId(host.getClusterId()); - hostResponse.setCpuNumber(host.getCpus()); - hostResponse.setZoneId(host.getDataCenterId()); - hostResponse.setDisconnectedOn(host.getDisconnectedOn()); - hostResponse.setHypervisor(host.getHypervisorType()); - hostResponse.setHostType(host.getType()); - hostResponse.setLastPinged(new Date(host.getLastPinged())); - hostResponse.setManagementServerId(host.getManagementServerId()); - hostResponse.setName(host.getName()); - hostResponse.setPodId(host.getPodId()); - hostResponse.setRemoved(host.getRemoved()); - hostResponse.setCpuSpeed(host.getSpeed()); - hostResponse.setState(host.getStatus()); - hostResponse.setIpAddress(host.getPrivateIpAddress()); - hostResponse.setVersion(host.getVersion()); - hostResponse.setCreated(host.getCreated()); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) - || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { - - GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId()); - if (guestOSCategory != null) { - hostResponse.setOsCategoryId(guestOSCategory.getId()); - hostResponse.setOsCategoryName(guestOSCategory.getName()); - } - hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); - - if (host.getPodId() != null) { - HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); - if (pod != null) { - hostResponse.setPodName(pod.getName()); - } - } - - if (host.getClusterId() != null) { - ClusterVO cluster = ApiDBUtils.findClusterById(host.getClusterId()); - hostResponse.setClusterName(cluster.getName()); - hostResponse.setClusterType(cluster.getClusterType().toString()); - } - } - - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - if (host.getType() == Host.Type.Routing) { - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { - // set allocated capacities - Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY); - Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU); - - hostResponse.setMemoryAllocated(mem); - hostResponse.setMemoryTotal(host.getTotalMemory()); - String hostTags = ApiDBUtils.getHostTags(host.getId()); - hostResponse.setHostTags(hostTags); - - String haTag = ApiDBUtils.getHaTag(); - if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) { - if (haTag.equalsIgnoreCase(hostTags)) { - hostResponse.setHaHost(true); - } else { - hostResponse.setHaHost(false); - } - } else { - hostResponse.setHaHost(false); - } - - hostResponse.setHypervisorVersion(host.getHypervisorVersion()); - - String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; - hostResponse.setCpuAllocated(cpuAlloc); - String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); - hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); - } - - if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { - // set CPU/RAM/Network stats - String cpuUsed = null; - HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); - if (hostStats != null) { - float cpuUtil = (float) hostStats.getCpuUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - hostResponse.setCpuUsed(cpuUsed); - hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); - hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); - hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); - - } - } - - } else if (host.getType() == Host.Type.SecondaryStorage) { - StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); - if (secStorageStats != null) { - hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); - hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); - } - } - - hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host)); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { - Set possibleEvents = host.getStatus().getPossibleEvents(); - if ((possibleEvents != null) && !possibleEvents.isEmpty()) { - String events = ""; - Iterator iter = possibleEvents.iterator(); - while (iter.hasNext()) { - com.cloud.host.Status.Event event = iter.next(); - events += event.toString(); - if (iter.hasNext()) { - events += "; "; - } - } - hostResponse.setEvents(events); - } - } - - hostResponse.setResourceState(host.getResourceState().toString()); - hostResponse.setObjectName("host"); - - return hostResponse; + List viewHosts = ApiDBUtils.newHostView(host); + List listHosts = ViewResponseHelper.createHostResponse(details, viewHosts.toArray(new HostJoinVO[viewHosts.size()])); + assert listHosts != null && listHosts.size() == 1 : "There should be one host returned"; + return listHosts.get(0); } @Override public SwiftResponse createSwiftResponse(Swift swift) { SwiftResponse swiftResponse = new SwiftResponse(); - swiftResponse.setId(swift.getId()); + swiftResponse.setId(swift.getUuid()); swiftResponse.setUrl(swift.getUrl()); swiftResponse.setAccount(swift.getAccount()); swiftResponse.setUsername(swift.getUserName()); @@ -759,7 +482,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setEndPoint(result.getEndPoint()); response.setHttpsFlag(result.getHttpsFlag()); response.setMaxErrorRetry(result.getMaxErrorRetry()); - response.setObjectId(result.getId()); + response.setObjectId(result.getUuid()); response.setSecretKey(result.getSecretKey()); response.setSocketTimeout(result.getSocketTimeout()); response.setTemplateBucketName(result.getBucketName()); @@ -773,15 +496,20 @@ public class ApiResponseHelper implements ResponseGenerator { Long podId = ApiDBUtils.getPodIdForVlan(vlan.getId()); VlanIpRangeResponse vlanResponse = new VlanIpRangeResponse(); - vlanResponse.setId(vlan.getId()); - vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); + vlanResponse.setId(vlan.getUuid()); + if (vlan.getVlanType() != null) { + vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); + } vlanResponse.setVlan(vlan.getVlanTag()); - vlanResponse.setZoneId(vlan.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(vlan.getDataCenterId()); + if (zone != null) { + vlanResponse.setZoneId(zone.getUuid()); + } if (podId != null) { HostPodVO pod = ApiDBUtils.findPodById(podId); - vlanResponse.setPodId(podId); if (pod != null) { + vlanResponse.setPodId(pod.getUuid()); vlanResponse.setPodName(pod.getName()); } } @@ -795,15 +523,24 @@ public class ApiResponseHelper implements ResponseGenerator { vlanResponse.setStartIp(range[0]); vlanResponse.setEndIp(range[1]); - vlanResponse.setNetworkId(vlan.getNetworkId()); + if (vlan.getNetworkId() != null) { + Network nw = ApiDBUtils.findNetworkById(vlan.getNetworkId()); + if (nw != null) { + vlanResponse.setNetworkId(nw.getUuid()); + } + } Account owner = ApiDBUtils.getVlanAccount(vlan.getId()); if (owner != null) { populateAccount(vlanResponse, owner.getId()); populateDomain(vlanResponse, owner.getDomainId()); } - vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); - + if (vlan.getPhysicalNetworkId() != null) { + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(vlan.getPhysicalNetworkId()); + if (pnw != null) { + vlanResponse.setPhysicalNetworkId(pnw.getUuid()); + } + } vlanResponse.setObjectName("vlan"); return vlanResponse; } @@ -815,13 +552,16 @@ public class ApiResponseHelper implements ResponseGenerator { long zoneId = ipAddr.getDataCenterId(); IPAddressResponse ipResponse = new IPAddressResponse(); - ipResponse.setId(ipAddr.getId()); + ipResponse.setId(ipAddr.getUuid()); ipResponse.setIpAddress(ipAddr.getAddress().toString()); if (ipAddr.getAllocatedTime() != null) { ipResponse.setAllocated(ipAddr.getAllocatedTime()); } - ipResponse.setZoneId(zoneId); - ipResponse.setZoneName(ApiDBUtils.findZoneById(ipAddr.getDataCenterId()).getName()); + DataCenter zone = ApiDBUtils.findZoneById(ipAddr.getDataCenterId()); + if (zone != null) { + ipResponse.setZoneId(zone.getUuid()); + ipResponse.setZoneName(zone.getName()); + } ipResponse.setSourceNat(ipAddr.isSourceNat()); ipResponse.setIsSystem(ipAddr.getSystem()); @@ -835,24 +575,34 @@ public class ApiResponseHelper implements ResponseGenerator { if (ipAddr.getAssociatedWithVmId() != null) { UserVm vm = ApiDBUtils.findUserVmById(ipAddr.getAssociatedWithVmId()); - ipResponse.setVirtualMachineId(vm.getId()); - ipResponse.setVirtualMachineName(vm.getHostName()); - if (vm.getDisplayName() != null) { - ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); - } else { - ipResponse.setVirtualMachineDisplayName(vm.getHostName()); + if (vm != null) { + ipResponse.setVirtualMachineId(vm.getUuid()); + ipResponse.setVirtualMachineName(vm.getHostName()); + if (vm.getDisplayName() != null) { + ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); + } else { + ipResponse.setVirtualMachineDisplayName(vm.getHostName()); + } } } if (ipAddr.getAssociatedWithNetworkId() != null) { Network ntwk = ApiDBUtils.findNetworkById(ipAddr.getAssociatedWithNetworkId()); - ipResponse.setAssociatedNetworkId(ipAddr.getAssociatedWithNetworkId()); - ipResponse.setAssociatedNetworkName(ntwk.getName()); + if (ntwk != null) { + ipResponse.setAssociatedNetworkId(ntwk.getUuid()); + ipResponse.setAssociatedNetworkName(ntwk.getName()); + } } - ipResponse.setVpcId(ipAddr.getVpcId()); + if (ipAddr.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(ipAddr.getVpcId()); + if (vpc != null) { + ipResponse.setVpcId(vpc.getUuid()); + } + } - // Network id the ip is associated with (if associated networkId is null, try to get this information from vlan) + // Network id the ip is associated with (if associated networkId is + // null, try to get this information from vlan) Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddr.getVlanId()); // Network id the ip belongs to @@ -863,15 +613,29 @@ public class ApiResponseHelper implements ResponseGenerator { networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId); } - ipResponse.setNetworkId(networkId); + if (networkId != null) { + NetworkVO nw = ApiDBUtils.findNetworkById(networkId); + if (nw != null) { + ipResponse.setNetworkId(nw.getUuid()); + } + } ipResponse.setState(ipAddr.getState().toString()); - ipResponse.setPhysicalNetworkId(ipAddr.getPhysicalNetworkId()); + + if (ipAddr.getPhysicalNetworkId() != null) { + PhysicalNetworkVO pnw = ApiDBUtils.findPhysicalNetworkById(ipAddr.getPhysicalNetworkId()); + if (pnw != null) { + ipResponse.setPhysicalNetworkId(pnw.getUuid()); + } + } // show this info to admin only Account account = UserContext.current().getCaller(); if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - ipResponse.setVlanId(ipAddr.getVlanId()); - ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddr.getVlanId()).getVlanTag()); + VlanVO vl = ApiDBUtils.findVlanById(ipAddr.getVlanId()); + if (vl != null) { + ipResponse.setVlanId(vl.getUuid()); + ipResponse.setVlanName(vl.getVlanTag()); + } } if (ipAddr.getSystem()) { @@ -898,14 +662,14 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public LoadBalancerResponse createLoadBalancerResponse(LoadBalancer loadBalancer) { LoadBalancerResponse lbResponse = new LoadBalancerResponse(); - lbResponse.setId(loadBalancer.getId()); + lbResponse.setId(loadBalancer.getUuid()); lbResponse.setName(loadBalancer.getName()); lbResponse.setDescription(loadBalancer.getDescription()); List cidrs = ApiDBUtils.findFirewallSourceCidrs(loadBalancer.getId()); lbResponse.setCidrList(StringUtils.join(cidrs, ",")); IPAddressVO publicIp = ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()); - lbResponse.setPublicIpId(publicIp.getId()); + lbResponse.setPublicIpId(publicIp.getUuid()); lbResponse.setPublicIp(publicIp.getAddress().addr()); lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart())); lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart())); @@ -917,7 +681,10 @@ public class ApiResponseHelper implements ResponseGenerator { } lbResponse.setState(stateToSet); populateOwner(lbResponse, loadBalancer); - lbResponse.setZoneId(publicIp.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(publicIp.getDataCenterId()); + if (zone != null) { + lbResponse.setZoneId(zone.getUuid()); + } //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, loadBalancer.getId()); @@ -942,10 +709,13 @@ public class ApiResponseHelper implements ResponseGenerator { } PodResponse podResponse = new PodResponse(); - podResponse.setId(pod.getId()); + podResponse.setId(pod.getUuid()); podResponse.setName(pod.getName()); - podResponse.setZoneId(pod.getDataCenterId()); - podResponse.setZoneName(PodZoneConfig.getZoneName(pod.getDataCenterId())); + DataCenter zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); + if (zone != null) { + podResponse.setZoneId(zone.getUuid()); + podResponse.setZoneName(zone.getName()); + } podResponse.setNetmask(NetUtils.getCidrNetmask(pod.getCidrSize())); podResponse.setStartIp(ipRange[0]); podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : ""); @@ -988,7 +758,7 @@ public class ApiResponseHelper implements ResponseGenerator { public ZoneResponse createZoneResponse(DataCenter dataCenter, Boolean showCapacities) { Account account = UserContext.current().getCaller(); ZoneResponse zoneResponse = new ZoneResponse(); - zoneResponse.setId(dataCenter.getId()); + zoneResponse.setId(dataCenter.getUuid()); zoneResponse.setName(dataCenter.getName()); zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); zoneResponse.setLocalStorageEnabled(dataCenter.isLocalStorageEnabled()); @@ -1082,211 +852,52 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VolumeResponse createVolumeResponse(Volume volume) { - VolumeResponse volResponse = new VolumeResponse(); - volResponse.setId(volume.getId()); - - if (volume.getName() != null) { - volResponse.setName(volume.getName()); - } else { - volResponse.setName(""); - } - - volResponse.setZoneId(volume.getDataCenterId()); - volResponse.setZoneName(ApiDBUtils.findZoneById(volume.getDataCenterId()).getName()); - - volResponse.setVolumeType(volume.getVolumeType().toString()); - volResponse.setDeviceId(volume.getDeviceId()); - - Long instanceId = volume.getInstanceId(); - if (instanceId != null && volume.getState() != Volume.State.Destroy) { - VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId); - if (vm != null) { - volResponse.setVirtualMachineId(vm.getId()); - volResponse.setVirtualMachineName(vm.getHostName()); - UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); - if (userVm != null) { - if (userVm.getDisplayName() != null) { - volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); - } else { - volResponse.setVirtualMachineDisplayName(userVm.getHostName()); - } - volResponse.setVirtualMachineState(vm.getState().toString()); - } else { - s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } else { - s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } - - // Show the virtual size of the volume - volResponse.setSize(volume.getSize()); - - volResponse.setCreated(volume.getCreated()); - volResponse.setState(volume.getState().toString()); - if(volume.getState() == Volume.State.UploadOp){ - com.cloud.storage.VolumeHostVO volumeHostRef = ApiDBUtils.findVolumeHostRef(volume.getId(), volume.getDataCenterId()); - volResponse.setSize(volumeHostRef.getSize()); - volResponse.setCreated(volumeHostRef.getCreated()); - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) - volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volumeHostRef.getFormat()).toString()); - if (volumeHostRef.getDownloadState() != Status.DOWNLOADED) { - String volumeStatus = "Processing"; - if (volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { - if (volumeHostRef.getDownloadPercent() == 100) { - volumeStatus = "Checking Volume"; - } else { - volumeStatus = volumeHostRef.getDownloadPercent() + "% Uploaded"; - } - volResponse.setState("Uploading"); - } else { - volumeStatus = volumeHostRef.getErrorString(); - if(volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.NOT_DOWNLOADED){ - volResponse.setState("UploadNotStarted"); - }else { - volResponse.setState("UploadError"); - } - } - volResponse.setStatus(volumeStatus); - } else if (volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { - volResponse.setStatus("Upload Complete"); - volResponse.setState("Uploaded"); - } else { - volResponse.setStatus("Successfully Installed"); - } - } - - populateOwner(volResponse, volume); - - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingId(volume.getDiskOfferingId()); - } else { - volResponse.setDiskOfferingId(volume.getDiskOfferingId()); - } - - DiskOfferingVO diskOffering = ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingName(diskOffering.getName()); - volResponse.setServiceOfferingDisplayText(diskOffering.getDisplayText()); - } else { - volResponse.setDiskOfferingName(diskOffering.getName()); - volResponse.setDiskOfferingDisplayText(diskOffering.getDisplayText()); - } - volResponse.setStorageType(diskOffering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); - - Long poolId = volume.getPoolId(); - String poolName = (poolId == null) ? "none" : ApiDBUtils.findStoragePoolById(poolId).getName(); - volResponse.setStoragePoolName(poolName); - // volResponse.setSourceId(volume.getSourceId()); - // if (volume.getSourceType() != null) { - // volResponse.setSourceType(volume.getSourceType().toString()); - // } - - // return hypervisor for ROOT and Resource domain only - Account caller = UserContext.current().getCaller(); - if ((caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) && volume.getState() != Volume.State.UploadOp) { - volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); - } - - volResponse.setAttached(volume.getAttached()); - volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); - boolean isExtractable = true; - if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence. - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes - isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; - } - } - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Volume, volume.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - volResponse.setTags(tagResponses); - - volResponse.setExtractable(isExtractable); - volResponse.setObjectName("volume"); - return volResponse; + List viewVrs = ApiDBUtils.newVolumeView(volume); + List listVrs = ViewResponseHelper.createVolumeResponse(viewVrs.toArray(new VolumeJoinVO[viewVrs.size()])); + assert listVrs != null && listVrs.size() == 1 : "There should be one volume returned"; + return listVrs.get(0); } @Override public InstanceGroupResponse createInstanceGroupResponse(InstanceGroup group) { - InstanceGroupResponse groupResponse = new InstanceGroupResponse(); - groupResponse.setId(group.getId()); - groupResponse.setName(group.getName()); - groupResponse.setCreated(group.getCreated()); + InstanceGroupJoinVO vgroup = ApiDBUtils.newInstanceGroupView(group); + return ApiDBUtils.newInstanceGroupResponse(vgroup); - populateOwner(groupResponse, group); - - groupResponse.setObjectName("instancegroup"); - return groupResponse; } + + @Override public StoragePoolResponse createStoragePoolResponse(StoragePool pool) { - StoragePoolResponse poolResponse = new StoragePoolResponse(); - poolResponse.setId(pool.getId()); - poolResponse.setName(pool.getName()); - poolResponse.setState(pool.getStatus()); - poolResponse.setPath(pool.getPath()); - poolResponse.setIpAddress(pool.getHostAddress()); - poolResponse.setZoneId(pool.getDataCenterId()); - poolResponse.setZoneName(ApiDBUtils.findZoneById(pool.getDataCenterId()).getName()); - if (pool.getPoolType() != null) { - poolResponse.setType(pool.getPoolType().toString()); - } - if (pool.getPodId() != null) { - poolResponse.setPodId(pool.getPodId()); - HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); - if (pod != null) { - poolResponse.setPodName(pod.getName()); - } - } - if (pool.getCreated() != null) { - poolResponse.setCreated(pool.getCreated()); - } + List viewPools = ApiDBUtils.newStoragePoolView(pool); + List listPools = ViewResponseHelper.createStoragePoolResponse(viewPools.toArray(new StoragePoolJoinVO[viewPools.size()])); + assert listPools != null && listPools.size() == 1 : "There should be one storage pool returned"; + return listPools.get(0); - StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId()); - long allocatedSize = ApiDBUtils.getStorageCapacitybyPool(pool.getId(), Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); - poolResponse.setDiskSizeTotal(pool.getCapacityBytes()); - poolResponse.setDiskSizeAllocated(allocatedSize); - if (stats != null) { - Long used = stats.getByteUsed(); - poolResponse.setDiskSizeUsed(used); - } - - if (pool.getClusterId() != null) { - ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); - poolResponse.setClusterId(cluster.getId()); - poolResponse.setClusterName(cluster.getName()); - } - poolResponse.setTags(ApiDBUtils.getStoragePoolTags(pool.getId())); - poolResponse.setObjectName("storagepool"); - return poolResponse; } @Override public ClusterResponse createClusterResponse(Cluster cluster, Boolean showCapacities) { ClusterResponse clusterResponse = new ClusterResponse(); - clusterResponse.setId(cluster.getId()); + clusterResponse.setId(cluster.getUuid()); clusterResponse.setName(cluster.getName()); - clusterResponse.setPodId(cluster.getPodId()); - clusterResponse.setZoneId(cluster.getDataCenterId()); + HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); + if (pod != null) { + clusterResponse.setPodId(pod.getUuid()); + clusterResponse.setPodName(pod.getName()); + } + DataCenter dc = ApiDBUtils.findZoneById(cluster.getDataCenterId()); + if (dc != null) { + clusterResponse.setZoneId(dc.getUuid()); + clusterResponse.setZoneName(dc.getName()); + } clusterResponse.setHypervisorType(cluster.getHypervisorType().toString()); clusterResponse.setClusterType(cluster.getClusterType().toString()); clusterResponse.setAllocationState(cluster.getAllocationState().toString()); clusterResponse.setManagedState(cluster.getManagedState().toString()); - HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); - if (pod != null) { - clusterResponse.setPodName(pod.getName()); - } - DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); - clusterResponse.setZoneName(zone.getName()); + + if (showCapacities != null && showCapacities) { List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId()); Set capacityResponses = new HashSet(); @@ -1324,7 +935,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public FirewallRuleResponse createPortForwardingRuleResponse(PortForwardingRule fwRule) { FirewallRuleResponse response = new FirewallRuleResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setPrivateStartPort(Integer.toString(fwRule.getDestinationPortStart())); response.setPrivateEndPort(Integer.toString(fwRule.getDestinationPortEnd())); response.setProtocol(fwRule.getProtocol()); @@ -1334,13 +945,13 @@ public class ApiResponseHelper implements ResponseGenerator { response.setCidrList(StringUtils.join(cidrs, ",")); IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); - response.setPublicIpAddressId(ip.getId()); + response.setPublicIpAddressId(ip.getUuid()); response.setPublicIpAddress(ip.getAddress().addr()); if (ip != null && fwRule.getDestinationIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId()); if (vm != null) { - response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineId(vm.getUuid()); response.setVirtualMachineName(vm.getHostName()); if (vm.getDisplayName() != null) { @@ -1373,7 +984,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public IpForwardingRuleResponse createIpForwardingRuleResponse(StaticNatRule fwRule) { IpForwardingRuleResponse response = new IpForwardingRuleResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setProtocol(fwRule.getProtocol()); IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); @@ -1383,7 +994,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (ip != null && fwRule.getDestIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(ip.getAssociatedWithVmId()); if (vm != null) {// vm might be destroyed - response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineId(vm.getUuid()); response.setVirtualMachineName(vm.getHostName()); if (vm.getDisplayName() != null) { response.setVirtualMachineDisplayName(vm.getDisplayName()); @@ -1408,420 +1019,56 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public List createUserVmResponse(String objectName, EnumSet details, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - Map dataCenters = new HashMap(); - Map hosts = new HashMap(); - Map templates = new HashMap(); - Map serviceOfferings = new HashMap(); - Map networks = new HashMap(); + List viewVms = ApiDBUtils.newUserVmView(userVms); + return ViewResponseHelper.createUserVmResponse(objectName, details, viewVms.toArray(new UserVmJoinVO[viewVms.size()])); - List vmResponses = new ArrayList(); - - for (UserVm userVm : userVms) { - UserVmResponse userVmResponse = new UserVmResponse(); - Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); - if (acct != null) { - userVmResponse.setAccountName(acct.getAccountName()); - userVmResponse.setDomainId(acct.getDomainId()); - userVmResponse.setDomainName(ApiDBUtils.findDomainById(acct.getDomainId()).getName()); - } - - userVmResponse.setId(userVm.getId()); - userVmResponse.setName(userVm.getHostName()); - userVmResponse.setCreated(userVm.getCreated()); - - userVmResponse.setHaEnable(userVm.isHaEnabled()); - - if (userVm.getDisplayName() != null) { - userVmResponse.setDisplayName(userVm.getDisplayName()); - } else { - userVmResponse.setDisplayName(userVm.getHostName()); - } - - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - userVmResponse.setInstanceName(userVm.getInstanceName()); - } - - - if (userVm.getPassword() != null) { - userVmResponse.setPassword(userVm.getPassword()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { - InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId()); - if (group != null) { - userVmResponse.setGroup(group.getName()); - userVmResponse.setGroupId(group.getId()); - } - - } - - // Data Center Info - DataCenter zone = dataCenters.get(userVm.getDataCenterIdToDeployIn()); - if (zone == null) { - zone = ApiDBUtils.findZoneById(userVm.getDataCenterIdToDeployIn()); - dataCenters.put(zone.getId(), zone); - } - - userVmResponse.setZoneId(zone.getId()); - userVmResponse.setZoneName(zone.getName()); - - // if user is an admin, display host id - if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - - userVmResponse.setHostId(host.getId()); - userVmResponse.setHostName(host.getName()); - } - - if (userVm.getState() != null) { - if (userVm.getHostId() != null) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - if (host.getStatus() != com.cloud.host.Status.Up) { - userVmResponse.setState(VirtualMachine.State.Unknown.toString()); - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } - - if (userVm.getHypervisorType() != null) { - userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { - // Template Info - VMTemplateVO template = templates.get(userVm.getTemplateId()); - if (template == null) { - template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); - if (template != null) { - templates.put(template.getId(), template); - } - } - - if (template != null) { - userVmResponse.setTemplateId(userVm.getTemplateId()); - userVmResponse.setTemplateName(template.getName()); - userVmResponse.setTemplateDisplayText(template.getDisplayText()); - userVmResponse.setPasswordEnabled(template.getEnablePassword()); - } else { - userVmResponse.setTemplateId(-1L); - userVmResponse.setTemplateName("ISO Boot"); - userVmResponse.setTemplateDisplayText("ISO Boot"); - userVmResponse.setPasswordEnabled(false); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { - // ISO Info - VMTemplateVO iso = templates.get(userVm.getIsoId()); - if (iso == null) { - iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); - if (iso != null) { - templates.put(iso.getId(), iso); - } - } - - if (iso != null) { - userVmResponse.setIsoId(iso.getId()); - userVmResponse.setIsoName(iso.getName()); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - - userVmResponse.setServiceOfferingId(offering.getId()); - userVmResponse.setServiceOfferingName(offering.getName()); - userVmResponse.setCpuNumber(offering.getCpu()); - userVmResponse.setCpuSpeed(offering.getSpeed()); - userVmResponse.setMemory(offering.getRamSize()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { - VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); - if (rootVolume != null) { - userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); - String rootDeviceType = "Not created"; - if (rootVolume.getPoolId() != null) { - StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); - rootDeviceType = storagePool.getPoolType().toString(); - } - userVmResponse.setRootDeviceType(rootDeviceType); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { - // stats calculation - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - String cpuUsed = null; - VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - } - - userVmResponse.setGuestOsId(userVm.getGuestOSId()); - - if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { - // security groups - list only when zone is security group enabled - if (zone.isSecurityGroupEnabled()) { - List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); - List securityGroupResponse = new ArrayList(); - for (SecurityGroupVO grp : securityGroups) { - SecurityGroupResponse resp = new SecurityGroupResponse(); - resp.setId(grp.getId()); - resp.setName(grp.getName()); - resp.setDescription(grp.getDescription()); - resp.setObjectName("securitygroup"); - securityGroupResponse.add(resp); - } - userVmResponse.setSecurityGroupList(securityGroupResponse); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { - List nicProfiles = ApiDBUtils.getNics(userVm); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - nicResponse.setNetworkName(ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()).getName()); - if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - } - - // Long networkId = singleNicProfile.getNetworkId(); - Network network = networks.get(singleNicProfile.getNetworkId()); - if (network == null) { - network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - networks.put(singleNicProfile.getNetworkId(), network); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - nicResponse.setType(network.getGuestType().toString()); - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - userVmResponse.setNics(nicResponses); - } - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, userVm.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - userVmResponse.setTags(tagResponses); - - IpAddress ip = ApiDBUtils.findIpByAssociatedVmId(userVm.getId()); - if (ip != null) { - userVmResponse.setPublicIpId(ip.getId()); - userVmResponse.setPublicIp(ip.getAddress().addr()); - } - - userVmResponse.setObjectName(objectName); - vmResponses.add(userVmResponse); - } - - return vmResponses; } @Override public List createUserVmResponse(String objectName, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - boolean caller_is_admin = ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)); - - Hashtable vmDataList = new Hashtable(); - // Initialise the vmdatalist with the input data - for (UserVm userVm : userVms) { - UserVmData userVmData = newUserVmData(userVm); - vmDataList.put(userVm.getId(), userVmData); - } - - vmDataList = ApiDBUtils.listVmDetails(vmDataList); - - // initialize vmresponse from vmdatalist - List vmResponses = new ArrayList(); - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - for (UserVmData uvd : vmDataList.values()) { - UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin); - - // stats calculation - String cpuUsed = null; - // VmStats vmStats = ApiDBUtils.getVmStatistics(userVmResponse.getId()); - VmStats vmStats = ApiDBUtils.getVmStatistics(uvd.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - userVmResponse.setObjectName(objectName); - - vmResponses.add(userVmResponse); - } - return vmResponses; + List viewVms = ApiDBUtils.newUserVmView(userVms); + return ViewResponseHelper.createUserVmResponse(objectName, viewVms.toArray(new UserVmJoinVO[viewVms.size()])); } + + @Override public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { - Account caller = UserContext.current().getCaller(); - Map serviceOfferings = new HashMap(); - - DomainRouterResponse routerResponse = new DomainRouterResponse(); - routerResponse.setId(router.getId()); - routerResponse.setZoneId(router.getDataCenterIdToDeployIn()); - routerResponse.setName(router.getHostName()); - routerResponse.setTemplateId(router.getTemplateId()); - routerResponse.setCreated(router.getCreated()); - routerResponse.setState(router.getState()); - routerResponse.setIsRedundantRouter(router.getIsRedundantRouter()); - routerResponse.setRedundantState(router.getRedundantState().toString()); - - if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (router.getHostId() != null) { - routerResponse.setHostId(router.getHostId()); - routerResponse.setHostName(ApiDBUtils.findHostById(router.getHostId()).getName()); - } - routerResponse.setPodId(router.getPodIdToDeployIn()); - List nicProfiles = ApiDBUtils.getNics(router); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - //legacy code, public/control/guest nic info is kept in nics response object - if (network != null) { - if (network.getTrafficType() == TrafficType.Public) { - routerResponse.setPublicIp(singleNicProfile.getIp4Address()); - routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); - routerResponse.setGateway(singleNicProfile.getGateway()); - routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Control) { - routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); - routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Guest) { - routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); - routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); - routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); - routerResponse.setNetworkDomain(network.getNetworkDomain()); - } - - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - nicResponse.setNetworkName(network.getName()); - - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - if (network.getGuestType() != null) { - nicResponse.setType(network.getGuestType().toString()); - } - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - } - routerResponse.setNics(nicResponses); - } - - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(router.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(router.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - routerResponse.setServiceOfferingId(offering.getId()); - routerResponse.setServiceOfferingName(offering.getName()); - - populateOwner(routerResponse, router); - - DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); - if (zone != null) { - routerResponse.setZoneName(zone.getName()); - routerResponse.setDns1(zone.getDns1()); - routerResponse.setDns2(zone.getDns2()); - } - - routerResponse.setVpcId(router.getVpcId()); - - routerResponse.setObjectName("domainrouter"); - return routerResponse; + List viewVrs = ApiDBUtils.newDomainRouterView(router); + List listVrs = ViewResponseHelper.createDomainRouterResponse(viewVrs.toArray(new DomainRouterJoinVO[viewVrs.size()])); + assert listVrs != null && listVrs.size() == 1 : "There should be one virtual router returned"; + return listVrs.get(0); } + @Override public SystemVmResponse createSystemVmResponse(VirtualMachine vm) { SystemVmResponse vmResponse = new SystemVmResponse(); if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy) { // SystemVm vm = (SystemVm) systemVM; - vmResponse.setId(vm.getId()); - vmResponse.setObjectId(vm.getId()); + vmResponse.setId(vm.getUuid()); + //vmResponse.setObjectId(vm.getId()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); - vmResponse.setZoneId(vm.getDataCenterIdToDeployIn()); vmResponse.setName(vm.getHostName()); - vmResponse.setPodId(vm.getPodIdToDeployIn()); - vmResponse.setTemplateId(vm.getTemplateId()); + if ( vm.getPodIdToDeployIn() != null ){ + HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn()); + if ( pod != null ){ + vmResponse.setPodId(pod.getUuid()); + } + } + VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId()); + if (template != null){ + vmResponse.setTemplateId(template.getUuid()); + } vmResponse.setCreated(vm.getCreated()); if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); - vmResponse.setHostName(ApiDBUtils.findHostById(vm.getHostId()).getName()); + Host host = ApiDBUtils.findHostById(vm.getHostId()); + if (host != null) { + vmResponse.setHostId(host.getUuid()); + vmResponse.setHostName(host.getName()); + } } if (vm.getState() != null) { @@ -1839,6 +1086,7 @@ public class ApiResponseHelper implements ResponseGenerator { DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterIdToDeployIn()); if (zone != null) { + vmResponse.setZoneId(zone.getUuid()); vmResponse.setZoneName(zone.getName()); vmResponse.setDns1(zone.getDns1()); vmResponse.setDns2(zone.getDns2()); @@ -1904,7 +1152,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VpnUsersResponse createVpnUserResponse(VpnUser vpnUser) { VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getId()); + vpnResponse.setId(vpnUser.getUuid()); vpnResponse.setUserName(vpnUser.getUsername()); populateOwner(vpnResponse, vpnUser); @@ -1916,11 +1164,13 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) { RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse(); - vpnResponse.setPublicIpId(vpn.getServerAddressId()); - vpnResponse.setPublicIp(ApiDBUtils.findIpAddressById(vpn.getServerAddressId()).getAddress().addr()); + IpAddress ip = ApiDBUtils.findIpAddressById(vpn.getServerAddressId()); + if (ip != null) { + vpnResponse.setPublicIpId(ip.getUuid()); + vpnResponse.setPublicIp(ip.getAddress().addr()); + } vpnResponse.setIpRange(vpn.getIpRange()); vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey()); - vpnResponse.setDomainId(vpn.getDomainId()); populateOwner(vpnResponse, vpn); @@ -1933,14 +1183,17 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public TemplateResponse createIsoResponse(VirtualMachineTemplate result) { TemplateResponse response = new TemplateResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setName(result.getName()); response.setDisplayText(result.getDisplayText()); response.setPublic(result.isPublicTemplate()); response.setCreated(result.getCreated()); response.setFormat(result.getFormat()); - response.setOsTypeId(result.getGuestOSId()); - response.setOsTypeName(ApiDBUtils.findGuestOSById(result.getGuestOSId()).getDisplayName()); + GuestOS os = ApiDBUtils.findGuestOSById(result.getGuestOSId()); + if (os != null) { + response.setOsTypeId(os.getUuid()); + response.setOsTypeName(os.getDisplayName()); + } response.setDetails(result.getDetails()); Account caller = UserContext.current().getCaller(); @@ -2002,7 +1255,7 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); + templateResponse.setId(template.getUuid()); templateResponse.setName(template.getName()); templateResponse.setDisplayText(template.getDisplayText()); templateResponse.setPublic(template.isPublicTemplate()); @@ -2012,6 +1265,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setFeatured(template.isFeatured()); templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); templateResponse.setPasswordEnabled(template.getEnablePassword()); + templateResponse.setSshKeyEnabled(template.getEnableSshKey()); templateResponse.setCrossZones(template.isCrossZones()); templateResponse.setFormat(template.getFormat()); templateResponse.setDetails(template.getDetails()); @@ -2023,10 +1277,10 @@ public class ApiResponseHelper implements ResponseGenerator { GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { - templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeId(os.getUuid()); templateResponse.setOsTypeName(os.getDisplayName()); } else { - templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeId("-1"); templateResponse.setOsTypeName(""); } @@ -2052,7 +1306,12 @@ public class ApiResponseHelper implements ResponseGenerator { } templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + if (template.getSourceTemplateId() != null) { + VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId()); + if (tmpl != null) { + templateResponse.setSourceTemplateId(tmpl.getUuid()); + } + } templateResponse.setChecksum(template.getChecksum()); @@ -2078,7 +1337,7 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); + templateResponse.setId(template.getUuid()); templateResponse.setName(template.getName()); templateResponse.setDisplayText(template.getDisplayText()); templateResponse.setPublic(template.isPublicTemplate()); @@ -2088,6 +1347,7 @@ public class ApiResponseHelper implements ResponseGenerator { templateResponse.setFeatured(template.isFeatured()); templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM)); templateResponse.setPasswordEnabled(template.getEnablePassword()); + templateResponse.setSshKeyEnabled(template.getEnableSshKey()); templateResponse.setCrossZones(template.isCrossZones()); templateResponse.setFormat(template.getFormat()); if (template.getTemplateType() != null) { @@ -2099,10 +1359,10 @@ public class ApiResponseHelper implements ResponseGenerator { GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { - templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeId(os.getUuid()); templateResponse.setOsTypeName(os.getDisplayName()); } else { - templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeId("-1"); templateResponse.setOsTypeName(""); } @@ -2110,11 +1370,13 @@ public class ApiResponseHelper implements ResponseGenerator { populateAccount(templateResponse, account.getId()); populateDomain(templateResponse, account.getDomainId()); - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); + DataCenter datacenter = ApiDBUtils.findZoneById(zoneId); - // Add the zone ID - templateResponse.setZoneId(zoneId); - templateResponse.setZoneName(datacenter.getName()); + if (datacenter != null) { + // Add the zone ID + templateResponse.setZoneId(datacenter.getUuid()); + templateResponse.setZoneName(datacenter.getName()); + } boolean isAdmin = false; Account caller = UserContext.current().getCaller(); @@ -2150,7 +1412,12 @@ public class ApiResponseHelper implements ResponseGenerator { } templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + if (template.getSourceTemplateId() != null) { + VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId()); + if (tmpl != null) { + templateResponse.setSourceTemplateId(tmpl.getUuid()); + } + } templateResponse.setChecksum(template.getChecksum()); @@ -2182,7 +1449,7 @@ public class ApiResponseHelper implements ResponseGenerator { VirtualMachineTemplate iso = findTemplateById(isoId); if (iso.getTemplateType() == TemplateType.PERHOST) { TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2248,7 +1515,7 @@ public class ApiResponseHelper implements ResponseGenerator { final TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(iso.getId()); + templateResponse.setId(iso.getUuid()); templateResponse.setName(iso.getName()); templateResponse.setDisplayText(iso.getDisplayText()); templateResponse.setPublic(iso.isPublicTemplate()); @@ -2264,10 +1531,10 @@ public class ApiResponseHelper implements ResponseGenerator { final GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { - templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeId(os.getUuid()); templateResponse.setOsTypeName(os.getDisplayName()); } else { - templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeId(""); templateResponse.setOsTypeName(""); } @@ -2305,7 +1572,7 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2322,10 +1589,10 @@ public class ApiResponseHelper implements ResponseGenerator { // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { - isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeId(os.getUuid()); isoResponse.setOsTypeName(os.getDisplayName()); } else { - isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeId("-1"); isoResponse.setOsTypeName(""); } Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); @@ -2359,7 +1626,7 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2376,10 +1643,10 @@ public class ApiResponseHelper implements ResponseGenerator { // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { - isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeId(os.getUuid()); isoResponse.setOsTypeName(os.getDisplayName()); } else { - isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeId("-1"); isoResponse.setOsTypeName(""); } @@ -2393,9 +1660,11 @@ public class ApiResponseHelper implements ResponseGenerator { isAdmin = true; } // Add the zone ID - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); - isoResponse.setZoneId(zoneId); - isoResponse.setZoneName(datacenter.getName()); + DataCenter datacenter = ApiDBUtils.findZoneById(zoneId); + if (datacenter != null) { + isoResponse.setZoneId(datacenter.getUuid()); + isoResponse.setZoneName(datacenter.getName()); + } // If the user is an admin, add the template download status if (isAdmin || caller.getId() == iso.getAccountId()) { @@ -2439,92 +1708,14 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } - @Override - public ListResponse createSecurityGroupResponses( - List networkGroups) { - List groupResultObjs = SecurityGroupResultObject - .transposeNetworkGroups(networkGroups); - ListResponse response = new ListResponse(); - List netGrpResponses = new ArrayList(); - for (SecurityGroupResultObject networkGroup : groupResultObjs) { - SecurityGroupResponse netGrpResponse = new SecurityGroupResponse(); - netGrpResponse.setId(networkGroup.getId()); - netGrpResponse.setName(networkGroup.getName()); - netGrpResponse.setDescription(networkGroup.getDescription()); - - populateOwner(netGrpResponse, networkGroup); - - List securityGroupRules = networkGroup - .getSecurityGroupRules(); - if ((securityGroupRules != null) && !securityGroupRules.isEmpty()) { - List ingressRulesResponse = new ArrayList(); - List egressRulesResponse = new ArrayList(); - for (SecurityGroupRuleResultObject securityGroupRule : securityGroupRules) { - SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); - ruleData.setRuleId(securityGroupRule.getId()); - ruleData.setProtocol(securityGroupRule.getProtocol()); - - if ("icmp".equalsIgnoreCase(securityGroupRule.getProtocol())) { - ruleData.setIcmpType(securityGroupRule.getStartPort()); - ruleData.setIcmpCode(securityGroupRule.getEndPort()); - } else { - ruleData.setStartPort(securityGroupRule.getStartPort()); - ruleData.setEndPort(securityGroupRule.getEndPort()); - } - - if (securityGroupRule.getAllowedSecurityGroup() != null) { - ruleData.setSecurityGroupName(securityGroupRule - .getAllowedSecurityGroup()); - ruleData.setAccountName(securityGroupRule - .getAllowedSecGroupAcct()); - } else { - ruleData.setCidr(securityGroupRule - .getAllowedSourceIpCidr()); - } - - if (securityGroupRule.getRuleType() == SecurityRuleType.IngressRule) { - ruleData.setObjectName("ingressrule"); - ingressRulesResponse.add(ruleData); - } else { - ruleData.setObjectName("egressrule"); - egressRulesResponse.add(ruleData); - } - } - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, networkGroup.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - netGrpResponse.setTags(tagResponses); - - netGrpResponse - .setSecurityGroupIngressRules(ingressRulesResponse); - netGrpResponse.setSecurityGroupEgressRules(egressRulesResponse); - } - netGrpResponse.setObjectName("securitygroup"); - netGrpResponses.add(netGrpResponse); - } - - response.setResponses(netGrpResponses); - return response; - } @Override public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { - SecurityGroupResponse response = new SecurityGroupResponse(); - - populateOwner(response, group); - - response.setDescription(group.getDescription()); - response.setId(group.getId()); - response.setName(group.getName()); - - response.setObjectName("securitygroup"); - return response; - + List viewSgs = ApiDBUtils.newSecurityGroupView(group); + List listSgs = ViewResponseHelper.createSecurityGroupResponses(viewSgs); + assert listSgs != null && listSgs.size() == 1 : "There should be one security group returned"; + return listSgs.get(0); } @Override @@ -2532,16 +1723,19 @@ public class ApiResponseHelper implements ResponseGenerator { UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId); ExtractResponse response = new ExtractResponse(); response.setObjectName("template"); - response.setId(id); - response.setName(ApiDBUtils.findTemplateById(id).getName()); + VMTemplateVO template = ApiDBUtils.findTemplateById(id); + response.setId(template.getUuid()); + response.setName(template.getName()); if (zoneId != null) { - response.setZoneId(zoneId); - response.setZoneName(ApiDBUtils.findZoneById(zoneId).getName()); + DataCenter zone = ApiDBUtils.findZoneById(zoneId); + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); } response.setMode(mode); - response.setUploadId(uploadId); + response.setUploadId(uploadInfo.getUuid()); response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(accountId); + Account account = ApiDBUtils.findAccountById(accountId); + response.setAccountId(account.getUuid()); response.setUrl(uploadInfo.getUploadUrl()); return response; @@ -2554,39 +1748,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public AsyncJobResponse createAsyncJobResponse(AsyncJob job) { - AsyncJobResponse jobResponse = new AsyncJobResponse(); - jobResponse.setAccountId(job.getAccountId()); - jobResponse.setUserId(job.getUserId()); - jobResponse.setCmd(job.getCmd()); - jobResponse.setCreated(job.getCreated()); - jobResponse.setJobId(job.getId()); - jobResponse.setJobStatus(job.getStatus()); - jobResponse.setJobProcStatus(job.getProcessStatus()); - - if (job.getInstanceType() != null && job.getInstanceId() != null) { - jobResponse.setJobInstanceType(job.getInstanceType().toString()); - jobResponse.setJobInstanceId(job.getInstanceId()); - } - jobResponse.setJobResultCode(job.getResultCode()); - - boolean savedValue = SerializationContext.current().getUuidTranslation(); - SerializationContext.current().setUuidTranslation(false); - - Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); - jobResponse.setJobResult((ResponseObject) resultObject); - SerializationContext.current().setUuidTranslation(savedValue); - - if (resultObject != null) { - Class clz = resultObject.getClass(); - if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { - jobResponse.setJobResultType("text"); - } else { - jobResponse.setJobResultType("object"); - } - } - - jobResponse.setObjectName("asyncjobs"); - return jobResponse; + AsyncJobJoinVO vJob = ApiDBUtils.newAsyncJobView(job); + return ApiDBUtils.newAsyncJobResponse(vJob); } @Override @@ -2609,26 +1772,12 @@ public class ApiResponseHelper implements ResponseGenerator { return createTemplateResponses(templateId, host.getDataCenterId(), true); } + + @Override public EventResponse createEventResponse(Event event) { - EventResponse responseEvent = new EventResponse(); - responseEvent.setCreated(event.getCreateDate()); - responseEvent.setDescription(event.getDescription()); - responseEvent.setEventType(event.getType()); - responseEvent.setId(event.getId()); - responseEvent.setLevel(event.getLevel()); - responseEvent.setParentId(event.getStartId()); - responseEvent.setState(event.getState()); - - populateOwner(responseEvent, event); - - User user = ApiDBUtils.findUserById(event.getUserId()); - if (user != null) { - responseEvent.setUsername(user.getUsername()); - } - - responseEvent.setObjectName("event"); - return responseEvent; + EventJoinVO vEvent = ApiDBUtils.newEventView(event); + return ApiDBUtils.newEventResponse(vEvent); } private List sumCapacities(List hostCapacities) { @@ -2784,26 +1933,30 @@ public class ApiResponseHelper implements ResponseGenerator { capacityResponse.setCapacityType(summedCapacity.getCapacityType()); capacityResponse.setCapacityUsed(summedCapacity.getUsedCapacity()); if (summedCapacity.getPodId() != null) { - capacityResponse.setPodId(summedCapacity.getPodId()); + capacityResponse.setPodId(ApiDBUtils.findPodById(summedCapacity.getPodId()).getUuid()); HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); if (pod != null) { + capacityResponse.setPodId(pod.getUuid()); capacityResponse.setPodName(pod.getName()); } } if (summedCapacity.getClusterId() != null) { - capacityResponse.setClusterId(summedCapacity.getClusterId()); ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId()); if (cluster != null) { + capacityResponse.setClusterId(cluster.getUuid()); capacityResponse.setClusterName(cluster.getName()); if (summedCapacity.getPodId() == null) { - long podId = cluster.getPodId(); - capacityResponse.setPodId(podId); - capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); + HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); + capacityResponse.setPodId(pod.getUuid()); + capacityResponse.setPodName(pod.getName()); } } } - capacityResponse.setZoneId(summedCapacity.getDataCenterId()); - capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); + DataCenter zone = ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()); + if (zone != null) { + capacityResponse.setZoneId(zone.getUuid()); + capacityResponse.setZoneName(zone.getName()); + } if (summedCapacity.getUsedPercentage() != null){ capacityResponse.setPercentUsed(format.format(summedCapacity.getUsedPercentage() * 100f)); } else if (summedCapacity.getTotalCapacity() != 0) { @@ -2832,10 +1985,13 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplatePermissionsResponse response = new TemplatePermissionsResponse(); - response.setId(template.getId()); + response.setId(template.getUuid()); response.setPublicTemplate(template.isPublicTemplate()); if (isAdmin && (templateOwnerDomain != null)) { - response.setDomainId(templateOwnerDomain); + Domain domain = ApiDBUtils.findDomainById(templateOwnerDomain); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } } // Set accounts @@ -2882,27 +2038,27 @@ public class ApiResponseHelper implements ResponseGenerator { Map allowedSecuriytGroupAccounts = new HashMap(); if ((securityRules != null) && !securityRules.isEmpty()) { - SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(securityRules.get(0).getSecurityGroupId()); - response.setId(securityGroup.getId()); + SecurityGroupJoinVO securityGroup = ApiDBUtils.findSecurityGroupViewById(securityRules.get(0).getSecurityGroupId()).get(0); + response.setId(securityGroup.getUuid()); response.setName(securityGroup.getName()); response.setDescription(securityGroup.getDescription()); Account account = securiytGroupAccounts.get(securityGroup.getAccountId()); - if (account == null) { - account = ApiDBUtils.findAccountById(securityGroup.getAccountId()); - securiytGroupAccounts.put(securityGroup.getAccountId(), account); + if (securityGroup.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + response.setProjectId(securityGroup.getProjectUuid()); + response.setProjectName(securityGroup.getProjectName()); + } else { + response.setAccountName(securityGroup.getAccountName()); } - populateAccount(response, account.getId()); - populateDomain(response, account.getDomainId()); + response.setDomainId(securityGroup.getDomainUuid()); + response.setDomainName(securityGroup.getDomainName()); - List egressResponses = new ArrayList(); - List ingressResponses = new ArrayList(); for (SecurityRule securityRule : securityRules) { SecurityGroupRuleResponse securityGroupData = new SecurityGroupRuleResponse(); - securityGroupData.setRuleId(securityRule.getId()); + securityGroupData.setRuleId(securityRule.getUuid()); securityGroupData.setProtocol(securityRule.getProtocol()); if ("icmp".equalsIgnoreCase(securityRule.getProtocol())) { securityGroupData.setIcmpType(securityRule.getStartPort()); @@ -2914,35 +2070,24 @@ public class ApiResponseHelper implements ResponseGenerator { Long allowedSecurityGroupId = securityRule.getAllowedNetworkId(); if (allowedSecurityGroupId != null) { - SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); - if (allowedSecurityGroup == null) { - allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId); - allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); + List sgs = ApiDBUtils.findSecurityGroupViewById(allowedSecurityGroupId); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + securityGroupData.setSecurityGroupName(sg.getName()); + securityGroupData.setAccountName(sg.getAccountName()); } - - securityGroupData.setSecurityGroupName(allowedSecurityGroup.getName()); - - Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId()); - if (allowedAccount == null) { - allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId()); - allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount); - } - - securityGroupData.setAccountName(allowedAccount.getAccountName()); } else { securityGroupData.setCidr(securityRule.getAllowedSourceIpCidr()); } if (securityRule.getRuleType() == SecurityRuleType.IngressRule) { securityGroupData.setObjectName("ingressrule"); - ingressResponses.add(securityGroupData); + response.addSecurityGroupIngressRule(securityGroupData); } else { securityGroupData.setObjectName("egressrule"); - egressResponses.add(securityGroupData); + response.addSecurityGroupEgressRule(securityGroupData); } } - response.setSecurityGroupIngressRules(ingressResponses); - response.setSecurityGroupEgressRules(egressResponses); response.setObjectName("securitygroup"); } @@ -2952,7 +2097,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public NetworkOfferingResponse createNetworkOfferingResponse(NetworkOffering offering) { NetworkOfferingResponse response = new NetworkOfferingResponse(); - response.setId(offering.getId()); + response.setId(offering.getUuid()); response.setName(offering.getName()); response.setDisplayText(offering.getDisplayText()); response.setTags(offering.getTags()); @@ -2963,11 +2108,18 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyIpRanges(offering.getSpecifyIpRanges()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); + Long so = null; if (offering.getServiceOfferingId() != null) { - response.setServiceOfferingId(offering.getServiceOfferingId()); + so = offering.getServiceOfferingId(); } else { - response.setServiceOfferingId(ApiDBUtils.findDefaultRouterServiceOffering()); + so = ApiDBUtils.findDefaultRouterServiceOffering(); } + if (so != null) { + ServiceOffering soffering = ApiDBUtils.findServiceOfferingById(so); + if (soffering != null) + response.setServiceOfferingId(soffering.getUuid()); + } + if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); } @@ -3006,6 +2158,11 @@ public class ApiResponseHelper implements ResponseGenerator { eLb.setValue(offering.getElasticLb() ? "true" : "false"); lbCapResponse.add(eLb); + CapabilityResponse inline = new CapabilityResponse(); + inline.setName(Capability.InlineMode.getName()); + inline.setValue(offering.isInline() ? "true" : "false"); + lbCapResponse.add(inline); + svcRsp.setCapabilities(lbCapResponse); } else if (Service.SourceNat == service) { List capabilities = new ArrayList(); @@ -3034,7 +2191,7 @@ public class ApiResponseHelper implements ResponseGenerator { serviceResponses.add(svcRsp); } response.setForVpc(ApiDBUtils.isOfferingForVpc(offering)); - + response.setServices(serviceResponses); response.setObjectName("networkoffering"); return response; @@ -3045,7 +2202,7 @@ public class ApiResponseHelper implements ResponseGenerator { // need to get network profile in order to retrieve dns information from there NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); NetworkResponse response = new NetworkResponse(); - response.setId(network.getId()); + response.setId(network.getUuid()); response.setName(network.getName()); response.setDisplaytext(network.getDisplayText()); if (network.getBroadcastDomainType() != null) { @@ -3074,22 +2231,27 @@ public class ApiResponseHelper implements ResponseGenerator { response.setBroadcastUri(broadcastUri); String vlan="N/A"; if (broadcastUri.startsWith("vlan")) { - vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); + vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); } //return vlan information only to Root admin response.setVlan(vlan); - + } DataCenter zone = ApiDBUtils.findZoneById(network.getDataCenterId()); - response.setZoneId(network.getDataCenterId()); - response.setZoneName(zone.getName()); - response.setPhysicalNetworkId(network.getPhysicalNetworkId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } + if (network.getPhysicalNetworkId() != null) { + PhysicalNetworkVO pnet = ApiDBUtils.findPhysicalNetworkById(network.getPhysicalNetworkId()); + response.setPhysicalNetworkId(pnet.getUuid()); + } // populate network offering information - NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); + NetworkOffering networkOffering = (NetworkOffering) ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); if (networkOffering != null) { - response.setNetworkOfferingId(networkOffering.getId()); + response.setNetworkOfferingId(networkOffering.getUuid()); response.setNetworkOfferingName(networkOffering.getName()); response.setNetworkOfferingDisplayText(networkOffering.getDisplayText()); response.setIsSystem(networkOffering.isSystemOnly()); @@ -3101,7 +2263,10 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setState(network.getState().toString()); response.setRestartRequired(network.isRestartRequired()); - response.setRelated(network.getRelated()); + NetworkVO nw = ApiDBUtils.findNetworkById(network.getRelated()); + if (nw != null) { + response.setRelated(nw.getUuid()); + } response.setNetworkDomain(network.getNetworkDomain()); response.setDns1(profile.getDns1()); @@ -3144,19 +2309,31 @@ public class ApiResponseHelper implements ResponseGenerator { } else { // get domain from network_domain table Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); - response.setDomainId(domainNetworkDetails.first()); + if (domainNetworkDetails.first() != null) { + Domain domain = ApiDBUtils.findDomainById(domainNetworkDetails.first()); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } + } response.setSubdomainAccess(domainNetworkDetails.second()); } Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); if (dedicatedDomainId != null) { Domain domain = ApiDBUtils.findDomainById(dedicatedDomainId); - response.setDomainId(dedicatedDomainId); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } response.setDomainName(domain.getName()); } response.setSpecifyIpRanges(network.getSpecifyIpRanges()); - response.setVpcId(network.getVpcId()); + if (network.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(network.getVpcId()); + if (vpc != null) { + response.setVpcId(vpc.getUuid()); + } + } response.setCanUseForDeploy(ApiDBUtils.canUseForDeploy(network)); //set tag information @@ -3184,36 +2361,20 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ProjectResponse createProjectResponse(Project project) { - ProjectResponse response = new ProjectResponse(); - response.setId(project.getId()); - response.setName(project.getName()); - response.setDisplaytext(project.getDisplayText()); - response.setState(project.getState().toString()); - - Domain domain = ApiDBUtils.findDomainById(project.getDomainId()); - response.setDomainId(domain.getId()); - response.setDomain(domain.getName()); - - response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Project, project.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - response.setTags(tagResponses); - - response.setObjectName("project"); - return response; + List viewPrjs = ApiDBUtils.newProjectView(project); + List listPrjs = ViewResponseHelper.createProjectResponse(viewPrjs.toArray(new ProjectJoinVO[viewPrjs.size()])); + assert listPrjs != null && listPrjs.size() == 1 : "There should be one project returned"; + return listPrjs.get(0); } + + + @Override public FirewallResponse createFirewallResponse(FirewallRule fwRule) { FirewallResponse response = new FirewallResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setProtocol(fwRule.getProtocol()); if (fwRule.getSourcePortStart() != null) { response.setStartPort(Integer.toString(fwRule.getSourcePortStart())); @@ -3252,12 +2413,12 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("firewallrule"); return response; } - + @Override public NetworkACLResponse createNetworkACLResponse(FirewallRule networkACL) { NetworkACLResponse response = new NetworkACLResponse(); - response.setId(networkACL.getId()); + response.setId(networkACL.getUuid()); response.setProtocol(networkACL.getProtocol()); if (networkACL.getSourcePortStart() != null) { response.setStartPort(Integer.toString(networkACL.getSourcePortStart())); @@ -3282,7 +2443,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setIcmpType(networkACL.getIcmpType()); response.setState(stateToSet); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.NetworkACL, networkACL.getId()); List tagResponses = new ArrayList(); @@ -3291,150 +2452,15 @@ public class ApiResponseHelper implements ResponseGenerator { tagResponses.add(tagResponse); } response.setTags(tagResponses); - + response.setObjectName("networkacl"); return response; } - public UserVmData newUserVmData(UserVm userVm) { - UserVmData userVmData = new UserVmData(); - userVmData.setId(userVm.getId()); - userVmData.setName(userVm.getHostName()); - userVmData.setCreated(userVm.getCreated()); - userVmData.setGuestOsId(userVm.getGuestOSId()); - userVmData.setHaEnable(userVm.isHaEnabled()); - if (userVm.getState() != null) { - userVmData.setState(userVm.getState().toString()); - } - if (userVm.getDisplayName() != null) { - userVmData.setDisplayName(userVm.getDisplayName()); - } else { - userVmData.setDisplayName(userVm.getHostName()); - } - userVmData.setInstanceName(userVm.getInstanceName()); - - userVmData.setDomainId(userVm.getDomainId()); - - if (userVm.getHypervisorType() != null) { - userVmData.setHypervisor(userVm.getHypervisorType().toString()); - } - - if (userVm.getPassword() != null) { - userVmData.setPassword(userVm.getPassword()); - } - return userVmData; - } - - public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) { - UserVmResponse userVmResponse = new UserVmResponse(); - - userVmResponse.setHypervisor(userVmData.getHypervisor()); - userVmResponse.setId(userVmData.getId()); - userVmResponse.setName(userVmData.getName()); - - userVmResponse.setDisplayName(userVmData.getDisplayName()); - - populateAccount(userVmResponse, userVmData.getAccountId()); - populateDomain(userVmResponse, userVmData.getDomainId()); - - userVmResponse.setCreated(userVmData.getCreated()); - userVmResponse.setState(userVmData.getState()); - userVmResponse.setHaEnable(userVmData.getHaEnable()); - userVmResponse.setGroupId(userVmData.getGroupId()); - userVmResponse.setGroup(userVmData.getGroup()); - userVmResponse.setZoneId(userVmData.getZoneId()); - userVmResponse.setZoneName(userVmData.getZoneName()); - if (caller_is_admin) { - userVmResponse.setInstanceName(userVmData.getInstanceName()); - userVmResponse.setHostId(userVmData.getHostId()); - userVmResponse.setHostName(userVmData.getHostName()); - } - userVmResponse.setTemplateId(userVmData.getTemplateId()); - userVmResponse.setTemplateName(userVmData.getTemplateName()); - userVmResponse.setTemplateDisplayText(userVmData.getTemplateDisplayText()); - userVmResponse.setPasswordEnabled(userVmData.getPasswordEnabled()); - userVmResponse.setIsoId(userVmData.getIsoId()); - userVmResponse.setIsoName(userVmData.getIsoName()); - userVmResponse.setIsoDisplayText(userVmData.getIsoDisplayText()); - userVmResponse.setServiceOfferingId(userVmData.getServiceOfferingId()); - userVmResponse.setServiceOfferingName(userVmData.getServiceOfferingName()); - userVmResponse.setCpuNumber(userVmData.getCpuNumber()); - userVmResponse.setCpuSpeed(userVmData.getCpuSpeed()); - userVmResponse.setMemory(userVmData.getMemory()); - userVmResponse.setCpuUsed(userVmData.getCpuUsed()); - userVmResponse.setNetworkKbsRead(userVmData.getNetworkKbsRead()); - userVmResponse.setNetworkKbsWrite(userVmData.getNetworkKbsWrite()); - userVmResponse.setGuestOsId(userVmData.getGuestOsId()); - userVmResponse.setRootDeviceId(userVmData.getRootDeviceId()); - userVmResponse.setRootDeviceType(userVmData.getRootDeviceType()); - userVmResponse.setPassword(userVmData.getPassword()); - userVmResponse.setJobId(userVmData.getJobId()); - userVmResponse.setJobStatus(userVmData.getJobStatus()); - userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork()); - - Set securityGroupResponse = new HashSet(); - for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) { - if (sgd.getId() != null) { - SecurityGroupResponse sgr = new SecurityGroupResponse(); - sgr.setId(sgd.getId()); - sgr.setName(sgd.getName()); - sgr.setDescription(sgd.getDescription()); - - Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); - if (account != null) { - populateAccount(sgr, account.getId()); - populateDomain(sgr, account.getDomainId()); - } - - sgr.setObjectName(sgd.getObjectName()); - securityGroupResponse.add(sgr); - } - } - userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); - - Set nicResponses = new HashSet(); - for (NicData nd : userVmData.getNics()) { - NicResponse nr = new NicResponse(); - nr.setId(nd.getId()); - nr.setNetworkid(nd.getNetworkid()); - nr.setNetmask(nd.getNetmask()); - nr.setGateway(nd.getGateway()); - nr.setIpaddress(nd.getIpaddress()); - nr.setIsolationUri(nd.getIsolationUri()); - nr.setBroadcastUri(nd.getBroadcastUri()); - nr.setTrafficType(nd.getTrafficType()); - nr.setType(nd.getType()); - nr.setIsDefault(nd.getIsDefault()); - nr.setMacAddress(nd.getMacAddress()); - nr.setObjectName(nd.getObjectName()); - nicResponses.add(nr); - } - userVmResponse.setNics(new ArrayList(nicResponses)); - userVmResponse.setPublicIpId(userVmData.getPublicIpId()); - userVmResponse.setPublicIp(userVmData.getPublicIp()); - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, userVmData.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - userVmResponse.setTags(tagResponses); - - UserVmDetailVO userVmDetail = ApiDBUtils.findPublicKeyByVmId(userVmData.getId()); - if (userVmDetail != null && userVmDetail.getValue() != null) { - String keyPairName = ApiDBUtils.getKeyPairName(userVmDetail.getValue()); - userVmResponse.setKeyPairName(keyPairName); - } - - return userVmResponse; - } - @Override public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) { HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse(); - hpvCapabilitiesResponse.setId(hpvCapabilities.getId()); + hpvCapabilitiesResponse.setId(hpvCapabilities.getUuid()); hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType()); hpvCapabilitiesResponse.setHypervisorVersion(hpvCapabilities.getHypervisorVersion()); hpvCapabilitiesResponse.setIsSecurityGroupEnabled(hpvCapabilities.isSecurityGroupEnabled()); @@ -3442,29 +2468,44 @@ public class ApiResponseHelper implements ResponseGenerator { return hpvCapabilitiesResponse; } + // TODO: we may need to refactor once ControlledEntityResponse and ControlledEntity id to uuid conversion are all done. + // currently code is scattered in private void populateOwner(ControlledEntityResponse response, ControlledEntity object) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { // find the project Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); + response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); } Domain domain = ApiDBUtils.findDomainById(object.getDomainId()); - response.setDomainId(domain.getId()); + response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); } + public static void populateOwner(ControlledViewEntityResponse response, ControlledViewEntity object) { + + if (object.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + response.setProjectId(object.getProjectUuid()); + response.setProjectName(object.getProjectName()); + } else { + response.setAccountName(object.getAccountName()); + } + + response.setDomainId(object.getDomainUuid()); + response.setDomainName(object.getDomainName()); + } + private void populateAccount(ControlledEntityResponse response, long accountId) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { // find the project Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); + response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); @@ -3474,69 +2515,39 @@ public class ApiResponseHelper implements ResponseGenerator { private void populateDomain(ControlledEntityResponse response, long domainId) { Domain domain = ApiDBUtils.findDomainById(domainId); - response.setDomainId(domain.getId()); + response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); } @Override public ProjectAccountResponse createProjectAccountResponse(ProjectAccount projectAccount) { - Account account = ApiDBUtils.findAccountById(projectAccount.getAccountId()); - ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); - - long projectId = projectAccount.getProjectId(); - projectAccountResponse.setProjectId(projectId); - projectAccountResponse.setProjectName(ApiDBUtils.findProjectById(projectId).getName()); - - projectAccountResponse.setId(account.getId()); - projectAccountResponse.setAccountName(account.getAccountName()); - projectAccountResponse.setAccountType(account.getType()); - projectAccountResponse.setRole(projectAccount.getAccountRole().toString()); - populateDomain(projectAccountResponse, account.getDomainId()); - - // add all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - projectAccountResponse.setUsers(userResponseList); - projectAccountResponse.setObjectName("projectaccount"); - - return projectAccountResponse; + ProjectAccountJoinVO vProj = ApiDBUtils.newProjectAccountView(projectAccount); + List listProjs = ViewResponseHelper.createProjectAccountResponse(vProj); + assert listProjs != null && listProjs.size() == 1 : "There should be one project account returned"; + return listProjs.get(0); } + + + @Override public ProjectInvitationResponse createProjectInvitationResponse(ProjectInvitation invite) { - ProjectInvitationResponse response = new ProjectInvitationResponse(); - response.setId(invite.getId()); - response.setProjectId(invite.getProjectId()); - response.setProjectName(ApiDBUtils.findProjectById(invite.getProjectId()).getName()); - response.setInvitationState(invite.getState().toString()); - - if (invite.getForAccountId() != null) { - Account account = ApiDBUtils.findAccountById(invite.getForAccountId()); - response.setAccountName(account.getAccountName()); - - } else { - response.setEmail(invite.getEmail()); - } - - populateDomain(response, invite.getInDomainId()); - - response.setObjectName("projectinvitation"); - return response; + ProjectInvitationJoinVO vInvite = ApiDBUtils.newProjectInvitationView(invite); + return ApiDBUtils.newProjectInvitationResponse(vInvite); } + @Override public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); - vmResponse.setId(vm.getId()); + vmResponse.setId(vm.getUuid()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); vmResponse.setName(vm.getHostName()); if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); + Host host = ApiDBUtils.findHostById(vm.getHostId()); + if (host != null) { + vmResponse.setHostId(host.getUuid()); + } } if (vm.getState() != null) { vmResponse.setState(vm.getState().toString()); @@ -3555,10 +2566,18 @@ public class ApiResponseHelper implements ResponseGenerator { public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { PhysicalNetworkResponse response = new PhysicalNetworkResponse(); - response.setZoneId(result.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(result.getDataCenterId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + } response.setNetworkSpeed(result.getSpeed()); response.setVlan(result.getVnet()); - response.setDomainId(result.getDomainId()); + if (result.getDomainId() != null) { + Domain domain = ApiDBUtils.findDomainById(result.getDomainId()); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } + } response.setId(result.getUuid()); if (result.getBroadcastDomainRange() != null) { response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); @@ -3630,8 +2649,14 @@ public class ApiResponseHelper implements ResponseGenerator { ProviderResponse response = new ProviderResponse(); response.setId(result.getUuid()); response.setName(result.getProviderName()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + PhysicalNetwork dnw = ApiDBUtils.findPhysicalNetworkById(result.getDestinationPhysicalNetworkId()); + if (dnw != null) { + response.setDestinationPhysicalNetworkId(dnw.getUuid()); + } response.setState(result.getState().toString()); // set enabled services @@ -3649,8 +2674,14 @@ public class ApiResponseHelper implements ResponseGenerator { public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result) { TrafficTypeResponse response = new TrafficTypeResponse(); response.setId(result.getUuid()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setTrafficType(result.getTrafficType().toString()); + PhysicalNetwork pnet = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnet != null) { + response.setPhysicalNetworkId(pnet.getUuid()); + } + if (result.getTrafficType() != null) { + response.setTrafficType(result.getTrafficType().toString()); + } + response.setXenLabel(result.getXenNetworkLabel()); response.setKvmLabel(result.getKvmNetworkLabel()); response.setVmwareLabel(result.getVmwareNetworkLabel()); @@ -3662,8 +2693,11 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); - response.setId(result.getId()); - response.setNspId(result.getNspId()); + response.setId(result.getUuid()); + PhysicalNetworkServiceProvider nsp = ApiDBUtils.findPhysicalNetworkServiceProviderById(result.getNspId()); + if (nsp != null) { + response.setNspId(nsp.getUuid()); + } response.setEnabled(result.isEnabled()); response.setObjectName("virtualrouterelement"); @@ -3675,13 +2709,15 @@ public class ApiResponseHelper implements ResponseGenerator { StickinessPolicy stickinessPolicy, LoadBalancer lb) { LBStickinessResponse spResponse = new LBStickinessResponse(); - spResponse.setlbRuleId(lb.getId()); + spResponse.setlbRuleId(lb.getUuid()); Account accountTemp = ApiDBUtils.findAccountById(lb.getAccountId()); if (accountTemp != null) { spResponse.setAccountName(accountTemp.getAccountName()); - spResponse.setDomainId(accountTemp.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - accountTemp.getDomainId()).getName()); + Domain domain = ApiDBUtils.findDomainById(accountTemp.getDomainId()); + if (domain != null) { + spResponse.setDomainId(domain.getUuid()); + spResponse.setDomainName(domain.getName()); + } } List responses = new ArrayList(); @@ -3702,13 +2738,15 @@ public class ApiResponseHelper implements ResponseGenerator { if (lb == null) return spResponse; - spResponse.setlbRuleId(lb.getId()); + spResponse.setlbRuleId(lb.getUuid()); Account account = ApiDBUtils.findAccountById(lb.getAccountId()); if (account != null) { spResponse.setAccountName(account.getAccountName()); - spResponse.setDomainId(account.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - account.getDomainId()).getName()); + Domain domain = ApiDBUtils.findDomainById(account.getDomainId()); + if (domain != null) { + spResponse.setDomainId(domain.getUuid()); + spResponse.setDomainName(domain.getName()); + } } List responses = new ArrayList(); @@ -3753,52 +2791,18 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - @Override - public Long getIdentiyId(String tableName, String token) { - return ApiDispatcher.getIdentiyId(tableName, token); - } - @Override public ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly) { - ResourceTagResponse response = new ResourceTagResponse(); - response.setKey(resourceTag.getKey()); - response.setValue(resourceTag.getValue()); - - if (!keyValueOnly) { - response.setResourceType(resourceTag.getResourceType().toString()); - response.setId(ApiDBUtils.getUuid(String.valueOf(resourceTag.getResourceId()),resourceTag.getResourceType())); - Long accountId = resourceTag.getAccountId(); - Long domainId = resourceTag.getDomainId(); - if (accountId != null) { - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(resourceTag.getAccountId()); - - if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - // find the project - Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); - response.setProjectName(project.getName()); - } else { - response.setAccountName(account.getAccountName()); - } - } - - if (domainId != null) { - response.setDomainId(domainId); - response.setDomainName(ApiDBUtils.findDomainById(domainId).getName()); - } - - response.setCustomer(resourceTag.getCustomer()); - } - - response.setObjectName("ag"); - - return response; + ResourceTagJoinVO rto = ApiDBUtils.newResourceTagView(resourceTag); + return ApiDBUtils.newResourceTagResponse(rto, keyValueOnly); } - + + + @Override public VpcOfferingResponse createVpcOfferingResponse(VpcOffering offering) { VpcOfferingResponse response = new VpcOfferingResponse(); - response.setId(offering.getId()); + response.setId(offering.getUuid()); response.setName(offering.getName()); response.setDisplayText(offering.getDisplayText()); response.setIsDefault(offering.isDefault()); @@ -3829,16 +2833,19 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("vpcoffering"); return response; } - - + + @Override public VpcResponse createVpcResponse(Vpc vpc) { VpcResponse response = new VpcResponse(); - response.setId(vpc.getId()); + response.setId(vpc.getUuid()); response.setName(vpc.getName()); response.setDisplayText(vpc.getDisplayText()); response.setState(vpc.getState().name()); - response.setVpcOfferingId(vpc.getVpcOfferingId()); + VpcOffering voff = ApiDBUtils.findVpcOfferingById(vpc.getVpcOfferingId()); + if (voff != null) { + response.setVpcOfferingId(voff.getUuid()); + } response.setCidr(vpc.getCidr()); response.setRestartRequired(vpc.isRestartRequired()); response.setNetworkDomain(vpc.getNetworkDomain()); @@ -3864,22 +2871,24 @@ public class ApiResponseHelper implements ResponseGenerator { serviceResponses.add(svcRsp); } - + List networkResponses = new ArrayList(); List networks = ApiDBUtils.listVpcNetworks(vpc.getId()); for (Network network : networks) { NetworkResponse ntwkRsp = createNetworkResponse(network); networkResponses.add(ntwkRsp); } - + DataCenter zone = ApiDBUtils.findZoneById(vpc.getZoneId()); - response.setZoneId(vpc.getZoneId()); - response.setZoneName(zone.getName()); - + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } + response.setNetworks(networkResponses); response.setServices(serviceResponses); populateOwner(response, vpc); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Vpc, vpc.getId()); List tagResponses = new ArrayList(); @@ -3895,23 +2904,32 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public PrivateGatewayResponse createPrivateGatewayResponse(PrivateGateway result) { PrivateGatewayResponse response = new PrivateGatewayResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setVlan(result.getVlanTag()); response.setGateway(result.getGateway()); response.setNetmask(result.getNetmask()); - response.setVpcId(result.getVpcId()); - response.setZoneId(result.getZoneId()); + if (result.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + response.setVpcId(vpc.getUuid()); + } + DataCenter zone = ApiDBUtils.findZoneById(result.getZoneId()); - response.setZoneName(zone.getName()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } response.setAddress(result.getIp4Address()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - + PhysicalNetwork pnet = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnet != null) { + response.setPhysicalNetworkId(pnet.getUuid()); + } + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); response.setState(result.getState().toString()); - + response.setObjectName("privategateway"); - + return response; } @@ -3919,7 +2937,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public CounterResponse createCounterResponse(Counter counter) { CounterResponse response = new CounterResponse(); - response.setId(counter.getId()); + response.setId(counter.getUuid()); response.setSource(counter.getSource().toString()); response.setName(counter.getName()); response.setValue(counter.getValue()); @@ -3930,7 +2948,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ConditionResponse createConditionResponse(Condition condition) { ConditionResponse response = new ConditionResponse(); - response.setId(condition.getId()); + response.setId(condition.getUuid()); List counterResponseList = new ArrayList(); counterResponseList.add(createCounterResponse(ApiDBUtils.getCounter(condition.getCounterid()))); response.setCounterResponse(counterResponseList); @@ -3944,14 +2962,32 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public AutoScaleVmProfileResponse createAutoScaleVmProfileResponse(AutoScaleVmProfile profile) { AutoScaleVmProfileResponse response = new AutoScaleVmProfileResponse(); - response.setId(profile.getId()); - response.setZoneId(profile.getZoneId()); - response.setServiceOfferingId(profile.getServiceOfferingId()); - response.setTemplateId(profile.getTemplateId()); + response.setId(profile.getUuid()); + if (profile.getZoneId() != null) { + DataCenter zone = ApiDBUtils.findZoneById(profile.getZoneId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + } + } + if (profile.getServiceOfferingId() != null) { + ServiceOffering so = ApiDBUtils.findServiceOfferingById(profile.getServiceOfferingId()); + if (so != null) { + response.setServiceOfferingId(so.getUuid()); + } + } + if (profile.getTemplateId() != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(profile.getTemplateId()); + if (template != null) { + response.setTemplateId(template.getUuid()); + } + } response.setOtherDeployParams(profile.getOtherDeployParams()); response.setCounterParams(profile.getCounterParams()); response.setDestroyVmGraceperiod(profile.getDestroyVmGraceperiod()); - response.setAutoscaleUserId(profile.getAutoScaleUserId()); + User user = ApiDBUtils.findUserById(profile.getAutoScaleUserId()); + if (user != null) { + response.setAutoscaleUserId(user.getUuid()); + } response.setObjectName("autoscalevmprofile"); // Populates the account information in the response @@ -3962,7 +2998,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public AutoScalePolicyResponse createAutoScalePolicyResponse(AutoScalePolicy policy) { AutoScalePolicyResponse response = new AutoScalePolicyResponse(); - response.setId(policy.getId()); + response.setId(policy.getUuid()); response.setDuration(policy.getDuration()); response.setQuietTime(policy.getQuietTime()); response.setAction(policy.getAction()); @@ -3983,13 +3019,19 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public AutoScaleVmGroupResponse createAutoScaleVmGroupResponse(AutoScaleVmGroup vmGroup) { AutoScaleVmGroupResponse response = new AutoScaleVmGroupResponse(); - response.setId(vmGroup.getId()); + response.setId(vmGroup.getUuid()); response.setMinMembers(vmGroup.getMinMembers()); response.setMaxMembers(vmGroup.getMaxMembers()); response.setState(vmGroup.getState()); response.setInterval(vmGroup.getInterval()); - response.setProfileId(vmGroup.getProfileId()); - response.setLoadBalancerId(vmGroup.getProfileId()); + AutoScaleVmProfileVO profile = ApiDBUtils.findAutoScaleVmProfileById(vmGroup.getProfileId()); + if (profile != null) { + response.setProfileId(profile.getUuid()); + } + FirewallRuleVO fw = ApiDBUtils.findFirewallRuleById(vmGroup.getProfileId()); + if (fw != null) { + response.setLoadBalancerId(fw.getUuid()); + } List scaleUpPoliciesResponse = new ArrayList(); List scaleDownPoliciesResponse = new ArrayList(); @@ -4011,14 +3053,19 @@ public class ApiResponseHelper implements ResponseGenerator { return response; } - + @Override public StaticRouteResponse createStaticRouteResponse(StaticRoute result) { StaticRouteResponse response = new StaticRouteResponse(); - response.setId(result.getId()); - response.setVpcId(result.getVpcId()); + response.setId(result.getUuid()); + if (result.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + if (vpc != null) { + response.setVpcId(vpc.getUuid()); + } + } response.setCidr(result.getCidr()); - + StaticRoute.State state = result.getState(); String stateToSet = state.toString(); if (state.equals(FirewallRule.State.Revoke)) { @@ -4027,7 +3074,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setState(stateToSet); populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.StaticRoute, result.getId()); List tagResponses = new ArrayList(); @@ -4037,19 +3084,22 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setTags(tagResponses); response.setObjectName("staticroute"); - + return response; } - + @Override public Site2SiteVpnGatewayResponse createSite2SiteVpnGatewayResponse(Site2SiteVpnGateway result) { - Site2SiteVpnGatewayResponse response = new Site2SiteVpnGatewayResponse(); - response.setId(result.getId()); + Site2SiteVpnGatewayResponse response = new Site2SiteVpnGatewayResponse(); + response.setId(result.getUuid()); response.setIp(ApiDBUtils.findIpAddressById(result.getAddrId()).getAddress().toString()); - response.setVpcId(result.getVpcId()); + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + if (vpc != null) { + response.setVpcId(result.getUuid()); + } response.setRemoved(result.getRemoved()); response.setObjectName("vpngateway"); - + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); return response; @@ -4058,7 +3108,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result) { Site2SiteCustomerGatewayResponse response = new Site2SiteCustomerGatewayResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setName(result.getName()); response.setGatewayIp(result.getGatewayIp()); response.setGuestCidrList(result.getGuestCidrList()); @@ -4071,49 +3121,94 @@ public class ApiResponseHelper implements ResponseGenerator { response.setRemoved(result.getRemoved()); response.setObjectName("vpncustomergateway"); - + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + return response; } @Override public Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result) { Site2SiteVpnConnectionResponse response = new Site2SiteVpnConnectionResponse(); - response.setId(result.getId()); - - response.setVpnGatewayId(result.getVpnGatewayId()); + response.setId(result.getUuid()); + Long vpnGatewayId = result.getVpnGatewayId(); if(vpnGatewayId != null) { - Site2SiteVpnGatewayVO vpnGateway = ApiDBUtils.findVpnGatewayById(vpnGatewayId); - - long ipId = vpnGateway.getAddrId(); - IPAddressVO ipObj = ApiDBUtils.findIpAddressById(ipId); - response.setIp(ipObj.getAddress().addr()); + Site2SiteVpnGateway vpnGateway = ApiDBUtils.findVpnGatewayById(vpnGatewayId); + if (vpnGateway != null) { + response.setVpnGatewayId(vpnGateway.getUuid()); + long ipId = vpnGateway.getAddrId(); + IPAddressVO ipObj = ApiDBUtils.findIpAddressById(ipId); + response.setIp(ipObj.getAddress().addr()); + } } - - response.setCustomerGatewayId(result.getCustomerGatewayId()); + Long customerGatewayId = result.getCustomerGatewayId(); if(customerGatewayId != null) { - Site2SiteCustomerGatewayVO customerGateway = ApiDBUtils.findCustomerGatewayById(customerGatewayId); - response.setGatewayIp(customerGateway.getGatewayIp()); - response.setGuestCidrList(customerGateway.getGuestCidrList()); - response.setIpsecPsk(customerGateway.getIpsecPsk()); - response.setIkePolicy(customerGateway.getIkePolicy()); - response.setEspPolicy(customerGateway.getEspPolicy()); + Site2SiteCustomerGateway customerGateway = ApiDBUtils.findCustomerGatewayById(customerGatewayId); + if (customerGateway != null) { + response.setCustomerGatewayId(customerGateway.getUuid()); + response.setGatewayIp(customerGateway.getGatewayIp()); + response.setGuestCidrList(customerGateway.getGuestCidrList()); + response.setIpsecPsk(customerGateway.getIpsecPsk()); + response.setIkePolicy(customerGateway.getIkePolicy()); + response.setEspPolicy(customerGateway.getEspPolicy()); response.setIkeLifetime(customerGateway.getIkeLifetime()); response.setEspLifetime(customerGateway.getEspLifetime()); response.setDpd(customerGateway.getDpd()); - } - + } + } + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + response.setState(result.getState().toString()); response.setCreated(result.getCreated()); response.setRemoved(result.getRemoved()); response.setObjectName("vpnconnection"); return response; } + + + + @Override + public GuestOSResponse createGuestOSResponse(GuestOS guestOS) { + GuestOSResponse response = new GuestOSResponse(); + response.setDescription(guestOS.getDisplayName()); + response.setId(guestOS.getUuid()); + GuestOSCategoryVO category = ApiDBUtils.findGuestOsCategoryById(guestOS.getCategoryId()); + if ( category != null ){ + response.setOsCategoryId(category.getUuid()); + } + + response.setObjectName("ostype"); + return response; + } + + + + @Override + public SnapshotScheduleResponse createSnapshotScheduleResponse(SnapshotSchedule snapshotSchedule) { + SnapshotScheduleResponse response = new SnapshotScheduleResponse(); + response.setId(snapshotSchedule.getUuid()); + if (snapshotSchedule.getVolumeId() != null) { + Volume vol = ApiDBUtils.findVolumeById(snapshotSchedule.getVolumeId()); + if (vol != null) { + response.setVolumeId(vol.getUuid()); + } + } + if (snapshotSchedule.getPolicyId() != null) { + SnapshotPolicy policy = ApiDBUtils.findSnapshotPolicyById(snapshotSchedule.getPolicyId()); + if (policy != null) { + response.setSnapshotPolicyId(policy.getUuid()); + } + } + response.setScheduled(snapshotSchedule.getScheduledTimestamp()); + + response.setObjectName("snapshot"); + return response; + } + + } diff --git a/server/src/com/cloud/api/ApiSerializerHelper.java b/server/src/com/cloud/api/ApiSerializerHelper.java index e2e1547491d..735330d261c 100644 --- a/server/src/com/cloud/api/ApiSerializerHelper.java +++ b/server/src/com/cloud/api/ApiSerializerHelper.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.api; +import org.apache.cloudstack.api.ResponseObject; import org.apache.log4j.Logger; import com.google.gson.Gson; diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index f42025c1d23..e106f0322ad 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -17,16 +17,14 @@ package com.cloud.api; import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.SecureRandom; @@ -40,7 +38,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ExecutorService; @@ -53,13 +50,25 @@ import javax.crypto.spec.SecretKeySpec; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import com.cloud.utils.ReflectUtil; +import org.apache.cloudstack.acl.APIChecker; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.commons.codec.binary.Base64; +import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; @@ -81,9 +90,17 @@ import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.log4j.Logger; +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.ExceptionResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ExceptionResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -105,181 +122,69 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; import com.cloud.user.UserVO; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; -import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.component.Adapters; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.PluggableService; +import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CSExceptionErrorCode; -import com.cloud.uuididentity.dao.IdentityDao; - public class ApiServer implements HttpRequestHandler { private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); - public static final short ADMIN_COMMAND = 1; - public static final short DOMAIN_ADMIN_COMMAND = 4; - public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2; - public static final short USER_COMMAND = 8; public static boolean encodeApiResponse = false; public static String jsonContentType = "text/javascript"; - private Properties _apiCommands = null; private ApiDispatcher _dispatcher; - private AccountManager _accountMgr = null; - private DomainManager _domainMgr = null; - private AsyncJobManager _asyncMgr = null; + + @Inject private AccountManager _accountMgr = null; + @Inject private DomainManager _domainMgr = null; + @Inject private AsyncJobManager _asyncMgr = null; + + @Inject(adapter = APIChecker.class) + protected Adapters _apiAccessCheckers; + private Account _systemAccount = null; private User _systemUser = null; - private static int _workerCount = 0; - private static ApiServer s_instance = null; - private static List s_userCommands = null; - private static List s_resellerCommands = null; // AKA domain-admin - private static List s_adminCommands = null; - private static List s_resourceDomainAdminCommands = null; - private static List s_allCommands = null; - private static List s_pluggableServiceCommands = null; private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + private static Map> _apiNameCmdClassMap = new HashMap>(); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("ApiServer")); - static { - s_userCommands = new ArrayList(); - s_resellerCommands = new ArrayList(); - s_adminCommands = new ArrayList(); - s_resourceDomainAdminCommands = new ArrayList(); - s_allCommands = new ArrayList(); - s_pluggableServiceCommands = new ArrayList(); + protected ApiServer() { + super(); } - private ApiServer() { - } - - public static void initApiServer(String[] apiConfig) { + public static void initApiServer() { if (s_instance == null) { - s_instance = new ApiServer(); - s_instance.init(apiConfig); + //Injection will create ApiServer and all its fields which have @Inject + s_instance = ComponentLocator.inject(ApiServer.class); + s_instance.init(); } } public static ApiServer getInstance() { - // initApiServer(); + if (s_instance == null) { + ApiServer.initApiServer(); + } return s_instance; } - public Properties get_apiCommands() { - return _apiCommands; - } - - public static boolean isPluggableServiceCommand(String cmdClassName) { - if (s_pluggableServiceCommands != null) { - if (s_pluggableServiceCommands.contains(cmdClassName)) { - return true; - } - } - return false; - } - - private String[] getPluggableServicesApiConfigs() { - List pluggableServicesApiConfigs = new ArrayList(); - - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - List services = locator.getAllPluggableServices(); - for (PluggableService service : services) { - pluggableServicesApiConfigs.add(service.getPropertiesFile()); - } - return pluggableServicesApiConfigs.toArray(new String[0]); - } - - private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) { - try { - if (_apiCommands == null) { - _apiCommands = new Properties(); - } - Properties preProcessedCommands = new Properties(); - if (apiConfig != null) { - for (String configFile : apiConfig) { - File commandsFile = PropertiesUtil.findConfigFile(configFile); - if (commandsFile != null) { - try { - preProcessedCommands.load(new FileInputStream(commandsFile)); - } catch (FileNotFoundException fnfex) { - // in case of a file within a jar in classpath, try to open stream using url - InputStream stream = PropertiesUtil.openStreamFromURL(configFile); - if (stream != null) { - preProcessedCommands.load(stream); - } else { - s_logger.error("Unable to find properites file", fnfex); - } - } - } - } - for (Object key : preProcessedCommands.keySet()) { - String preProcessedCommand = preProcessedCommands.getProperty((String) key); - String[] commandParts = preProcessedCommand.split(";"); - _apiCommands.put(key, commandParts[0]); - - if (pluggableServicesConfig) { - s_pluggableServiceCommands.add(commandParts[0]); - } - - if (commandParts.length > 1) { - try { - short cmdPermissions = Short.parseShort(commandParts[1]); - if ((cmdPermissions & ADMIN_COMMAND) != 0) { - s_adminCommands.add((String) key); - } - if ((cmdPermissions & RESOURCE_DOMAIN_ADMIN_COMMAND) != 0) { - s_resourceDomainAdminCommands.add((String) key); - } - if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { - s_resellerCommands.add((String) key); - } - if ((cmdPermissions & USER_COMMAND) != 0) { - s_userCommands.add((String) key); - } - } catch (NumberFormatException nfe) { - s_logger.info("Malformed command.properties permissions value, key = " + key + ", value = " + preProcessedCommand); - } - } - } - - s_allCommands.addAll(s_adminCommands); - s_allCommands.addAll(s_resourceDomainAdminCommands); - s_allCommands.addAll(s_userCommands); - s_allCommands.addAll(s_resellerCommands); - } - } catch (FileNotFoundException fnfex) { - s_logger.error("Unable to find properites file", fnfex); - } catch (IOException ioex) { - s_logger.error("Exception loading properties file", ioex); - } - } - - public void init(String[] apiConfig) { + public void init() { BaseCmd.setComponents(new ApiResponseHelper()); BaseListCmd.configure(); - processConfigFiles(apiConfig, false); - // get commands for all pluggable services - String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs(); - processConfigFiles(pluggableServicesApiConfigs, true); - - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - _accountMgr = locator.getManager(AccountManager.class); - _asyncMgr = locator.getManager(AsyncJobManager.class); _systemAccount = _accountMgr.getSystemAccount(); _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); - _domainMgr = locator.getManager(DomainManager.class); Integer apiPort = null; // api port, null by default + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); SearchCriteria sc = configDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); @@ -291,8 +196,19 @@ public class ApiServer implements HttpRequestHandler { } } - encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); + Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, + new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); + for(Class cmdClass: cmdClasses) { + String apiName = cmdClass.getAnnotation(APICommand.class).name(); + if (_apiNameCmdClassMap.containsKey(apiName)) { + s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); + continue; + } + _apiNameCmdClassMap.put(apiName, cmdClass); + } + + encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); if (jsonType != null) { jsonContentType = jsonType; @@ -301,13 +217,17 @@ public class ApiServer implements HttpRequestHandler { if (apiPort != null) { ListenerThread listenerThread = new ListenerThread(this, apiPort); listenerThread.start(); - } + } } + // NOTE: handle() only handles over the wire (OTW) requests from integration.api.port 8096 + // If integration api port is not configured, actual OTW requests will be received by ApiServlet @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { - // get some information for the access log... + public void handle(HttpRequest request, HttpResponse response, HttpContext context) + throws HttpException, IOException { + + // Create StringBuffer to log information in access log StringBuffer sb = new StringBuffer(); HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection"); if (connObj instanceof SocketHttpServerConnection) { @@ -317,36 +237,32 @@ public class ApiServer implements HttpRequestHandler { sb.append(StringUtils.cleanString(request.getRequestLine().toString())); try { - String uri = request.getRequestLine().getUri(); - int requestParamsStartIndex = uri.indexOf('?'); - if (requestParamsStartIndex >= 0) { - uri = uri.substring(requestParamsStartIndex + 1); - } - - String[] paramArray = uri.split("&"); - if (paramArray.length < 1) { - s_logger.info("no parameters received for request: " + uri + ", aborting..."); - return; + List paramList = null; + try { + paramList = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), "UTF-8"); + } catch (URISyntaxException e) { + s_logger.error("Error parsing url request", e); } + // Use Multimap as the parameter map should be in the form (name=String, value=String[]) + // So parameter values are stored in a list for the same name key + // APITODO: Use Guava's (import com.google.common.collect.Multimap;) + // (Immutable)Multimap paramMultiMap = HashMultimap.create(); + // Map> parameterMap = paramMultiMap.asMap(); Map parameterMap = new HashMap(); - - String responseType = BaseCmd.RESPONSE_TYPE_XML; - for (String paramEntry : paramArray) { - String[] paramValue = paramEntry.split("="); - if (paramValue.length != 2) { - s_logger.info("malformed parameter: " + paramEntry + ", skipping"); + String responseType = BaseCmd.RESPONSE_TYPE_JSON; + for (NameValuePair param : paramList) { + if (param.getName().equalsIgnoreCase("response")) { + responseType = param.getValue(); continue; } - if ("response".equalsIgnoreCase(paramValue[0])) { - responseType = paramValue[1]; - } else { - // according to the servlet spec, the parameter map should be in the form (name=String, - // value=String[]), so - // parameter values will be stored in an array - parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); - } + parameterMap.put(param.getName(), new String[] { param.getValue() }); } + + // Check responseType, if not among valid types, fallback to JSON + if (!(responseType.equals(BaseCmd.RESPONSE_TYPE_JSON) || responseType.equals(BaseCmd.RESPONSE_TYPE_XML))) + responseType = BaseCmd.RESPONSE_TYPE_JSON; + try { // always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true); @@ -356,7 +272,7 @@ public class ApiServer implements HttpRequestHandler { writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null); } catch (ServerApiException se) { - String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); + String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription()); sb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (RuntimeException e) { @@ -414,9 +330,9 @@ public class ApiServer implements HttpRequestHandler { } paramMap.put(key, decodedValue); } - String cmdClassName = _apiCommands.getProperty(command[0]); - if (cmdClassName != null) { - Class cmdClass = Class.forName(cmdClassName); + + Class cmdClass = getCmdClass(command[0]); + if (cmdClass != null) { BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance(); cmdObj.setFullUrlParams(paramMap); cmdObj.setResponseType(responseType); @@ -435,14 +351,13 @@ public class ApiServer implements HttpRequestHandler { } catch (Exception ex) { if (ex instanceof InvalidParameterValueException) { InvalidParameterValueException ref = (InvalidParameterValueException)ex; - ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); + ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy obj = idList.get(i); - e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName()); + e.addProxyObject(idList.get(i)); } } // Also copy over the cserror code and the function/layer in which it was thrown. @@ -452,12 +367,11 @@ public class ApiServer implements HttpRequestHandler { PermissionDeniedException ref = (PermissionDeniedException)ex; ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy obj = idList.get(i); - e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName()); + e.addProxyObject(idList.get(i)); } } e.setCSErrorCode(ref.getCSErrorCode()); @@ -478,18 +392,22 @@ public class ApiServer implements HttpRequestHandler { UserContext ctx = UserContext.current(); Long callerUserId = ctx.getCallerUserId(); Account caller = ctx.getCaller(); + + // Queue command based on Cmd super class: + // BaseCmd: cmd is dispatched to ApiDispatcher, executed, serialized and returned. + // BaseAsyncCreateCmd: cmd params are processed and create() is called, then same workflow as BaseAsyncCmd. + // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned. if (cmdObj instanceof BaseAsyncCmd) { Long objectId = null; - String objectEntityTable = null; + String objectUuid = null; if (cmdObj instanceof BaseAsyncCreateCmd) { BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj; _dispatcher.dispatchCreateCmd(createCmd, params); objectId = createCmd.getEntityId(); - objectEntityTable = createCmd.getEntityTable(); + objectUuid = createCmd.getEntityUuid(); params.put("id", objectId.toString()); } else { - ApiDispatcher.setupParameters(cmdObj, params); - ApiDispatcher.plugService(cmdObj); + ApiDispatcher.processParameters(cmdObj, params); } BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj; @@ -505,7 +423,7 @@ public class ApiServer implements HttpRequestHandler { asyncCmd.setStartEventId(startEventId); // save the scheduled event - Long eventId = EventUtils.saveScheduledEvent((callerUserId == null) ? User.UID_SYSTEM : callerUserId, + Long eventId = EventUtils.saveScheduledEvent((callerUserId == null) ? User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), startEventId); if (startEventId == 0) { @@ -517,8 +435,8 @@ public class ApiServer implements HttpRequestHandler { ctx.setAccountId(asyncCmd.getEntityOwnerId()); - Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId; - AsyncJobVO job = new AsyncJobVO(callerUserId, caller.getId(), cmdObj.getClass().getName(), + Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId; + AsyncJobVO job = new AsyncJobVO(callerUserId, caller.getId(), cmdObj.getClass().getName(), ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType()); long jobId = _asyncMgr.submitAsyncJob(job); @@ -530,8 +448,8 @@ public class ApiServer implements HttpRequestHandler { } if (objectId != null) { - SerializationContext.current().setUuidTranslation(true); - return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objectId, objectEntityTable); + String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid; + return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objUuid); } SerializationContext.current().setUuidTranslation(true); @@ -541,7 +459,21 @@ public class ApiServer implements HttpRequestHandler { // if the command is of the listXXXCommand, we will need to also return the // the job id and status if possible - if (cmdObj instanceof BaseListCmd) { + // For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views. + if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd) + && !(cmdObj instanceof ListSecurityGroupsCmd) + && !(cmdObj instanceof ListTagsCmd) + && !(cmdObj instanceof ListEventsCmd) + && !(cmdObj instanceof ListVMGroupsCmd) + && !(cmdObj instanceof ListProjectsCmd) + && !(cmdObj instanceof ListProjectAccountsCmd) + && !(cmdObj instanceof ListProjectInvitationsCmd) + && !(cmdObj instanceof ListHostsCmd) + && !(cmdObj instanceof ListVolumesCmd) + && !(cmdObj instanceof ListUsersCmd) + && !(cmdObj instanceof ListAccountsCmd) + && !(cmdObj instanceof ListStoragePoolsCmd) + ) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } @@ -566,17 +498,22 @@ public class ApiServer implements HttpRequestHandler { return; } - // Using maps might possibly be more efficient if the set is large enough but for now, we'll just do a - // comparison of two lists. Either way, there shouldn't be too many async jobs active for the account. + Map objectJobMap = new HashMap(); for (AsyncJob job : jobs) { if (job.getInstanceId() == null) { continue; } - for (ResponseObject response : responses) { - if (response.getObjectId() != null && job.getInstanceId().longValue() == response.getObjectId().longValue()) { - response.setJobId(job.getId()); - response.setJobStatus(job.getStatus()); - } + String instanceUuid = ApiDBUtils.findJobInstanceUuid(job); + if (instanceUuid != null) { + objectJobMap.put(instanceUuid, job); + } + } + + for (ResponseObject response : responses) { + if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) { + AsyncJob job = objectJobMap.get(response.getObjectId()); + response.setJobId(job.getUuid()); + response.setJobStatus(job.getStatus()); } } } @@ -593,12 +530,6 @@ public class ApiServer implements HttpRequestHandler { auditTrailSb.append(StringUtils.cleanString(result)); } } - - private static boolean isCommandAvailable(String commandName) { - boolean isCommandAvailable = false; - isCommandAvailable = s_allCommands.contains(commandName); - return isCommandAvailable; - } public boolean verifyRequest(Map requestParameters, Long userId) throws ServerApiException { try { @@ -617,20 +548,20 @@ public class ApiServer implements HttpRequestHandler { // if userId not null, that mean that user is logged in if (userId != null) { - Long accountId = ApiDBUtils.findUserById(userId).getAccountId(); - Account userAccount = _accountMgr.getAccount(accountId); - short accountType = userAccount.getType(); - - if (!isCommandAvailable(accountType, commandName)) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); + User user = ApiDBUtils.findUserById(userId); + try{ + checkCommandAvailable(user, commandName); + } + catch (PermissionDeniedException ex){ + s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } return true; } else { // check against every available command to see if the command exists or not - if (!isCommandAvailable(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); + if (!_apiNameCmdClassMap.containsKey(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { + s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } } @@ -673,30 +604,29 @@ public class ApiServer implements HttpRequestHandler { // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { - if (s_logger.isDebugEnabled()) { - s_logger.info("expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); - } + s_logger.debug("Expired session, missing signature, or missing apiKey -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey); return false; // no signature, bad request } Date expiresTS = null; + // FIXME: Hard coded signature, why not have an enum if ("3".equals(signatureVersion)) { // New signature authentication. Check for expire parameter and its validity if (expires == null) { - s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); + s_logger.debug("Missing Expires parameter -- ignoring request. Signature: " + signature + ", apiKey: " + apiKey); return false; } synchronized (_dateFormat) { try { expiresTS = _dateFormat.parse(expires); } catch (ParseException pe) { - s_logger.info("Incorrect date format for Expires parameter", pe); + s_logger.debug("Incorrect date format for Expires parameter", pe); return false; } } Date now = new Date(System.currentTimeMillis()); if (expiresTS.before(now)) { - s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); + s_logger.debug("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); return false; } } @@ -707,7 +637,7 @@ public class ApiServer implements HttpRequestHandler { // verify there is a user with this api key Pair userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { - s_logger.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); + s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } @@ -722,9 +652,12 @@ public class ApiServer implements HttpRequestHandler { UserContext.updateContext(user.getId(), account, null); - if (!isCommandAvailable(account.getType(), commandName)) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist"); + try{ + checkCommandAvailable(user, commandName); + } + catch (PermissionDeniedException ex){ + s_logger.debug("The given command:" + commandName + " does not exist or it is not available for user"); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user with id:" + userId); } // verify secret key exists @@ -751,20 +684,13 @@ public class ApiServer implements HttpRequestHandler { if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) { throw (ServerApiException) ex; } - s_logger.error("unable to verifty request signature", ex); + s_logger.error("unable to verify request signature", ex); } return false; } - - public Long fetchDomainId(String domainUUID){ - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - IdentityDao identityDao = locator.getDao(IdentityDao.class); - try{ - Long domainId = identityDao.getIdentityId("domain", domainUUID); - return domainId; - }catch(InvalidParameterValueException ex){ - return null; - } + + public Long fetchDomainId(String domainUUID) { + return _domainMgr.getDomain(domainUUID).getId(); } public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath, String loginIpAddress ,Map requestParameters) throws CloudAuthenticationException { @@ -806,19 +732,19 @@ public class ApiServer implements HttpRequestHandler { if(user.getUuid() != null){ session.setAttribute("user_UUID", user.getUuid()); } - + session.setAttribute("username", userAcct.getUsername()); session.setAttribute("firstname", userAcct.getFirstname()); session.setAttribute("lastname", userAcct.getLastname()); session.setAttribute("accountobj", account); session.setAttribute("account", account.getAccountName()); - + session.setAttribute("domainid", account.getDomainId()); DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId()); if(domain.getUuid() != null){ session.setAttribute("domain_UUID", domain.getUuid()); } - + session.setAttribute("type", Short.valueOf(account.getType()).toString()); session.setAttribute("registrationtoken", userAcct.getRegistrationToken()); session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString()); @@ -860,23 +786,18 @@ public class ApiServer implements HttpRequestHandler { return true; } - public static boolean isCommandAvailable(short accountType, String commandName) { - boolean isCommandAvailable = false; - switch (accountType) { - case Account.ACCOUNT_TYPE_ADMIN: - isCommandAvailable = s_adminCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: - isCommandAvailable = s_resellerCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: - isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_NORMAL: - isCommandAvailable = s_userCommands.contains(commandName); - break; + private void checkCommandAvailable(User user, String commandName) throws PermissionDeniedException { + if (user == null) { + throw new PermissionDeniedException("User is null for role based API access check for command" + commandName); } - return isCommandAvailable; + + for (APIChecker apiChecker : _apiAccessCheckers) { + apiChecker.checkAccess(user, commandName); + } + } + + private Class getCmdClass(String cmdName) { + return _apiNameCmdClassMap.get(cmdName); } // FIXME: rather than isError, we might was to pass in the status code to give more flexibility @@ -1012,8 +933,7 @@ public class ApiServer implements HttpRequestHandler { public String getSerializedApiError(int errorCode, String errorText, Map apiCommandParams, String responseType, Exception ex) { String responseName = null; - String cmdClassName = null; - + Class cmdClass = null; String responseText = null; try { @@ -1024,10 +944,9 @@ public class ApiServer implements HttpRequestHandler { // cmd name can be null when "command" parameter is missing in the request if (cmdObj != null) { String cmdName = ((String[]) cmdObj)[0]; - cmdClassName = _apiCommands.getProperty(cmdName); - if (cmdClassName != null) { - Class claz = Class.forName(cmdClassName); - responseName = ((BaseCmd) claz.newInstance()).getCommandName(); + cmdClass = getCmdClass(cmdName); + if (cmdClass != null) { + responseName = ((BaseCmd) cmdClass.newInstance()).getCommandName(); } else { responseName = "errorresponse"; } @@ -1048,34 +967,31 @@ public class ApiServer implements HttpRequestHandler { // Cast the exception appropriately and retrieve the IdentityProxy if (ex instanceof ServerApiException) { ServerApiException ref = (ServerApiException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - } + apiResponse.addProxyObject(idList.get(i)); + } } // Also copy over the cserror code and the function/layer in which it was thrown. apiResponse.setCSErrorCode(ref.getCSErrorCode()); } else if (ex instanceof PermissionDeniedException) { PermissionDeniedException ref = (PermissionDeniedException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - } + apiResponse.addProxyObject(idList.get(i)); + } } // Also copy over the cserror code and the function/layer in which it was thrown. apiResponse.setCSErrorCode(ref.getCSErrorCode()); } else if (ex instanceof InvalidParameterValueException) { InvalidParameterValueException ref = (InvalidParameterValueException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - } + apiResponse.addProxyObject(idList.get(i)); + } } // Also copy over the cserror code and the function/layer in which it was thrown. apiResponse.setCSErrorCode(ref.getCSErrorCode()); @@ -1086,7 +1002,7 @@ public class ApiServer implements HttpRequestHandler { responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType); } catch (Exception e) { - s_logger.error("Exception responding to http request", e); + s_logger.error("Exception responding to http request", e); } return responseText; } diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index 091bf189cc2..19091f25ff2 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -28,6 +28,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ServerApiException; import org.apache.log4j.Logger; import com.cloud.cluster.StackMaid; @@ -85,8 +87,8 @@ public class ApiServlet extends HttpServlet { for (String param : paramsInQueryString) { String[] paramTokens = param.split("="); if (paramTokens != null && paramTokens.length == 2) { - String name = param.split("=")[0]; - String value = param.split("=")[1]; + String name = paramTokens[0]; + String value = paramTokens[1]; try { name = URLDecoder.decode(name, "UTF-8"); @@ -98,7 +100,7 @@ public class ApiServlet extends HttpServlet { } params.put(name, new String[] { value }); } else { - s_logger.debug("Invalid paramemter in URL found. param: " + param); + s_logger.debug("Invalid parameter in URL found. param: " + param); } } } @@ -114,13 +116,10 @@ public class ApiServlet extends HttpServlet { Map params = new HashMap(); params.putAll(req.getParameterMap()); - // // For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries // to unwrap URL encoded content from ISO-9959-1. - // - // After failed in using setCharacterEncoding() to control it, end up with following hacking : for all GET requests, - // we will override it with our-own way of UTF-8 based URL decoding. - // + // After failed in using setCharacterEncoding() to control it, end up with following hacking: + // for all GET requests, we will override it with our-own way of UTF-8 based URL decoding. utf8Fixup(req, params); // logging the request start and end in management log for easy debugging @@ -264,7 +263,8 @@ public class ApiServlet extends HttpServlet { } // Do a sanity check here to make sure the user hasn't already been deleted - if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { + if ((userId != null) && (account != null) + && (accountObj != null) && _apiServer.verifyUser(userId)) { String[] command = (String[]) params.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); @@ -275,9 +275,8 @@ public class ApiServlet extends HttpServlet { } UserContext.updateContext(userId, (Account) accountObj, session.getId()); } else { - // Invalidate the session to ensure we won't allow a request across management server restarts if the userId - // was serialized to the - // stored session + // Invalidate the session to ensure we won't allow a request across management server + // restarts if the userId was serialized to the stored session try { session.invalidate(); } catch (IllegalStateException ise) { @@ -388,12 +387,11 @@ public class ApiServlet extends HttpServlet { StringBuffer sb = new StringBuffer(); int inactiveInterval = session.getMaxInactiveInterval(); - String user_UUID = (String)session.getAttribute("user_UUID"); - session.removeAttribute("user_UUID"); + String user_UUID = (String)session.getAttribute("user_UUID"); + session.removeAttribute("user_UUID"); - String domain_UUID = (String)session.getAttribute("domain_UUID"); - session.removeAttribute("domain_UUID"); - + String domain_UUID = (String)session.getAttribute("domain_UUID"); + session.removeAttribute("domain_UUID"); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { sb.append("{ \"loginresponse\" : { "); @@ -414,10 +412,13 @@ public class ApiServlet extends HttpServlet { } } } - sb.append(" } }"); + sb.append(" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); } else { sb.append(""); - sb.append(""); + sb.append(""); sb.append("" + inactiveInterval + ""); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { @@ -444,10 +445,13 @@ public class ApiServlet extends HttpServlet { private String getLogoutSuccessResponse(String responseType) { StringBuffer sb = new StringBuffer(); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { - sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }"); + sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); } else { sb.append(""); - sb.append(""); + sb.append(""); sb.append("success"); sb.append(""); } diff --git a/server/src/com/cloud/api/IdentityTypeAdapter.java b/server/src/com/cloud/api/IdentityTypeAdapter.java deleted file mode 100644 index 0e91a4ee444..00000000000 --- a/server/src/com/cloud/api/IdentityTypeAdapter.java +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api; - -import java.lang.reflect.Type; -import java.util.ArrayList; - -import com.cloud.uuididentity.dao.IdentityDao; -import com.cloud.uuididentity.dao.IdentityDaoImpl; -import com.google.gson.Gson; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.cloud.utils.IdentityProxy; - - -public class IdentityTypeAdapter implements JsonSerializer, JsonDeserializer { - - @Override - public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) { - if(SerializationContext.current().getUuidTranslation()) { - assert(src != null); - if(src.getValue() == null) - return context.serialize(null); - - IdentityDao identityDao = new IdentityDaoImpl(); - if(src.getTableName() != null) { - String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue())); - if(uuid == null) - return context.serialize(null); - - // Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not - // null, prepare a structure of uuid and idFieldName and return the json representation of that. - String idName = src.getidFieldName(); - if (idName != null) { - // Prepare a structure. - JsonObject jsonObj = new JsonObject(); - jsonObj.add("uuid", new JsonPrimitive(uuid)); - jsonObj.add("uuidProperty", new JsonPrimitive(idName)); - return jsonObj; - } - return new JsonPrimitive(uuid); - } else { - return new JsonPrimitive(String.valueOf(src.getValue())); - } - } else { - return new Gson().toJsonTree(src); - } - } - - @Override - public IdentityProxy deserialize(JsonElement src, Type srcType, - JsonDeserializationContext context) throws JsonParseException { - - IdentityProxy obj = new IdentityProxy(); - JsonObject json = src.getAsJsonObject(); - obj.setTableName(json.get("_tableName").getAsString()); - if(json.get("_value") != null) - obj.setValue(json.get("_value").getAsLong()); - return obj; - } -} diff --git a/server/src/com/cloud/api/ResponseObjectTypeAdapter.java b/server/src/com/cloud/api/ResponseObjectTypeAdapter.java index 9c768dc9de6..b49792334f4 100644 --- a/server/src/com/cloud/api/ResponseObjectTypeAdapter.java +++ b/server/src/com/cloud/api/ResponseObjectTypeAdapter.java @@ -19,10 +19,11 @@ package com.cloud.api; import java.lang.reflect.Method; import java.lang.reflect.Type; +import org.apache.cloudstack.api.ResponseObject; import org.apache.log4j.Logger; -import com.cloud.api.response.ExceptionResponse; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ExceptionResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; diff --git a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java deleted file mode 100644 index 6edd2ab2aec..00000000000 --- a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java +++ /dev/null @@ -1,95 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="Adds a network device of one of the following types: ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer", responseObject = NetworkDeviceResponse.class) -public class AddNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddNetworkDeviceCmd.class); - private static final String s_name = "addnetworkdeviceresponse"; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") - private String type; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") - private Map paramList; - - - public String getDeviceType() { - return type; - } - - public Map getParamList() { - return paramList; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - Host device = nwDeviceMgr.addNetworkDevice(this); - NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(device); - response.setObjectName("networkdevice"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } - -} diff --git a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java index f253b378bc1..fdbbbe4ca3c 100644 --- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java @@ -16,25 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; -import com.cloud.server.api.response.ExternalFirewallResponse; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "addTrafficMonitor", description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class) public class AddTrafficMonitorCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName()); private static final String s_name = "addtrafficmonitorresponse"; @@ -43,10 +39,9 @@ public class AddTrafficMonitorCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; - @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host") private String url; @@ -96,8 +91,8 @@ public class AddTrafficMonitorCmd extends BaseCmd { try { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class); - Host trafficMoinitor = networkUsageMgr.addTrafficMonitor(this); - TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMoinitor); + Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this); + TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor); response.setObjectName("trafficmonitor"); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java deleted file mode 100644 index 7d07a3b0901..00000000000 --- a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java +++ /dev/null @@ -1,90 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="Deletes network device.", responseObject=SuccessResponse.class) -public class DeleteNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkDeviceCmd.class); - private static final String s_name = "deletenetworkdeviceresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="host") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required=true, description = "Id of network device to delete") - private Long id; - - - public Long getId() { - return id; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - boolean result = nwDeviceMgr.deleteNetworkDevice(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network device:" + getId()); - } - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } - -} diff --git a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java index 1a4d1ab825d..4c7d3a70546 100644 --- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java @@ -16,22 +16,22 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteTrafficMonitor", description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class) public class DeleteTrafficMonitorCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); private static final String s_name = "deletetrafficmonitorresponse"; @@ -40,8 +40,8 @@ public class DeleteTrafficMonitorCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the Traffic Monitor Host.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the Traffic Monitor Host.") private Long id; /////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java index b285775313c..aa3c082ce81 100644 --- a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java @@ -18,19 +18,16 @@ package com.cloud.api.commands; import java.util.Date; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.server.ManagementServerExt; import com.cloud.user.Account; -@Implementation(description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) +@APICommand(name = "generateUsageRecords", description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) public class GenerateUsageRecordsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GenerateUsageRecordsCmd.class.getName()); @@ -40,8 +37,8 @@ public class GenerateUsageRecordsCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List events for the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="List events for the specified domain.") private Long domainId; @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") diff --git a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java index 4edcb25760d..60afbd0a8f4 100644 --- a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java @@ -23,25 +23,32 @@ import java.util.Date; import java.util.List; import java.util.TimeZone; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; +import com.cloud.dc.DataCenter; +import com.cloud.domain.Domain; + +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.projects.Project; import com.cloud.server.ManagementServerExt; -import com.cloud.server.api.response.UsageRecordResponse; +import org.apache.cloudstack.api.response.UsageRecordResponse; +import com.cloud.storage.VMTemplateVO; import com.cloud.usage.UsageTypes; import com.cloud.usage.UsageVO; import com.cloud.user.Account; import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDaoImpl; +import com.cloud.vm.VMInstanceVO; -@Implementation(description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) +@APICommand(name = "listUsageRecords", description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) public class GetUsageRecordsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName()); @@ -54,8 +61,8 @@ public class GetUsageRecordsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List usage records for the specified user.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List usage records for the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="List usage records for the specified domain.") private Long domainId; @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") @@ -63,15 +70,15 @@ public class GetUsageRecordsCmd extends BaseListCmd { @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") private Date startDate; - - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, description="List usage records for the specified account") + + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + description="List usage records for the specified account") private Long accountId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="List usage records for specified project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="List usage records for specified project") private Long projectId; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.LONG, description="List usage records for the specified usage type") private Long usageType; @@ -94,7 +101,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { public Date getStartDate() { return startDate; } - + public Long getAccountId() { return accountId; } @@ -102,11 +109,11 @@ public class GetUsageRecordsCmd extends BaseListCmd { public Long getUsageType() { return usageType; } - + public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// Misc parameters /////////////////// ///////////////////////////////////////////////////// @@ -162,7 +169,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { } else { sb.append(hour+":"); } - + int minute = cal.get(Calendar.MINUTE); if (minute < 10) { sb.append("0" + minute + ":"); @@ -213,7 +220,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { return sb.toString(); } - + @Override public void execute(){ ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; @@ -225,28 +232,46 @@ public class GetUsageRecordsCmd extends BaseListCmd { UsageRecordResponse usageRecResponse = new UsageRecordResponse(); if (usageRecordGeneric instanceof UsageVO) { UsageVO usageRecord = (UsageVO)usageRecordGeneric; - - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId()); + + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { //find the project Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - usageRecResponse.setProjectId(project.getId()); + usageRecResponse.setProjectId(project.getUuid()); usageRecResponse.setProjectName(project.getName()); } else { - usageRecResponse.setAccountId(account.getId()); + usageRecResponse.setAccountId(account.getUuid()); usageRecResponse.setAccountName(account.getAccountName()); } - - usageRecResponse.setDomainId(usageRecord.getDomainId()); - - usageRecResponse.setZoneId(usageRecord.getZoneId()); + + Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId()); + if (domain != null) { + usageRecResponse.setDomainId(domain.getUuid()); + } + + if (usageRecord.getZoneId() != null) { + DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId()); + if (zone != null) { + usageRecResponse.setZoneId(zone.getUuid()); + } + } usageRecResponse.setDescription(usageRecord.getDescription()); usageRecResponse.setUsage(usageRecord.getUsageDisplay()); usageRecResponse.setUsageType(usageRecord.getUsageType()); - usageRecResponse.setVirtualMachineId(usageRecord.getVmInstanceId()); + if (usageRecord.getVmInstanceId() != null) { + VMInstanceVO vm = ApiDBUtils.findVMInstanceById(usageRecord.getVmInstanceId()); + if (vm != null) { + usageRecResponse.setVirtualMachineId(vm.getUuid()); + } + } usageRecResponse.setVmName(usageRecord.getVmName()); - usageRecResponse.setTemplateId(usageRecord.getTemplateId()); - + if (usageRecord.getTemplateId() != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId()); + if (template != null) { + usageRecResponse.setTemplateId(template.getUuid()); + } + } + if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){ //Service Offering Id usageRecResponse.setOfferingId(identityDao.getIdentityUuid("disk_offering", usageRecord.getOfferingId().toString())); @@ -254,7 +279,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString())); //Hypervisor Type usageRecResponse.setType(usageRecord.getType()); - + } else if(usageRecord.getUsageType() == UsageTypes.IP_ADDRESS){ //isSourceNAT usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat"))?true:false); @@ -262,7 +287,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false); //IP Address ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("user_ip_address", usageRecord.getUsageId().toString())); - + } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){ //Device Type usageRecResponse.setType(usageRecord.getType()); @@ -271,11 +296,11 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString())); } else { //External Device Host Id - usageRecResponse.setUsageId(identityDao.getIdentityUuid("host", usageRecord.getUsageId().toString())); + usageRecResponse.setUsageId(identityDao.getIdentityUuid("host", usageRecord.getUsageId().toString())); } //Network ID usageRecResponse.setNetworkId(identityDao.getIdentityUuid("networks", usageRecord.getNetworkId().toString())); - + } else if(usageRecord.getUsageType() == UsageTypes.VOLUME){ //Volume ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("volumes", usageRecord.getUsageId().toString())); @@ -291,36 +316,36 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_template", usageRecord.getUsageId().toString())); //Template/ISO Size usageRecResponse.setSize(usageRecord.getSize()); - + } else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){ //Snapshot ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("snapshots", usageRecord.getUsageId().toString())); //Snapshot Size usageRecResponse.setSize(usageRecord.getSize()); - + } else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){ //Load Balancer Policy ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){ //Port Forwarding Rule ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){ //Network Offering Id usageRecResponse.setOfferingId(identityDao.getIdentityUuid("network_offerings", usageRecord.getOfferingId().toString())); //is Default usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false); - + } else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){ //VPN User ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){ //Security Group Id usageRecResponse.setUsageId(identityDao.getIdentityUuid("security_group", usageRecord.getUsageId().toString())); } - + if (usageRecord.getRawUsage() != null) { DecimalFormat decimalFormat = new DecimalFormat("###########.######"); usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage())); @@ -332,7 +357,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { if (usageRecord.getEndDate() != null) { usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate())); } - } + } usageRecResponse.setObjectName("usagerecord"); usageResponses.add(usageRecResponse); diff --git a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java deleted file mode 100644 index fc583c15f7b..00000000000 --- a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java +++ /dev/null @@ -1,99 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.api.commands; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="List network devices", responseObject = NetworkDeviceResponse.class) -public class ListNetworkDeviceCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkDeviceCmd.class); - private static final String s_name = "listnetworkdevice"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") - private String type; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") - private Map paramList; - - public String getDeviceType() { - return type; - } - - public Map getParamList() { - return paramList; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - List devices = nwDeviceMgr.listNetworkDevice(this); - List nwdeviceResponses = new ArrayList(); - ListResponse listResponse = new ListResponse(); - for (Host d : devices) { - NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(d); - response.setObjectName("networkdevice"); - response.setResponseName(getCommandName()); - nwdeviceResponses.add(response); - } - - listResponse.setResponses(nwdeviceResponses); - listResponse.setResponseName(getCommandName()); - this.setResponseObject(listResponse); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java index 78338d86710..21ad339137a 100644 --- a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java +++ b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java @@ -19,22 +19,22 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.host.Host; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; -import com.cloud.server.api.response.ExternalFirewallResponse; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List traffic monitor Hosts.", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class) public class ListTrafficMonitorsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); private static final String s_name = "listtrafficmonitorsresponse"; @@ -43,11 +43,10 @@ public class ListTrafficMonitorsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="zone Id") private long zoneId; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java b/server/src/com/cloud/api/commands/ListUsageTypesCmd.java index b60807c24a8..dfa5dc1bb20 100644 --- a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java +++ b/server/src/com/cloud/api/commands/ListUsageTypesCmd.java @@ -18,16 +18,16 @@ package com.cloud.api.commands; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.server.ManagementServerExt; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.user.Account; -@Implementation(description = "List Usage Types", responseObject = UsageTypeResponse.class) +@APICommand(name = "listUsageTypes", description = "List Usage Types", responseObject = UsageTypeResponse.class) public class ListUsageTypesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListUsageTypesCmd.class.getName()); private static final String s_name = "listusagetypesresponse"; diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java index ffdd5be237b..84851c389ad 100644 --- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java @@ -24,48 +24,36 @@ import java.io.FileWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.TreeMap; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import com.cloud.utils.ReflectUtil; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; import com.cloud.alert.AlertManager; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.BaseResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.serializer.Param; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; import com.google.gson.annotations.SerializedName; import com.thoughtworks.xstream.XStream; +import org.reflections.Reflections; public class ApiXmlDocWriter { public static final Logger s_logger = Logger.getLogger(ApiXmlDocWriter.class.getName()); private static final short DOMAIN_ADMIN_COMMAND = 4; private static final short USER_COMMAND = 8; + private static Map> _apiNameCmdClassMap = new HashMap>(); private static LinkedHashMap all_api_commands = new LinkedHashMap(); private static LinkedHashMap domain_admin_api_commands = new LinkedHashMap(); private static LinkedHashMap regular_user_api_commands = new LinkedHashMap(); @@ -92,6 +80,18 @@ public class ApiXmlDocWriter { } public static void main(String[] args) { + + Set> cmdClasses = ReflectUtil.getClassesWithAnnotation(APICommand.class, new String[]{"org.apache.cloudstack.api", "com.cloud.api"}); + + for(Class cmdClass: cmdClasses) { + String apiName = cmdClass.getAnnotation(APICommand.class).name(); + if (_apiNameCmdClassMap.containsKey(apiName)) { + System.out.println("Warning, API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); + continue; + } + _apiNameCmdClassMap.put(apiName, cmdClass); + } + LinkedProperties preProcessedCommands = new LinkedProperties(); String[] fileNames = null; @@ -131,13 +131,19 @@ public class ApiXmlDocWriter { while (propertiesIterator.hasNext()) { String key = (String) propertiesIterator.next(); String preProcessedCommand = preProcessedCommands.getProperty(key); - String[] commandParts = preProcessedCommand.split(";"); - String commandName = commandParts[0]; + int splitIndex = preProcessedCommand.lastIndexOf(";"); + String commandRoleMask = preProcessedCommand.substring(splitIndex + 1); + Class cmdClass = _apiNameCmdClassMap.get(key); + if (cmdClass == null) { + System.out.println("Check, Null Value for key: " + key + " preProcessedCommand=" + preProcessedCommand); + continue; + } + String commandName = cmdClass.getName(); all_api_commands.put(key, commandName); short cmdPermissions = 1; - if (commandParts.length > 1 && commandParts[1] != null) { - cmdPermissions = Short.parseShort(commandParts[1]); + if (commandRoleMask != null) { + cmdPermissions = Short.parseShort(commandRoleMask); } if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { @@ -309,14 +315,14 @@ public class ApiXmlDocWriter { Command apiCommand = new Command(); apiCommand.setName(command); - Implementation impl = clas.getAnnotation(Implementation.class); + APICommand impl = clas.getAnnotation(APICommand.class); if (impl == null) { - impl = clas.getSuperclass().getAnnotation(Implementation.class); + impl = clas.getSuperclass().getAnnotation(APICommand.class); } if (impl == null) { throw new IllegalStateException(String.format("An %1$s annotation is required for class %2$s.", - Implementation.class.getCanonicalName(), clas.getCanonicalName())); + APICommand.class.getCanonicalName(), clas.getCanonicalName())); } if (impl.includeInApiDoc()) { @@ -337,33 +343,15 @@ public class ApiXmlDocWriter { if(!impl.since().isEmpty()){ apiCommand.setSinceVersion(impl.since()); } - - // Set request parameters - Field[] fields = clas.getDeclaredFields(); - // Get fields from superclass - Class superClass = clas.getSuperclass(); - boolean isAsync = false; - while (superClass != null && superClass != Object.class) { - String superName = superClass.getName(); - if (!superName.equals(BaseCmd.class.getName()) && !superName.equals(BaseAsyncCmd.class.getName()) && !superName.equals(BaseAsyncCreateCmd.class.getName())) { - Field[] superClassFields = superClass.getDeclaredFields(); - if (superClassFields != null) { - Field[] tmpFields = new Field[fields.length + superClassFields.length]; - System.arraycopy(fields, 0, tmpFields, 0, fields.length); - System.arraycopy(superClassFields, 0, tmpFields, fields.length, superClassFields.length); - fields = tmpFields; - } - } - superClass = superClass.getSuperclass(); - // Set Async information for the command - if (superName.equals(BaseAsyncCmd.class.getName()) || superName.equals(BaseAsyncCreateCmd.class.getName())) { - isAsync = true; - } - } - + boolean isAsync = ReflectUtil.isCmdClassAsync(clas, + new Class[] {BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + apiCommand.setAsync(isAsync); - + + Field[] fields = ReflectUtil.getAllFieldsForClass(clas, + new Class[] {BaseCmd.class, BaseAsyncCmd.class, BaseAsyncCreateCmd.class}); + request = setRequestFields(fields); // Get response parameters diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java new file mode 100644 index 00000000000..b61f10a1ade --- /dev/null +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -0,0 +1,1892 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.query.QueryService; +import org.apache.log4j.Logger; + +import com.cloud.api.query.dao.AccountJoinDao; +import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.HostJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.StoragePoolJoinDao; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.dao.VolumeJoinDao; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.domain.Domain; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.event.dao.EventJoinDao; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.ha.HighAvailabilityManager; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.network.security.dao.SecurityGroupVMMapDao; +import com.cloud.projects.ProjectInvitation; +import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.projects.Project; +import com.cloud.projects.ProjectManager; +import com.cloud.projects.dao.ProjectAccountDao; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.server.Criteria; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolVO; +import com.cloud.storage.Volume; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountVO; +import com.cloud.user.UserContext; +import com.cloud.user.dao.AccountDao; +import com.cloud.utils.DateUtil; +import com.cloud.utils.Pair; +import com.cloud.utils.Ternary; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.UserVmDao; + +/** + * @author minc + * + */ +@Local(value = {QueryService.class }) +public class QueryManagerImpl implements QueryService, Manager { + + public static final Logger s_logger = Logger.getLogger(QueryManagerImpl.class); + + private String _name; + + // public static ViewResponseHelper _responseGenerator; + + @Inject + private AccountManager _accountMgr; + + @Inject + private ProjectManager _projectMgr; + + @Inject + private DomainDao _domainDao; + + @Inject + private UserAccountJoinDao _userAccountJoinDao; + + @Inject + private EventJoinDao _eventJoinDao; + + @Inject + private ResourceTagJoinDao _resourceTagJoinDao; + + @Inject + private InstanceGroupJoinDao _vmGroupJoinDao; + + @Inject + private UserVmJoinDao _userVmJoinDao; + + @Inject + private UserVmDao _userVmDao; + + @Inject + private SecurityGroupJoinDao _securityGroupJoinDao; + + @Inject + private SecurityGroupVMMapDao _securityGroupVMMapDao; + + @Inject + private DomainRouterJoinDao _routerJoinDao; + + @Inject + private ProjectInvitationJoinDao _projectInvitationJoinDao; + + @Inject + private ProjectJoinDao _projectJoinDao; + + @Inject + private ProjectDao _projectDao; + + @Inject + private ProjectAccountDao _projectAccountDao; + + @Inject + private ProjectAccountJoinDao _projectAccountJoinDao; + + @Inject + private HostJoinDao _hostJoinDao; + + @Inject + private VolumeJoinDao _volumeJoinDao; + + @Inject + private AccountDao _accountDao; + + @Inject + private AccountJoinDao _accountJoinDao; + + @Inject + private AsyncJobJoinDao _jobJoinDao; + + @Inject + private StoragePoolJoinDao _poolJoinDao; + + @Inject + private HighAvailabilityManager _haMgr; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + // _responseGenerator = new ViewResponseHelper(); + return false; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + /* (non-Javadoc) + * @see com.cloud.api.query.QueryService#searchForUsers(org.apache.cloudstack.api.command.admin.user.ListUsersCmd) + */ + @Override + public ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { + Pair, Integer> result = searchForUsersInternal(cmd); + ListResponse response = new ListResponse(); + List userResponses = ViewResponseHelper.createUserResponse(result.first().toArray(new UserAccountJoinVO[result.first().size()])); + response.setResponses(userResponses, result.second()); + return response; + } + + private Pair, Integer> searchForUsersInternal(ListUsersCmd cmd) throws PermissionDeniedException { + Account caller = UserContext.current().getCaller(); + + //TODO: Integrate with ACL checkAccess refactoring + Long domainId = cmd.getDomainId(); + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + } + + _accountMgr.checkAccess(caller, domain); + } else { + // default domainId to the caller's domain + domainId = caller.getDomainId(); + } + + Filter searchFilter = new Filter(UserAccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + Long id = cmd.getId(); + Object username = cmd.getUsername(); + Object type = cmd.getAccountType(); + Object accountName = cmd.getAccountName(); + Object state = cmd.getState(); + Object keyword = cmd.getKeyword(); + + SearchBuilder sb = _userAccountJoinDao.createSearchBuilder(); + sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE); + if (id != null && id == 1) { + // system user should NOT be searchable + List emptyList = new ArrayList(); + return new Pair, Integer>(emptyList, 0); + } else if (id != null) { + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + } else { + // this condition is used to exclude system user from the search results + sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ); + } + + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + + if ((accountName == null) && (domainId != null)) { + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + SearchCriteria sc = sb.create(); + if (keyword != null) { + SearchCriteria ssc = _userAccountJoinDao.createSearchCriteria(); + ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("username", SearchCriteria.Op.SC, ssc); + } + + if (username != null) { + sc.setParameters("username", username); + } + + if (id != null) { + sc.setParameters("id", id); + } else { + // Don't return system user, search builder with NEQ + sc.setParameters("id", 1); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + if (domainId != null) { + sc.setParameters("domainId", domainId); + } + } else if (domainId != null) { + DomainVO domainVO = _domainDao.findById(domainId); + sc.setParameters("domainPath", domainVO.getPath() + "%"); + } + + if (state != null) { + sc.setParameters("state", state); + } + + return _userAccountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForEvents(ListEventsCmd cmd) { + Pair, Integer> result = searchForEventsInternal(cmd); + ListResponse response = new ListResponse(); + List eventResponses = ViewResponseHelper.createEventResponse(result.first().toArray(new EventJoinVO[result.first().size()])); + response.setResponses(eventResponses, result.second()); + return response; + } + + private Pair, Integer> searchForEventsInternal(ListEventsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Long id = cmd.getId(); + String type = cmd.getType(); + String level = cmd.getLevel(); + Date startDate = cmd.getStartDate(); + Date endDate = cmd.getEndDate(); + String keyword = cmd.getKeyword(); + Integer entryTime = cmd.getEntryTime(); + Integer duration = cmd.getDuration(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _eventJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); + sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); + sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ); + sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); + sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); + + SearchCriteria sc = sb.create(); + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (id != null) { + sc.setParameters("id", id); + } + + if (keyword != null) { + SearchCriteria ssc = _eventJoinDao.createSearchCriteria(); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("level", SearchCriteria.Op.SC, ssc); + } + + if (level != null) { + sc.setParameters("levelEQ", level); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (startDate != null && endDate != null) { + sc.setParameters("createDateB", startDate, endDate); + } else if (startDate != null) { + sc.setParameters("createDateG", startDate); + } else if (endDate != null) { + sc.setParameters("createDateL", endDate); + } + + Pair, Integer> eventPair = null; + // event_view will not have duplicate rows for each event, so searchAndCount should be good enough. + if ((entryTime != null) && (duration != null)) { + // TODO: waiting for response from dev list, logic is mystery to + // me!! + /* + * if (entryTime <= duration) { throw new + * InvalidParameterValueException + * ("Entry time must be greater than duration"); } Calendar calMin = + * Calendar.getInstance(); Calendar calMax = Calendar.getInstance(); + * calMin.add(Calendar.SECOND, -entryTime); + * calMax.add(Calendar.SECOND, -duration); Date minTime = + * calMin.getTime(); Date maxTime = calMax.getTime(); + * + * sc.setParameters("state", com.cloud.event.Event.State.Completed); + * sc.setParameters("startId", 0); sc.setParameters("createDate", + * minTime, maxTime); List startedEvents = + * _eventJoinDao.searchAllEvents(sc, searchFilter); + * List pendingEvents = new ArrayList(); + * for (EventVO event : startedEvents) { EventVO completedEvent = + * _eventDao.findCompletedEvent(event.getId()); if (completedEvent + * == null) { pendingEvents.add(event); } } return pendingEvents; + */ + } else { + eventPair = _eventJoinDao.searchAndCount(sc, searchFilter); + } + return eventPair; + + } + + @Override + public ListResponse listTags(ListTagsCmd cmd) { + Pair, Integer> tags = listTagsInternal(cmd); + ListResponse response = new ListResponse(); + List tagResponses = ViewResponseHelper.createResourceTagResponse(false, tags.first().toArray(new ResourceTagJoinVO[tags.first().size()])); + response.setResponses(tagResponses, tags.second()); + return response; + } + + private Pair, Integer> listTagsInternal(ListTagsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String key = cmd.getKey(); + String value = cmd.getValue(); + String resourceId = cmd.getResourceId(); + String resourceType = cmd.getResourceType(); + String customerName = cmd.getCustomer(); + boolean listAll = cmd.listAll(); + + Ternary domainIdRecursiveListProject = + new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), + cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(ResourceTagJoinVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + + SearchBuilder sb = _resourceTagJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); + sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); + + if (resourceId != null) { + sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); + sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); + sb.cp(); + } + + sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); + + // now set the SC criteria... + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (key != null) { + sc.setParameters("key", key); + } + + if (value != null) { + sc.setParameters("value", value); + } + + if (resourceId != null) { + sc.setParameters("resourceId", resourceId); + sc.setParameters("resourceUuid", resourceId); + } + + if (resourceType != null) { + sc.setParameters("resourceType", resourceType); + } + + if (customerName != null) { + sc.setParameters("customer", customerName); + } + + Pair, Integer> result = _resourceTagJoinDao.searchAndCount(sc, searchFilter); + return result; + } + + + + @Override + public ListResponse searchForVmGroups(ListVMGroupsCmd cmd) { + Pair, Integer> groups = searchForVmGroupsInternal(cmd); + ListResponse response = new ListResponse(); + List grpResponses = ViewResponseHelper.createInstanceGroupResponse(groups.first().toArray(new InstanceGroupJoinVO[groups.first().size()])); + response.setResponses(grpResponses, groups.second()); + return response; + } + + private Pair, Integer> searchForVmGroupsInternal(ListVMGroupsCmd cmd) { + Long id = cmd.getId(); + String name = cmd.getGroupName(); + String keyword = cmd.getKeyword(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(InstanceGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + SearchBuilder sb = _vmGroupJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _vmGroupJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + + if (id != null) { + sc.setParameters("id", id); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + return _vmGroupJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForUserVMs(ListVMsCmd cmd) { + Pair, Integer> result = searchForUserVMsInternal(cmd); + ListResponse response = new ListResponse(); + List vmResponses = ViewResponseHelper.createUserVmResponse("virtualmachine", cmd.getDetails(), result.first().toArray(new UserVmJoinVO[result.first().size()])); + response.setResponses(vmResponses, result.second()); + return response; + } + + private Pair, Integer> searchForUserVMsInternal(ListVMsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String hypervisor = cmd.getHypervisor(); + boolean listAll = cmd.listAll(); + Long id = cmd.getId(); + Map tags = cmd.getTags(); + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); + //Criteria c = new Criteria(null, Boolean.FALSE, cmd.getStartIndex(), cmd.getPageSizeVal()); //version without default sorting + c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); + c.addCriteria(Criteria.ID, cmd.getId()); + c.addCriteria(Criteria.NAME, cmd.getInstanceName()); + c.addCriteria(Criteria.STATE, cmd.getState()); + c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId()); + c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); + c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); + c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); + c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId()); + c.addCriteria(Criteria.ISO_ID, cmd.getIsoId()); + c.addCriteria(Criteria.VPC_ID, cmd.getVpcId()); + + if (domainId != null) { + c.addCriteria(Criteria.DOMAINID, domainId); + } + + if (HypervisorType.getType(hypervisor) != HypervisorType.None) { + c.addCriteria(Criteria.HYPERVISOR, hypervisor); + } else if (hypervisor != null) { + throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); + } + + // ignore these search requests if it's not an admin + if (_accountMgr.isAdmin(caller.getType())) { + c.addCriteria(Criteria.PODID, cmd.getPodId()); + c.addCriteria(Criteria.HOSTID, cmd.getHostId()); + c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId()); + } + + if (!permittedAccounts.isEmpty()) { + c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray()); + } + c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType())); + + return searchForUserVMsByCriteria(c, caller, domainId, isRecursive, + permittedAccounts, listAll, listProjectResourcesCriteria, tags); + } + + + private Pair, Integer> searchForUserVMsByCriteria(Criteria c, Account caller, Long domainId, boolean isRecursive, + List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); + + //first search distinct vm id by using query criteria and pagination + SearchBuilder sb = _userVmJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + Object id = c.getCriteria(Criteria.ID); + Object name = c.getCriteria(Criteria.NAME); + Object state = c.getCriteria(Criteria.STATE); + Object notState = c.getCriteria(Criteria.NOTSTATE); + Object zone = c.getCriteria(Criteria.DATACENTERID); + Object pod = c.getCriteria(Criteria.PODID); + Object hostId = c.getCriteria(Criteria.HOSTID); + Object hostName = c.getCriteria(Criteria.HOSTNAME); + Object keyword = c.getCriteria(Criteria.KEYWORD); + Object isAdmin = c.getCriteria(Criteria.ISADMIN); + assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table."; + Object groupId = c.getCriteria(Criteria.GROUPID); + Object networkId = c.getCriteria(Criteria.NETWORKID); + Object hypervisor = c.getCriteria(Criteria.HYPERVISOR); + Object storageId = c.getCriteria(Criteria.STORAGE_ID); + Object templateId = c.getCriteria(Criteria.TEMPLATE_ID); + Object isoId = c.getCriteria(Criteria.ISO_ID); + Object vpcId = c.getCriteria(Criteria.VPC_ID); + + sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); + sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); + sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ); + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); + + if (groupId != null && (Long) groupId != -1) { + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); + } + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + if (networkId != null) { + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); + } + + if(vpcId != null && networkId == null){ + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + } + + if (storageId != null) { + sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ); + } + + // populate the search criteria with the values passed in + SearchCriteria sc = sb.create(); + + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (groupId != null && (Long)groupId != -1) { + sc.setParameters("instanceGroupId", groupId); + } + + if (keyword != null) { + SearchCriteria ssc = _userVmJoinDao.createSearchCriteria(); + ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.EQ, keyword); + + sc.addAnd("displayName", SearchCriteria.Op.SC, ssc); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (templateId != null) { + sc.setParameters("templateId", templateId); + } + + if (isoId != null) { + sc.setParameters("isoId", isoId); + } + + if (networkId != null) { + sc.setParameters("networkId", networkId); + } + + if(vpcId != null && networkId == null){ + sc.setParameters("vpcId", vpcId); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + if (state != null) { + if (notState != null && (Boolean) notState == true) { + sc.setParameters("stateNEQ", state); + } else { + sc.setParameters("stateEQ", state); + } + } + + if (hypervisor != null) { + sc.setParameters("hypervisorType", hypervisor); + } + + // Don't show Destroyed and Expunging vms to the end user + if ((isAdmin != null) && ((Boolean) isAdmin != true)) { + sc.setParameters("stateNIN", "Destroyed", "Expunging"); + } + + if (zone != null) { + sc.setParameters("dataCenterId", zone); + + if (state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } + } + if (pod != null) { + sc.setParameters("podId", pod); + + if (state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } + } + + if (hostId != null) { + sc.setParameters("hostIdEQ", hostId); + } else { + if (hostName != null) { + sc.setParameters("hostName", hostName); + } + } + + if (storageId != null) { + sc.setParameters("poolId", storageId); + } + + // search vm details by ids + Pair, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVmPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueVmPair; + } + List uniqueVms = uniqueVmPair.first(); + Long[] vmIds = new Long[uniqueVms.size()]; + int i = 0; + for (UserVmJoinVO v : uniqueVms ){ + vmIds[i++] = v.getId(); + } + List vms = _userVmJoinDao.searchByIds(vmIds); + return new Pair, Integer>(vms, count); + } + + + @Override + public ListResponse searchForSecurityGroups(ListSecurityGroupsCmd cmd) { + Pair, Integer> result = searchForSecurityGroupsInternal(cmd); + ListResponse response = new ListResponse(); + List routerResponses = ViewResponseHelper.createSecurityGroupResponses(result.first()); + response.setResponses(routerResponses, result.second()); + return response; + } + + private Pair, Integer> searchForSecurityGroupsInternal(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { + Account caller = UserContext.current().getCaller(); + Long instanceId = cmd.getVirtualMachineId(); + String securityGroup = cmd.getSecurityGroupName(); + Long id = cmd.getId(); + Object keyword = cmd.getKeyword(); + List permittedAccounts = new ArrayList(); + Map tags = cmd.getTags(); + + if (instanceId != null) { + UserVmVO userVM = _userVmDao.findById(instanceId); + if (userVM == null) { + throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); + } + _accountMgr.checkAccess(caller, null, true, userVM); + return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal()); + } + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(SecurityGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _securityGroupJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (id != null) { + sc.setParameters("id", id); + } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (securityGroup != null) { + sc.setParameters("name", securityGroup); + } + + if (keyword != null) { + SearchCriteria ssc = _securityGroupJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + // search security group together with rules + Pair, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueSgPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueSgPair; + } + + List uniqueSgs = uniqueSgPair.first(); + Long[] sgIds = new Long[uniqueSgs.size()]; + int i = 0; + for (SecurityGroupJoinVO v : uniqueSgs ){ + sgIds[i++] = v.getId(); + } + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); + } + + private Pair, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) { + Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize); + Pair, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf); + Integer count = sgVmMappingPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return new Pair, Integer>(new ArrayList(), count); + } + List sgVmMappings = sgVmMappingPair.first(); + Long[] sgIds = new Long[sgVmMappings.size()]; + int i = 0; + for (SecurityGroupVMMapVO sgVm : sgVmMappings) { + sgIds[i++] = sgVm.getSecurityGroupId(); + } + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); + } + + + @Override + public ListResponse searchForRouters(ListRoutersCmd cmd) { + Pair, Integer> result = searchForRoutersInternal(cmd); + ListResponse response = new ListResponse(); + + List routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first().toArray(new DomainRouterJoinVO[result.first().size()])); + response.setResponses(routerResponses, result.second()); + return response; + } + + + private Pair, Integer> searchForRoutersInternal(ListRoutersCmd cmd) { + Long id = cmd.getId(); + String name = cmd.getRouterName(); + String state = cmd.getState(); + Long zone = cmd.getZoneId(); + Long pod = cmd.getPodId(); + Long hostId = cmd.getHostId(); + String keyword = cmd.getKeyword(); + Long networkId = cmd.getNetworkId(); + Long vpcId = cmd.getVpcId(); + Boolean forVpc = cmd.getForVpc(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + //Filter searchFilter = new Filter(DomainRouterJoinVO.class, null, true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _routerJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids to get + // number of + // records with + // pagination + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + + if (forVpc != null) { + if (forVpc) { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); + } else { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); + } + } + + if (networkId != null) { + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); + } + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _routerJoinDao.createSearchCriteria(); + ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (zone != null) { + sc.setParameters("dataCenterId", zone); + } + + if (pod != null) { + sc.setParameters("podId", pod); + } + + if (hostId != null) { + sc.setParameters("hostId", hostId); + } + + if (networkId != null) { + sc.setJoinParameters("nicSearch", "networkId", networkId); + } + + if (vpcId != null) { + sc.setParameters("vpcId", vpcId); + } + + // search VR details by ids + Pair, Integer> uniqueVrPair = _routerJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVrPair.second(); + if (count.intValue() == 0) { + // empty result + return uniqueVrPair; + } + List uniqueVrs = uniqueVrPair.first(); + Long[] vrIds = new Long[uniqueVrs.size()]; + int i = 0; + for (DomainRouterJoinVO v : uniqueVrs) { + vrIds[i++] = v.getId(); + } + List vrs = _routerJoinDao.searchByIds(vrIds); + return new Pair, Integer>(vrs, count); + } + + + + @Override + public ListResponse listProjects(ListProjectsCmd cmd) { + Pair, Integer> projects = listProjectsInternal(cmd); + ListResponse response = new ListResponse(); + List projectResponses = ViewResponseHelper.createProjectResponse(projects.first().toArray(new ProjectJoinVO[projects.first().size()])); + response.setResponses(projectResponses, projects.second()); + return response; + } + + private Pair, Integer> listProjectsInternal(ListProjectsCmd cmd) { + + Long id = cmd.getId(); + String name = cmd.getName(); + String displayText = cmd.getDisplayText(); + String state = cmd.getState(); + String accountName = cmd.getAccountName(); + Long domainId = cmd.getDomainId(); + String keyword = cmd.getKeyword(); + Long startIndex = cmd.getStartIndex(); + Long pageSize = cmd.getPageSizeVal(); + boolean listAll = cmd.listAll(); + boolean isRecursive = cmd.isRecursive(); + Map tags = cmd.getTags(); + + Account caller = UserContext.current().getCaller(); + Long accountId = null; + String path = null; + + Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize); + SearchBuilder sb = _projectJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids + + if (_accountMgr.isAdmin(caller.getType())) { + if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system"); + } + + _accountMgr.checkAccess(caller, domain); + + if (accountName != null) { + Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); + if (owner == null) { + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + } + accountId = owner.getId(); + } + } else { // domainId == null + if (accountName != null) { + throw new InvalidParameterValueException("could not find account " + accountName + " because domain is not specified"); + } + + } + } else { + if (accountName != null && !accountName.equals(caller.getAccountName())) { + throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized"); + } + + if (domainId != null && domainId.equals(caller.getDomainId())) { + throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized"); + } + + accountId = caller.getId(); + } + + if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { + accountId = caller.getId(); + } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { + DomainVO domain = _domainDao.findById(caller.getDomainId()); + path = domain.getPath(); + } + + if (path != null) { + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + if (accountId != null) { + sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); + } + + if (tags != null && !tags.isEmpty()) { + for (int count = 0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + SearchCriteria sc = sb.create(); + + if (id != null) { + sc.addAnd("id", Op.EQ, id); + } + + if (domainId != null && !isRecursive) { + sc.addAnd("domainId", Op.EQ, domainId); + } + + if (name != null) { + sc.addAnd("name", Op.EQ, name); + } + + if (displayText != null) { + sc.addAnd("displayText", Op.EQ, displayText); + } + + if (accountId != null) { + sc.setParameters("accountId", accountId); + } + + if (state != null) { + sc.addAnd("state", Op.EQ, state); + } + + if (keyword != null) { + SearchCriteria ssc = _projectJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (path != null) { + sc.setParameters("domainPath", path); + } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + // search distinct projects to get count + Pair, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniquePrjPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return uniquePrjPair; + } + List uniquePrjs = uniquePrjPair.first(); + Long[] prjIds = new Long[uniquePrjs.size()]; + int i = 0; + for (ProjectJoinVO v : uniquePrjs) { + prjIds[i++] = v.getId(); + } + List prjs = _projectJoinDao.searchByIds(prjIds); + return new Pair, Integer>(prjs, count); + } + + + @Override + public ListResponse listProjectInvitations(ListProjectInvitationsCmd cmd) { + Pair, Integer> invites = listProjectInvitationsInternal(cmd); + ListResponse response = new ListResponse(); + List projectInvitationResponses = + ViewResponseHelper.createProjectInvitationResponse(invites.first().toArray(new ProjectInvitationJoinVO[invites.first().size()])); + + response.setResponses(projectInvitationResponses, invites.second()); + return response; + } + + public Pair, Integer> listProjectInvitationsInternal(ListProjectInvitationsCmd cmd){ + Long id = cmd.getId(); + Long projectId = cmd.getProjectId(); + String accountName = cmd.getAccountName(); + Long domainId = cmd.getDomainId(); + String state = cmd.getState(); + boolean activeOnly = cmd.isActiveOnly(); + Long startIndex = cmd.getStartIndex(); + Long pageSizeVal = cmd.getPageSizeVal(); + boolean isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(ProjectInvitationJoinVO.class, "id", true, startIndex, pageSizeVal); + SearchBuilder sb = _projectInvitationJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + + if (projectId != null){ + sc.setParameters("projectId", projectId); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (activeOnly) { + sc.setParameters("state", ProjectInvitation.State.Pending); + sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - _projectMgr.getInvitationTimeout())); + } + + return _projectInvitationJoinDao.searchAndCount(sc, searchFilter); + + } + + + @Override + public ListResponse listProjectAccounts(ListProjectAccountsCmd cmd) { + Pair, Integer> projectAccounts = listProjectAccountsInternal(cmd); + ListResponse response = new ListResponse(); + List projectResponses = ViewResponseHelper.createProjectAccountResponse(projectAccounts.first().toArray(new ProjectAccountJoinVO[projectAccounts.first().size()])); + response.setResponses(projectResponses, projectAccounts.second()); + return response; + } + + + public Pair, Integer> listProjectAccountsInternal(ListProjectAccountsCmd cmd) { + long projectId = cmd.getProjectId(); + String accountName = cmd.getAccountName(); + String role = cmd.getRole(); + Long startIndex = cmd.getStartIndex(); + Long pageSizeVal = cmd.getPageSizeVal(); + + //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) { + Account caller = UserContext.current().getCaller(); + + //check that the project exists + Project project = _projectDao.findById(projectId); + + if (project == null) { + throw new InvalidParameterValueException("Unable to find the project id=" + projectId); + } + + //verify permissions - only accounts belonging to the project can list project's account + if (!_accountMgr.isAdmin(caller.getType()) && _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) { + throw new PermissionDeniedException("Account " + caller + " is not authorized to list users of the project id=" + projectId); + } + + Filter searchFilter = new Filter(ProjectAccountJoinVO.class, "id", false, startIndex, pageSizeVal); + SearchBuilder sb = _projectAccountJoinDao.createSearchBuilder(); + sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ); + sb.and("projectId", sb.entity().getProjectId(), Op.EQ); + + SearchBuilder accountSearch; + if (accountName != null) { + sb.and("accountName", sb.entity().getAccountName(), Op.EQ); + } + + SearchCriteria sc = sb.create(); + + sc.setParameters("projectId", projectId); + + if (role != null) { + sc.setParameters("accountRole", role); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + } + + return _projectAccountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForServers(ListHostsCmd cmd) { + //FIXME: do we need to support list hosts with VmId, maybe we should create another command just for this + // Right now it is handled separately outside this QueryService + s_logger.debug(">>>Searching for hosts>>>"); + Pair, Integer> hosts = searchForServersInternal(cmd); + ListResponse response = new ListResponse(); + s_logger.debug(">>>Generating Response>>>"); + List hostResponses = ViewResponseHelper.createHostResponse(cmd.getDetails(), hosts.first().toArray(new HostJoinVO[hosts.first().size()])); + response.setResponses(hostResponses, hosts.second()); + return response; + } + + public Pair, Integer> searchForServersInternal(ListHostsCmd cmd) { + + Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); + Object name = cmd.getHostName(); + Object type = cmd.getType(); + Object state = cmd.getState(); + Object pod = cmd.getPodId(); + Object cluster = cmd.getClusterId(); + Object id = cmd.getId(); + Object keyword = cmd.getKeyword(); + Object resourceState = cmd.getResourceState(); + Object haHosts = cmd.getHaHost(); + Long startIndex = cmd.getStartIndex(); + Long pageSize = cmd.getPageSizeVal(); + + Filter searchFilter = new Filter(HostJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize); + + SearchBuilder sb = _hostJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.LIKE); + sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); + + String haTag = _haMgr.getHaTag(); + if (haHosts != null && haTag != null && !haTag.isEmpty()) { + if ((Boolean) haHosts) { + sb.and("tag", sb.entity().getTag(), SearchCriteria.Op.EQ); + } else { + sb.and().op("tag", sb.entity().getTag(), SearchCriteria.Op.NEQ); + sb.or("tagNull", sb.entity().getTag(), SearchCriteria.Op.NULL); + sb.cp(); + } + + } + + + SearchCriteria sc = sb.create(); + + if (keyword != null) { + SearchCriteria ssc = _hostJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("status", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + if (type != null) { + sc.setParameters("type", "%" + type); + } + if (state != null) { + sc.setParameters("status", state); + } + if (zoneId != null) { + sc.setParameters("dataCenterId", zoneId); + } + if (pod != null) { + sc.setParameters("podId", pod); + } + if (cluster != null) { + sc.setParameters("clusterId", cluster); + } + + if (resourceState != null) { + sc.setParameters("resourceState", resourceState); + } + + if (haHosts != null && haTag != null && !haTag.isEmpty()) { + sc.setJoinParameters("hostTagSearch", "tag", haTag); + } + + // search host details by ids + Pair, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueHostPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueHostPair; + } + List uniqueHosts = uniqueHostPair.first(); + Long[] hostIds = new Long[uniqueHosts.size()]; + int i = 0; + for (HostJoinVO v : uniqueHosts ){ + hostIds[i++] = v.getId(); + } + List hosts = _hostJoinDao.searchByIds(hostIds); + return new Pair, Integer>(hosts, count); + + } + + @Override + public ListResponse searchForVolumes(ListVolumesCmd cmd) { + Pair, Integer> result = searchForVolumesInternal(cmd); + ListResponse response = new ListResponse(); + + List volumeResponses = ViewResponseHelper.createVolumeResponse(result.first().toArray(new VolumeJoinVO[result.first().size()])); + response.setResponses(volumeResponses, result.second()); + return response; + } + + + private Pair, Integer> searchForVolumesInternal(ListVolumesCmd cmd) { + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Long id = cmd.getId(); + Long vmInstanceId = cmd.getVirtualMachineId(); + String name = cmd.getVolumeName(); + String keyword = cmd.getKeyword(); + String type = cmd.getType(); + Map tags = cmd.getTags(); + + Long zoneId = cmd.getZoneId(); + Long podId = null; + if (_accountMgr.isAdmin(caller.getType())) { + podId = cmd.getPodId(); + } + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(VolumeJoinVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + + // hack for now, this should be done better but due to needing a join I opted to + // do this quickly and worry about making it pretty later + SearchBuilder sb = _volumeJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids to get + // number of + // records with + // pagination + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE); + sb.and("instanceId", sb.entity().getVmId(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + // Only return volumes that are not destroyed + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("systemUse", sb.entity().isSystemUse(), SearchCriteria.Op.NEQ); + // display UserVM volumes only + sb.and().op("type", sb.entity().getVmType(), SearchCriteria.Op.NIN); + sb.or("nulltype", sb.entity().getVmType(), SearchCriteria.Op.NULL); + sb.cp(); + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + + + // now set the SC criteria... + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _volumeJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + sc.setParameters("systemUse", 1); + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (type != null) { + sc.setParameters("volumeType", "%" + type + "%"); + } + if (vmInstanceId != null) { + sc.setParameters("instanceId", vmInstanceId); + } + if (zoneId != null) { + sc.setParameters("dataCenterId", zoneId); + } + if (podId != null) { + sc.setParameters("podId", podId); + } + + // Don't return DomR and ConsoleProxy volumes + sc.setParameters("type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.DomainRouter); + + // Only return volumes that are not destroyed + sc.setParameters("state", Volume.State.Destroy); + + // search Volume details by ids + Pair, Integer> uniqueVolPair = _volumeJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVolPair.second(); + if (count.intValue() == 0) { + // empty result + return uniqueVolPair; + } + List uniqueVols = uniqueVolPair.first(); + Long[] vrIds = new Long[uniqueVols.size()]; + int i = 0; + for (VolumeJoinVO v : uniqueVols) { + vrIds[i++] = v.getId(); + } + List vrs = _volumeJoinDao.searchByIds(vrIds); + return new Pair, Integer>(vrs, count); + } + + @Override + public ListResponse searchForAccounts(ListAccountsCmd cmd) { + Pair, Integer> result = searchForAccountsInternal(cmd); + ListResponse response = new ListResponse(); + List accountResponses = ViewResponseHelper.createAccountResponse(result.first().toArray(new AccountJoinVO[result.first().size()])); + response.setResponses(accountResponses, result.second()); + return response; + } + + + public Pair, Integer> searchForAccountsInternal(ListAccountsCmd cmd) { + Account caller = UserContext.current().getCaller(); + Long domainId = cmd.getDomainId(); + Long accountId = cmd.getId(); + String accountName = cmd.getSearchName(); + boolean isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + Boolean listForDomain = false; + + if (accountId != null) { + Account account = _accountDao.findById(accountId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by id " + accountId); + } + + _accountMgr.checkAccess(caller, null, true, account); + } + + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); + } + + _accountMgr.checkAccess(caller, domain); + + if (accountName != null) { + Account account = _accountDao.findActiveAccount(accountName, domainId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); + } + _accountMgr.checkAccess(caller, null, true, account); + } + } + + if (accountId == null) { + if (_accountMgr.isAdmin(caller.getType()) && listAll && domainId == null) { + listForDomain = true; + isRecursive = true; + if (domainId == null) { + domainId = caller.getDomainId(); + } + } else if (_accountMgr.isAdmin(caller.getType()) && domainId != null) { + listForDomain = true; + } else { + accountId = caller.getAccountId(); + } + } + + Filter searchFilter = new Filter(AccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + Object type = cmd.getAccountType(); + Object state = cmd.getState(); + Object isCleanupRequired = cmd.isCleanupRequired(); + Object keyword = cmd.getKeyword(); + + SearchBuilder sb = _accountJoinDao.createSearchBuilder(); + sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("needsCleanup", sb.entity().isNeedsCleanup(), SearchCriteria.Op.EQ); + sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); + sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); + + if (listForDomain && isRecursive) { + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + SearchCriteria sc = sb.create(); + + sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); + + if (keyword != null) { + SearchCriteria ssc = _accountJoinDao.createSearchCriteria(); + ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("accountName", SearchCriteria.Op.SC, ssc); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (isCleanupRequired != null) { + sc.setParameters("needsCleanup", isCleanupRequired); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + } + + // don't return account of type project to the end user + sc.setParameters("typeNEQ", 5); + + if (accountId != null) { + sc.setParameters("id", accountId); + } + + if (listForDomain) { + if (isRecursive) { + Domain domain = _domainDao.findById(domainId); + sc.setParameters("path", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + + return _accountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd) { + Pair, Integer> result = searchForAsyncJobsInternal(cmd); + ListResponse response = new ListResponse(); + List jobResponses = ViewResponseHelper.createAsyncJobResponse(result.first().toArray(new AsyncJobJoinVO[result.first().size()])); + response.setResponses(jobResponses, result.second()); + return response; + } + + + public Pair, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) { + + Account caller = UserContext.current().getCaller(); + + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _jobJoinDao.createSearchBuilder(); + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + SearchBuilder accountSearch = null; + boolean accountJoinIsDone = false; + if (permittedAccounts.isEmpty() && domainId != null) { + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + accountJoinIsDone = true; + } + + if (listProjectResourcesCriteria != null) { + + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); + } + + if (!accountJoinIsDone) { + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + } + + Object keyword = cmd.getKeyword(); + Object startDate = cmd.getStartDate(); + + SearchCriteria sc = sb.create(); + if (listProjectResourcesCriteria != null) { + sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT); + } + + if (!permittedAccounts.isEmpty()) { + sc.setParameters("accountIdIN", permittedAccounts.toArray()); + } else if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (isRecursive) { + sc.setParameters("path", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + + if (keyword != null) { + sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + } + + if (startDate != null) { + sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); + } + + return _jobJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForStoragePools(ListStoragePoolsCmd cmd) { + Pair, Integer> result = searchForStoragePoolsInternal(cmd); + ListResponse response = new ListResponse(); + + List poolResponses = ViewResponseHelper.createStoragePoolResponse(result.first().toArray(new StoragePoolJoinVO[result.first().size()])); + response.setResponses(poolResponses, result.second()); + return response; + } + + public Pair, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) { + + Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); + Object id = cmd.getId(); + Object name = cmd.getStoragePoolName(); + Object path = cmd.getPath(); + Object pod = cmd.getPodId(); + Object cluster = cmd.getClusterId(); + Object address = cmd.getIpAddress(); + Object keyword = cmd.getKeyword(); + Long startIndex = cmd.getStartIndex(); + Long pageSize = cmd.getPageSizeVal(); + + + Filter searchFilter = new Filter(StoragePoolJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize); + + SearchBuilder sb = _poolJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("path", sb.entity().getPath(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.and("hostAddress", sb.entity().getHostAddress(), SearchCriteria.Op.EQ); + + + SearchCriteria sc = sb.create(); + + + if (keyword != null) { + SearchCriteria ssc = _poolJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("poolType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (name != null) { + sc.setParameters("name", SearchCriteria.Op.LIKE, "%" + name + "%"); + } + + if (path != null) { + sc.setParameters("path", SearchCriteria.Op.EQ, path); + } + if (zoneId != null) { + sc.setParameters("dataCenterId", SearchCriteria.Op.EQ, zoneId); + } + if (pod != null) { + sc.setParameters("podId", SearchCriteria.Op.EQ, pod); + } + if (address != null) { + sc.setParameters("hostAddress", SearchCriteria.Op.EQ, address); + } + if (cluster != null) { + sc.setParameters("clusterId", SearchCriteria.Op.EQ, cluster); + } + + // search Pool details by ids + Pair, Integer> uniquePoolPair = _poolJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniquePoolPair.second(); + if (count.intValue() == 0) { + // empty result + return uniquePoolPair; + } + List uniquePools = uniquePoolPair.first(); + Long[] vrIds = new Long[uniquePools.size()]; + int i = 0; + for (StoragePoolJoinVO v : uniquePools) { + vrIds[i++] = v.getId(); + } + List vrs = _poolJoinDao.searchByIds(vrIds); + return new Pair, Integer>(vrs, count); + + } + + +} diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java new file mode 100644 index 00000000000..39c108eb932 --- /dev/null +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -0,0 +1,277 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +/** + * Helper class to generate response from DB view VO objects. + * @author minc + * + */ +public class ViewResponseHelper { + + public static final Logger s_logger = Logger.getLogger(ViewResponseHelper.class); + + public static List createUserResponse(UserAccountJoinVO... users) { + List respList = new ArrayList(); + for (UserAccountJoinVO vt : users){ + respList.add(ApiDBUtils.newUserResponse(vt)); + } + return respList; + } + + public static List createEventResponse(EventJoinVO... events) { + List respList = new ArrayList(); + for (EventJoinVO vt : events){ + respList.add(ApiDBUtils.newEventResponse(vt)); + } + return respList; + } + + public static List createResourceTagResponse(boolean keyValueOnly, ResourceTagJoinVO... tags) { + List respList = new ArrayList(); + for (ResourceTagJoinVO vt : tags){ + respList.add(ApiDBUtils.newResourceTagResponse(vt, keyValueOnly)); + } + return respList; + } + + public static List createInstanceGroupResponse(InstanceGroupJoinVO... groups) { + List respList = new ArrayList(); + for (InstanceGroupJoinVO vt : groups){ + respList.add(ApiDBUtils.newInstanceGroupResponse(vt)); + } + return respList; + } + + + public static List createUserVmResponse(String objectName, UserVmJoinVO... userVms) { + return createUserVmResponse(objectName, EnumSet.of(VMDetails.all), userVms); + } + + public static List createUserVmResponse(String objectName, EnumSet details, UserVmJoinVO... userVms) { + Account caller = UserContext.current().getCaller(); + + Hashtable vmDataList = new Hashtable(); + // Initialise the vmdatalist with the input data + + + for (UserVmJoinVO userVm : userVms) { + UserVmResponse userVmData = vmDataList.get(userVm.getId()); + if ( userVmData == null ){ + // first time encountering this vm + userVmData = ApiDBUtils.newUserVmResponse(objectName, userVm, details, caller); + } else{ + // update nics, securitygroups, tags for 1 to many mapping fields + userVmData = ApiDBUtils.fillVmDetails(userVmData, userVm); + } + vmDataList.put(userVm.getId(), userVmData); + } + return new ArrayList(vmDataList.values()); + } + + public static List createDomainRouterResponse(DomainRouterJoinVO... routers) { + Account caller = UserContext.current().getCaller(); + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (DomainRouterJoinVO vr : routers) { + DomainRouterResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this vm + vrData = ApiDBUtils.newDomainRouterResponse(vr, caller); + } + else{ + // update nics for 1 to many mapping fields + vrData = ApiDBUtils.fillRouterDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + + public static List createSecurityGroupResponses(List securityGroups) { + Account caller = UserContext.current().getCaller(); + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (SecurityGroupJoinVO vr : securityGroups) { + SecurityGroupResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ) { + // first time encountering this sg + vrData = ApiDBUtils.newSecurityGroupResponse(vr, caller); + + } else { + // update rules for 1 to many mapping fields + vrData = ApiDBUtils.fillSecurityGroupDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + + public static List createProjectResponse(ProjectJoinVO... projects) { + Hashtable prjDataList = new Hashtable(); + // Initialise the prjdatalist with the input data + for (ProjectJoinVO p : projects) { + ProjectResponse pData = prjDataList.get(p.getId()); + if ( pData == null ){ + // first time encountering this vm + pData = ApiDBUtils.newProjectResponse(p); + } + else{ + // update those 1 to many mapping fields + pData = ApiDBUtils.fillProjectDetails(pData, p); + } + prjDataList.put(p.getId(), pData); + } + return new ArrayList(prjDataList.values()); + } + + + public static List createProjectAccountResponse(ProjectAccountJoinVO... projectAccounts) { + List responseList = new ArrayList(); + for (ProjectAccountJoinVO proj : projectAccounts){ + ProjectAccountResponse resp = ApiDBUtils.newProjectAccountResponse(proj); + // update user list + List users = ApiDBUtils.findUserViewByAccountId(proj.getAccountId()); + resp.setUsers(ViewResponseHelper.createUserResponse(users.toArray(new UserAccountJoinVO[users.size()]))); + responseList.add(resp); + } + return responseList; + } + + public static List createProjectInvitationResponse(ProjectInvitationJoinVO... invites) { + List respList = new ArrayList(); + for (ProjectInvitationJoinVO v : invites){ + respList.add(ApiDBUtils.newProjectInvitationResponse(v)); + } + return respList; + } + + public static List createHostResponse(EnumSet details, HostJoinVO... hosts) { + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (HostJoinVO vr : hosts) { + HostResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this vm + vrData = ApiDBUtils.newHostResponse(vr, details); + } + else{ + // update tags + vrData = ApiDBUtils.fillHostDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + public static List createVolumeResponse(VolumeJoinVO... volumes) { + Hashtable vrDataList = new Hashtable(); + for (VolumeJoinVO vr : volumes) { + VolumeResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this volume + vrData = ApiDBUtils.newVolumeResponse(vr); + } + else{ + // update tags + vrData = ApiDBUtils.fillVolumeDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + public static List createStoragePoolResponse(StoragePoolJoinVO... pools) { + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (StoragePoolJoinVO vr : pools) { + StoragePoolResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this vm + vrData = ApiDBUtils.newStoragePoolResponse(vr); + } + else{ + // update tags + vrData = ApiDBUtils.fillStoragePoolDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + + public static List createAccountResponse(AccountJoinVO... accounts) { + List respList = new ArrayList(); + for (AccountJoinVO vt : accounts){ + respList.add(ApiDBUtils.newAccountResponse(vt)); + } + return respList; + } + + public static List createAsyncJobResponse(AsyncJobJoinVO... jobs) { + List respList = new ArrayList(); + for (AsyncJobJoinVO vt : jobs){ + respList.add(ApiDBUtils.newAsyncJobResponse(vt)); + } + return respList; + } +} diff --git a/server/src/com/cloud/api/query/dao/AccountJoinDao.java b/server/src/com/cloud/api/query/dao/AccountJoinDao.java new file mode 100644 index 00000000000..5485f093d87 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AccountJoinDao.java @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.AccountResponse; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface AccountJoinDao extends GenericDao { + + AccountResponse newAccountResponse(AccountJoinVO vol); + + AccountJoinVO newAccountView(Account vol); + +} diff --git a/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java new file mode 100644 index 00000000000..626872447e7 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java @@ -0,0 +1,185 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.ViewResponseHelper; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.configuration.Resource.ResourceType; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.UserResponse; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={AccountJoinDao.class}) +public class AccountJoinDaoImpl extends GenericDaoBase implements AccountJoinDao { + public static final Logger s_logger = Logger.getLogger(AccountJoinDaoImpl.class); + + private SearchBuilder acctIdSearch; + + protected AccountJoinDaoImpl() { + + acctIdSearch = createSearchBuilder(); + acctIdSearch.and("id", acctIdSearch.entity().getId(), SearchCriteria.Op.EQ); + acctIdSearch.done(); + + this._count = "select count(distinct id) from account_view WHERE "; + } + + + + @Override + public AccountResponse newAccountResponse(AccountJoinVO account) { + boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); + AccountResponse accountResponse = new AccountResponse(); + accountResponse.setId(account.getUuid()); + accountResponse.setName(account.getAccountName()); + accountResponse.setAccountType(account.getType()); + accountResponse.setDomainId(account.getDomainUuid()); + accountResponse.setDomainName(account.getDomainName()); + accountResponse.setState(account.getState().toString()); + accountResponse.setNetworkDomain(account.getNetworkDomain()); + accountResponse.setDefaultZone(account.getDataCenterUuid()); + + // get network stat + accountResponse.setBytesReceived(account.getBytesReceived()); + accountResponse.setBytesSent(account.getBytesSent()); + + // Get resource limits and counts + + long vmLimit = ApiDBUtils.findCorrectResourceLimit(account.getVmLimit(), account.getType(), ResourceType.user_vm); + String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); + long vmTotal = (account.getVmTotal() == null) ? 0 : account.getVmTotal(); + String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); + accountResponse.setVmLimit(vmLimitDisplay); + accountResponse.setVmTotal(vmTotal); + accountResponse.setVmAvailable(vmAvail); + + long ipLimit = ApiDBUtils.findCorrectResourceLimit(account.getIpLimit(), account.getType(), ResourceType.public_ip); + String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); + long ipTotal = (account.getIpTotal() == null) ? 0 : account.getIpTotal(); + + Long ips = ipLimit - ipTotal; + // check how many free ips are left, and if it's less than max allowed number of ips from account - use this + // value + Long ipsLeft = account.getIpFree(); + boolean unlimited = true; + if (ips.longValue() > ipsLeft.longValue()) { + ips = ipsLeft; + unlimited = false; + } + + String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); + + accountResponse.setIpLimit(ipLimitDisplay); + accountResponse.setIpTotal(ipTotal); + accountResponse.setIpAvailable(ipAvail); + + long volumeLimit = ApiDBUtils.findCorrectResourceLimit(account.getVolumeLimit(), account.getType(), ResourceType.volume); + String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); + long volumeTotal = (account.getVolumeTotal() == 0) ? 0 : account.getVolumeTotal(); + String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); + accountResponse.setVolumeLimit(volumeLimitDisplay); + accountResponse.setVolumeTotal(volumeTotal); + accountResponse.setVolumeAvailable(volumeAvail); + + long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(account.getSnapshotLimit(), account.getType(), ResourceType.snapshot); + String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); + long snapshotTotal = (account.getSnapshotTotal() == null) ? 0 : account.getSnapshotTotal(); + String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); + accountResponse.setSnapshotLimit(snapshotLimitDisplay); + accountResponse.setSnapshotTotal(snapshotTotal); + accountResponse.setSnapshotAvailable(snapshotAvail); + + Long templateLimit = ApiDBUtils.findCorrectResourceLimit(account.getTemplateLimit(), account.getType(), ResourceType.template); + String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); + Long templateTotal = (account.getTemplateTotal() == null) ? 0 : account.getTemplateTotal(); + String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); + accountResponse.setTemplateLimit(templateLimitDisplay); + accountResponse.setTemplateTotal(templateTotal); + accountResponse.setTemplateAvailable(templateAvail); + + // Get stopped and running VMs + accountResponse.setVmStopped(account.getVmStopped()); + accountResponse.setVmRunning(account.getVmRunning()); + + + //get resource limits for projects + long projectLimit = ApiDBUtils.findCorrectResourceLimit(account.getProjectLimit(), account.getType(), ResourceType.project); + String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); + long projectTotal = (account.getProjectTotal() == null) ? 0 : account.getProjectTotal(); + String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); + accountResponse.setProjectLimit(projectLimitDisplay); + accountResponse.setProjectTotal(projectTotal); + accountResponse.setProjectAvailable(projectAvail); + + //get resource limits for networks + long networkLimit = ApiDBUtils.findCorrectResourceLimit(account.getNetworkLimit(), account.getType(), ResourceType.network); + String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); + long networkTotal = (account.getNetworkTotal() == null) ? 0 : account.getNetworkTotal(); + String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); + accountResponse.setNetworkLimit(networkLimitDisplay); + accountResponse.setNetworkTotal(networkTotal); + accountResponse.setNetworkAvailable(networkAvail); + + //get resource limits for vpcs + long vpcLimit = ApiDBUtils.findCorrectResourceLimit(account.getVpcLimit(), account.getType(), ResourceType.vpc); + String vpcLimitDisplay = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit); + long vpcTotal = (account.getVpcTotal() == null) ? 0 : account.getVpcTotal(); + String vpcAvail = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit - vpcTotal); + accountResponse.setNetworkLimit(vpcLimitDisplay); + accountResponse.setNetworkTotal(vpcTotal); + accountResponse.setNetworkAvailable(vpcAvail); + + // adding all the users for an account as part of the response obj + List usersForAccount = ApiDBUtils.findUserViewByAccountId(account.getId()); + List userResponses = ViewResponseHelper.createUserResponse(usersForAccount.toArray(new UserAccountJoinVO[usersForAccount.size()])); + accountResponse.setUsers(userResponses); + + // set details + accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); + accountResponse.setObjectName("account"); + + // set async job + accountResponse.setJobId(account.getJobUuid()); + accountResponse.setJobStatus(account.getJobStatus()); + return accountResponse; + } + + + @Override + public AccountJoinVO newAccountView(Account acct) { + SearchCriteria sc = acctIdSearch.create(); + sc.setParameters("id", acct.getId()); + List accounts = searchIncludingRemoved(sc, null, null, false); + assert accounts != null && accounts.size() == 1 : "No account found for account id " + acct.getId(); + return accounts.get(0); + + } + + +} diff --git a/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java b/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java new file mode 100644 index 00000000000..f7a2c8c0f69 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java @@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.AsyncJobResponse; + +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.async.AsyncJob; +import com.cloud.utils.db.GenericDao; + +public interface AsyncJobJoinDao extends GenericDao { + + AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO vol); + + AsyncJobJoinVO newAsyncJobView(AsyncJob vol); + +} diff --git a/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java new file mode 100644 index 00000000000..bf1d15c4205 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java @@ -0,0 +1,114 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.Date; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiSerializerHelper; +import com.cloud.api.SerializationContext; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.async.AsyncJob; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={AsyncJobJoinDao.class}) +public class AsyncJobJoinDaoImpl extends GenericDaoBase implements AsyncJobJoinDao { + public static final Logger s_logger = Logger.getLogger(AsyncJobJoinDaoImpl.class); + + private SearchBuilder jobIdSearch; + + protected AsyncJobJoinDaoImpl() { + + + jobIdSearch = createSearchBuilder(); + jobIdSearch.and("id", jobIdSearch.entity().getId(), SearchCriteria.Op.EQ); + jobIdSearch.done(); + + this._count = "select count(distinct id) from async_job_view WHERE "; + } + + + + + + @Override + public AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO job) { + AsyncJobResponse jobResponse = new AsyncJobResponse(); + jobResponse.setAccountId(job.getAccountUuid()); + jobResponse.setUserId(job.getUserUuid()); + jobResponse.setCmd(job.getCmd()); + jobResponse.setCreated(job.getCreated()); + jobResponse.setJobId(job.getUuid()); + jobResponse.setJobStatus(job.getStatus()); + jobResponse.setJobProcStatus(job.getProcessStatus()); + + if (job.getInstanceType() != null && job.getInstanceId() != null) { + jobResponse.setJobInstanceType(job.getInstanceType().toString()); + + jobResponse.setJobInstanceId(job.getInstanceUuid()); + + } + jobResponse.setJobResultCode(job.getResultCode()); + + boolean savedValue = SerializationContext.current().getUuidTranslation(); + SerializationContext.current().setUuidTranslation(false); + + Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); + jobResponse.setJobResult((ResponseObject) resultObject); + SerializationContext.current().setUuidTranslation(savedValue); + + if (resultObject != null) { + Class clz = resultObject.getClass(); + if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { + jobResponse.setJobResultType("text"); + } else { + jobResponse.setJobResultType("object"); + } + } + + jobResponse.setObjectName("asyncjobs"); + return jobResponse; + } + + + + + + @Override + public AsyncJobJoinVO newAsyncJobView(AsyncJob job) { + SearchCriteria sc = jobIdSearch.create(); + sc.setParameters("id", job.getId()); + List accounts = searchIncludingRemoved(sc, null, null, false); + assert accounts != null && accounts.size() == 1 : "No async job found for job id " + job.getId(); + return accounts.get(0); + + } + + + + + +} diff --git a/api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java similarity index 53% rename from api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java rename to server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java index 0af58555ea6..961ab40a88d 100644 --- a/api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java +++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java @@ -14,29 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package com.cloud.api.query.dao; -import org.apache.log4j.Logger; +import java.util.List; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.response.DomainRouterResponse; -public class ListIsoPermissionsCmd extends ListTemplateOrIsoPermissionsCmd { - protected String getResponseName() { - return "listisopermissionsresponse"; - } - - @Override - public String getMediaType() { - return "iso"; - } - - @Override - protected Logger getLogger() { - return Logger.getLogger(ListIsoPermissionsCmd.class.getName()); - } - - protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return template.getFormat().equals(ImageFormat.ISO); - } +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface DomainRouterJoinDao extends GenericDao { + + DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO uvo, Account caller); + + DomainRouterResponse setDomainRouterResponse(DomainRouterResponse userVmData, DomainRouterJoinVO uvo); + + List newDomainRouterView(VirtualRouter vr); + + List searchByIds(Long... ids); } diff --git a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java new file mode 100644 index 00000000000..94736cd7f90 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java @@ -0,0 +1,249 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.NicResponse; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={DomainRouterJoinDao.class}) +public class DomainRouterJoinDaoImpl extends GenericDaoBase implements DomainRouterJoinDao { + public static final Logger s_logger = Logger.getLogger(DomainRouterJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder vrSearch; + + private SearchBuilder vrIdSearch; + + protected DomainRouterJoinDaoImpl() { + + vrSearch = createSearchBuilder(); + vrSearch.and("idIN", vrSearch.entity().getId(), SearchCriteria.Op.IN); + vrSearch.done(); + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + this._count = "select count(distinct id) from domain_router_view WHERE "; + } + + + @Override + public DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO router, Account caller) { + DomainRouterResponse routerResponse = new DomainRouterResponse(); + routerResponse.setId(router.getUuid()); + routerResponse.setZoneId(router.getDataCenterUuid()); + routerResponse.setName(router.getHostName()); + routerResponse.setTemplateId(router.getTemplateUuid()); + routerResponse.setCreated(router.getCreated()); + routerResponse.setState(router.getState()); + routerResponse.setIsRedundantRouter(router.isRedundantRouter()); + routerResponse.setRedundantState(router.getRedundantState().toString()); + + if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN + || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { + if (router.getHostId() != null) { + routerResponse.setHostId(router.getHostUuid()); + routerResponse.setHostName(router.getHostName()); + } + routerResponse.setPodId(router.getPodUuid()); + long nic_id = router.getNicId(); + if (nic_id > 0) { + TrafficType ty = router.getTrafficType(); + if (ty != null) { + // legacy code, public/control/guest nic info is kept in + // nics response object + if (ty == TrafficType.Public) { + routerResponse.setPublicIp(router.getIpAddress()); + routerResponse.setPublicMacAddress(router.getMacAddress()); + routerResponse.setPublicNetmask(router.getNetmask()); + routerResponse.setGateway(router.getGateway()); + routerResponse.setPublicNetworkId(router.getNetworkUuid()); + } else if (ty == TrafficType.Control) { + routerResponse.setLinkLocalIp(router.getIpAddress()); + routerResponse.setLinkLocalMacAddress(router.getMacAddress()); + routerResponse.setLinkLocalNetmask(router.getNetmask()); + routerResponse.setLinkLocalNetworkId(router.getNetworkUuid()); + } else if (ty == TrafficType.Guest) { + routerResponse.setGuestIpAddress(router.getIpAddress()); + routerResponse.setGuestMacAddress(router.getMacAddress()); + routerResponse.setGuestNetmask(router.getNetmask()); + routerResponse.setGuestNetworkId(router.getNetworkUuid()); + routerResponse.setNetworkDomain(router.getNetworkDomain()); + } + } + + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(router.getNicUuid()); + nicResponse.setIpaddress(router.getIpAddress()); + nicResponse.setGateway(router.getGateway()); + nicResponse.setNetmask(router.getNetmask()); + nicResponse.setNetworkid(router.getNetworkUuid()); + nicResponse.setNetworkName(router.getNetworkName()); + nicResponse.setMacAddress(router.getMacAddress()); + if (router.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(router.getBroadcastUri().toString()); + } + if (router.getIsolationUri() != null) { + nicResponse.setIsolationUri(router.getIsolationUri().toString()); + } + if (router.getTrafficType() != null) { + nicResponse.setTrafficType(router.getTrafficType().toString()); + } + if (router.getGuestType() != null) { + nicResponse.setType(router.getGuestType().toString()); + } + nicResponse.setIsDefault(router.isDefaultNic()); + nicResponse.setObjectName("nic"); + routerResponse.addNic(nicResponse); + } + } + + routerResponse.setServiceOfferingId(router.getServiceOfferingUuid()); + routerResponse.setServiceOfferingName(router.getServiceOfferingName()); + + // populate owner. + ApiResponseHelper.populateOwner(routerResponse, router); + + + routerResponse.setDomainId(router.getDomainUuid()); + routerResponse.setDomainName(router.getDomainName()); + + routerResponse.setZoneName(router.getDataCenterName()); + routerResponse.setDns1(router.getDns1()); + routerResponse.setDns2(router.getDns2()); + + routerResponse.setVpcId(router.getVpcUuid()); + + // set async job + routerResponse.setJobId(router.getJobUuid()); + routerResponse.setJobStatus(router.getJobStatus()); + + routerResponse.setObjectName("router"); + + return routerResponse; + } + + + @Override + public DomainRouterResponse setDomainRouterResponse(DomainRouterResponse vrData, DomainRouterJoinVO vr) { + long nic_id = vr.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(vr.getNicUuid()); + nicResponse.setIpaddress(vr.getIpAddress()); + nicResponse.setGateway(vr.getGateway()); + nicResponse.setNetmask(vr.getNetmask()); + nicResponse.setNetworkid(vr.getNetworkUuid()); + nicResponse.setMacAddress(vr.getMacAddress()); + if (vr.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(vr.getBroadcastUri().toString()); + } + if (vr.getIsolationUri() != null) { + nicResponse.setIsolationUri(vr.getIsolationUri().toString()); + } + if (vr.getTrafficType() != null) { + nicResponse.setTrafficType(vr.getTrafficType().toString()); + } + if (vr.getGuestType() != null) { + nicResponse.setType(vr.getGuestType().toString()); + } + nicResponse.setIsDefault(vr.isDefaultNic()); + nicResponse.setObjectName("nic"); + vrData.addNic(nicResponse); + } + return vrData; + } + + + + + @Override + public List searchByIds(Long... vrIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( vrIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= vrIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = vrIds[j]; + } + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < vrIds.length) { + int batch_size = (vrIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = vrIds[j]; + } + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + @Override + public List newDomainRouterView(VirtualRouter vr) { + + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", vr.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + +} diff --git a/server/src/com/cloud/api/query/dao/HostJoinDao.java b/server/src/com/cloud/api/query/dao/HostJoinDao.java new file mode 100644 index 00000000000..1a2129998ed --- /dev/null +++ b/server/src/com/cloud/api/query/dao/HostJoinDao.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.EnumSet; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.response.HostResponse; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.host.Host; +import com.cloud.utils.db.GenericDao; + +public interface HostJoinDao extends GenericDao { + + HostResponse newHostResponse(HostJoinVO host, EnumSet details); + + HostResponse setHostResponse(HostResponse response, HostJoinVO host); + + List newHostView(Host group); + + List searchByIds(Long... ids); + +} diff --git a/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java new file mode 100644 index 00000000000..e8423836004 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java @@ -0,0 +1,270 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.host.Host; +import com.cloud.host.HostStats; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.response.HostResponse; +import com.cloud.storage.StorageStats; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={HostJoinDao.class}) +public class HostJoinDaoImpl extends GenericDaoBase implements HostJoinDao { + public static final Logger s_logger = Logger.getLogger(HostJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder hostSearch; + + private SearchBuilder hostIdSearch; + + + protected HostJoinDaoImpl() { + + hostSearch = createSearchBuilder(); + hostSearch.and("idIN", hostSearch.entity().getId(), SearchCriteria.Op.IN); + hostSearch.done(); + + hostIdSearch = createSearchBuilder(); + hostIdSearch.and("id", hostIdSearch.entity().getId(), SearchCriteria.Op.EQ); + hostIdSearch.done(); + + this._count = "select count(distinct id) from host_view WHERE "; + } + + + + @Override + public HostResponse newHostResponse(HostJoinVO host, EnumSet details) { + HostResponse hostResponse = new HostResponse(); + hostResponse.setId(host.getUuid()); + hostResponse.setCapabilities(host.getCapabilities()); + hostResponse.setClusterId(host.getClusterUuid()); + hostResponse.setCpuNumber(host.getCpus()); + hostResponse.setZoneId(host.getUuid()); + hostResponse.setDisconnectedOn(host.getDisconnectedOn()); + hostResponse.setHypervisor(host.getHypervisorType()); + hostResponse.setHostType(host.getType()); + hostResponse.setLastPinged(new Date(host.getLastPinged())); + hostResponse.setManagementServerId(host.getManagementServerId()); + hostResponse.setName(host.getName()); + hostResponse.setPodId(host.getPodUuid()); + hostResponse.setRemoved(host.getRemoved()); + hostResponse.setCpuSpeed(host.getSpeed()); + hostResponse.setState(host.getStatus()); + hostResponse.setIpAddress(host.getPrivateIpAddress()); + hostResponse.setVersion(host.getVersion()); + hostResponse.setCreated(host.getCreated()); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) + || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { + + hostResponse.setOsCategoryId(host.getOsCategoryUuid()); + hostResponse.setOsCategoryName(host.getOsCategoryName()); + hostResponse.setZoneName(host.getZoneName()); + hostResponse.setPodName(host.getPodName()); + if ( host.getClusterId() > 0) { + hostResponse.setClusterName(host.getClusterName()); + hostResponse.setClusterType(host.getClusterType().toString()); + } + } + + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + if (host.getType() == Host.Type.Routing) { + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { + // set allocated capacities + Long mem = host.getMemReservedCapacity() + host.getMemUsedCapacity(); + Long cpu = host.getCpuReservedCapacity() + host.getCpuReservedCapacity(); + + hostResponse.setMemoryAllocated(mem); + hostResponse.setMemoryTotal(host.getTotalMemory()); + + String hostTags = host.getTag(); + hostResponse.setHostTags(host.getTag()); + + String haTag = ApiDBUtils.getHaTag(); + if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) { + if (haTag.equalsIgnoreCase(hostTags)) { + hostResponse.setHaHost(true); + } else { + hostResponse.setHaHost(false); + } + } else { + hostResponse.setHaHost(false); + } + + hostResponse.setHypervisorVersion(host.getHypervisorVersion()); + + String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; + hostResponse.setCpuAllocated(cpuAlloc); + String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); + hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); + } + + if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { + // set CPU/RAM/Network stats + String cpuUsed = null; + HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); + if (hostStats != null) { + float cpuUtil = (float) hostStats.getCpuUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + hostResponse.setCpuUsed(cpuUsed); + hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); + hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); + hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); + + } + } + + } else if (host.getType() == Host.Type.SecondaryStorage) { + StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); + if (secStorageStats != null) { + hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); + hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); + } + } + + hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host.getId())); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { + Set possibleEvents = host.getStatus().getPossibleEvents(); + if ((possibleEvents != null) && !possibleEvents.isEmpty()) { + String events = ""; + Iterator iter = possibleEvents.iterator(); + while (iter.hasNext()) { + com.cloud.host.Status.Event event = iter.next(); + events += event.toString(); + if (iter.hasNext()) { + events += "; "; + } + } + hostResponse.setEvents(events); + } + } + + hostResponse.setResourceState(host.getResourceState().toString()); + + // set async job + hostResponse.setJobId(host.getJobUuid()); + hostResponse.setJobStatus(host.getJobStatus()); + + hostResponse.setObjectName("host"); + + return hostResponse; + } + + + + + + + @Override + public HostResponse setHostResponse(HostResponse response, HostJoinVO host) { + String tag = host.getTag(); + if (tag != null) { + if ( response.getHostTags() != null && response.getHostTags().length() > 0){ + response.setHostTags(response.getHostTags() + "," + tag); + } + else{ + response.setHostTags(tag); + } + } + return response; + } + + + + @Override + public List newHostView(Host host) { + SearchCriteria sc = hostIdSearch.create(); + sc.setParameters("id", host.getId()); + return searchIncludingRemoved(sc, null, null, false); + + } + + + + @Override + public List searchByIds(Long... hostIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( hostIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= hostIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = hostIds[j]; + } + SearchCriteria sc = hostSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < hostIds.length) { + int batch_size = (hostIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = hostIds[j]; + } + SearchCriteria sc = hostSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java new file mode 100644 index 00000000000..78ceab16c42 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; + +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.InstanceGroup; + +public interface InstanceGroupJoinDao extends GenericDao { + + InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO group); + + InstanceGroupJoinVO newInstanceGroupView(InstanceGroup group); + + +} diff --git a/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java new file mode 100644 index 00000000000..f83ef6cd8fd --- /dev/null +++ b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java @@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.InstanceGroupJoinVO; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.InstanceGroup; + + +@Local(value={InstanceGroupJoinDao.class}) +public class InstanceGroupJoinDaoImpl extends GenericDaoBase implements InstanceGroupJoinDao { + public static final Logger s_logger = Logger.getLogger(InstanceGroupJoinDaoImpl.class); + + private SearchBuilder vrIdSearch; + + + protected InstanceGroupJoinDaoImpl() { + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + this._count = "select count(distinct id) from instance_group_view WHERE "; + } + + + + @Override + public InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO group) { + InstanceGroupResponse groupResponse = new InstanceGroupResponse(); + groupResponse.setId(group.getUuid()); + groupResponse.setName(group.getName()); + groupResponse.setCreated(group.getCreated()); + + ApiResponseHelper.populateOwner(groupResponse, group); + + groupResponse.setObjectName("instancegroup"); + return groupResponse; + } + + + + @Override + public InstanceGroupJoinVO newInstanceGroupView(InstanceGroup group) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", group.getId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No vm group found for group id " + group.getId(); + return grps.get(0); + + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java new file mode 100644 index 00000000000..d8fa0f8acb1 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java @@ -0,0 +1,32 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.ProjectAccountResponse; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.projects.ProjectAccount; +import com.cloud.utils.db.GenericDao; + +public interface ProjectAccountJoinDao extends GenericDao { + + ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj); + + ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj); + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java new file mode 100644 index 00000000000..f808da0c5f1 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java @@ -0,0 +1,86 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.response.ProjectAccountResponse; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.projects.ProjectAccount; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectAccountJoinDao.class}) +public class ProjectAccountJoinDaoImpl extends GenericDaoBase implements ProjectAccountJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectAccountJoinDaoImpl.class); + + + private SearchBuilder paIdSearch; + + protected ProjectAccountJoinDaoImpl() { + + paIdSearch = createSearchBuilder(); + paIdSearch.and("accountId", paIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + paIdSearch.and("projectId", paIdSearch.entity().getProjectId(), SearchCriteria.Op.EQ); + paIdSearch.done(); + + this._count = "select count(distinct id) from project_account_view WHERE "; + } + + + + + @Override + public ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj) { + ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); + + projectAccountResponse.setProjectId(proj.getProjectUuid()); + projectAccountResponse.setProjectName(proj.getProjectName()); + + projectAccountResponse.setAccountId(proj.getAccountUuid()); + projectAccountResponse.setAccountName(proj.getAccountName()); + projectAccountResponse.setAccountType(proj.getAccountType()); + projectAccountResponse.setRole(proj.getAccountRole().toString()); + projectAccountResponse.setDomainId(proj.getDomainUuid()); + projectAccountResponse.setDomainName(proj.getDomainName()); + + projectAccountResponse.setObjectName("projectaccount"); + + return projectAccountResponse; + } + + + + + @Override + public ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj) { + SearchCriteria sc = paIdSearch.create(); + sc.setParameters("accountId", proj.getAccountId()); + sc.setParameters("projectId", proj.getProjectId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No project account found for account id = " + proj.getAccountId() + " and project id = " + proj.getProjectId(); + return grps.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java new file mode 100644 index 00000000000..ae81f0eae3b --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import org.apache.cloudstack.api.response.ProjectInvitationResponse; + +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.projects.ProjectInvitation; +import com.cloud.utils.db.GenericDao; + +public interface ProjectInvitationJoinDao extends GenericDao { + + ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO proj); + + ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj); +} diff --git a/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java new file mode 100644 index 00000000000..ebf64d1ce55 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.response.ProjectInvitationResponse; + +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.projects.ProjectInvitation; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectInvitationJoinDao.class}) +public class ProjectInvitationJoinDaoImpl extends GenericDaoBase implements ProjectInvitationJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectInvitationJoinDaoImpl.class); + + + private SearchBuilder piIdSearch; + + protected ProjectInvitationJoinDaoImpl() { + + piIdSearch = createSearchBuilder(); + piIdSearch.and("id", piIdSearch.entity().getId(), SearchCriteria.Op.EQ); + piIdSearch.done(); + + this._count = "select count(distinct id) from project_invitation_view WHERE "; + } + + + + @Override + public ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO invite) { + ProjectInvitationResponse response = new ProjectInvitationResponse(); + response.setId(invite.getUuid()); + response.setProjectId(invite.getProjectUuid()); + response.setProjectName(invite.getProjectName()); + response.setInvitationState(invite.getState().toString()); + + if (invite.getAccountName() != null) { + response.setAccountName(invite.getAccountName()); + } else { + response.setEmail(invite.getEmail()); + } + + response.setDomainId(invite.getDomainUuid()); + response.setDomainName(invite.getDomainName()); + + response.setObjectName("projectinvitation"); + return response; + } + + + + @Override + public ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj) { + SearchCriteria sc = piIdSearch.create(); + sc.setParameters("id", proj.getId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No project invitation found for id " + proj.getId(); + return grps.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectJoinDao.java new file mode 100644 index 00000000000..9eeb8aa65f2 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectJoinDao.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.ProjectResponse; + +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.projects.Project; +import com.cloud.utils.db.GenericDao; + +public interface ProjectJoinDao extends GenericDao { + + ProjectResponse newProjectResponse(ProjectJoinVO proj); + + ProjectResponse setProjectResponse(ProjectResponse rsp, ProjectJoinVO proj); + + List newProjectView(Project proj); + + List searchByIds(Long... ids); + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java new file mode 100644 index 00000000000..15bff3677fe --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java @@ -0,0 +1,153 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.ProjectResponse; +import com.cloud.projects.Project; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectJoinDao.class}) +public class ProjectJoinDaoImpl extends GenericDaoBase implements ProjectJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder prjSearch; + + private SearchBuilder prjIdSearch; + + protected ProjectJoinDaoImpl() { + + prjSearch = createSearchBuilder(); + prjSearch.and("idIN", prjSearch.entity().getId(), SearchCriteria.Op.IN); + prjSearch.done(); + + prjIdSearch = createSearchBuilder(); + prjIdSearch.and("id", prjIdSearch.entity().getId(), SearchCriteria.Op.EQ); + prjIdSearch.done(); + + this._count = "select count(distinct id) from project_view WHERE "; + } + + @Override + public ProjectResponse newProjectResponse(ProjectJoinVO proj) { + ProjectResponse response = new ProjectResponse(); + response.setId(proj.getUuid()); + response.setName(proj.getName()); + response.setDisplaytext(proj.getDisplayText()); + if (proj.getState() != null) { + response.setState(proj.getState().toString()); + } + response.setDomainId(proj.getDomainUuid()); + response.setDomain(proj.getDomainName()); + + response.setOwner(proj.getOwner()); + + // update tag information + Long tag_id = proj.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + response.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + response.setObjectName("project"); + return response; + } + + @Override + public ProjectResponse setProjectResponse(ProjectResponse rsp, ProjectJoinVO proj) { + // update tag information + Long tag_id = proj.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + rsp.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return rsp; + } + + @Override + public List newProjectView(Project proj) { + SearchCriteria sc = prjIdSearch.create(); + sc.setParameters("id", proj.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + @Override + public List searchByIds(Long... prjIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( prjIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= prjIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = prjIds[j]; + } + SearchCriteria sc = prjSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < prjIds.length) { + int batch_size = (prjIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = prjIds[j]; + } + SearchCriteria sc = prjSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + +} diff --git a/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java b/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java new file mode 100644 index 00000000000..57fc130de55 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java @@ -0,0 +1,34 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.ResourceTagResponse; + +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.server.ResourceTag; +import com.cloud.utils.db.GenericDao; + +public interface ResourceTagJoinDao extends GenericDao { + + ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO uvo, boolean keyValueOnly ); + + ResourceTagJoinVO newResourceTagView(ResourceTag vr); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java new file mode 100644 index 00000000000..5adee9ee170 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java @@ -0,0 +1,146 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.ResourceTagResponse; +import com.cloud.server.ResourceTag; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={ResourceTagJoinDao.class}) +public class ResourceTagJoinDaoImpl extends GenericDaoBase implements ResourceTagJoinDao { + public static final Logger s_logger = Logger.getLogger(ResourceTagJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder tagSearch; + + private SearchBuilder tagIdSearch; + + protected ResourceTagJoinDaoImpl() { + + tagSearch = createSearchBuilder(); + tagSearch.and("idIN", tagSearch.entity().getId(), SearchCriteria.Op.IN); + tagSearch.done(); + + tagIdSearch = createSearchBuilder(); + tagIdSearch.and("id", tagIdSearch.entity().getId(), SearchCriteria.Op.EQ); + tagIdSearch.done(); + + this._count = "select count(distinct id) from resource_tag_view WHERE "; + } + + + + + + @Override + public ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO resourceTag, boolean keyValueOnly) { + ResourceTagResponse response = new ResourceTagResponse(); + response.setKey(resourceTag.getKey()); + response.setValue(resourceTag.getValue()); + + if (!keyValueOnly) { + response.setResourceType(resourceTag.getResourceType().toString()); + response.setResourceId(resourceTag.getResourceUuid()); + + ApiResponseHelper.populateOwner(response, resourceTag); + + response.setDomainId(resourceTag.getDomainUuid()); + response.setDomainName(resourceTag.getDomainName()); + + response.setCustomer(resourceTag.getCustomer()); + } + + response.setObjectName("tag"); + + return response; + } + + + @Override + public List searchByIds(Long... tagIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( tagIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= tagIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = tagIds[j]; + } + SearchCriteria sc = tagSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < tagIds.length) { + int batch_size = (tagIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = tagIds[j]; + } + SearchCriteria sc = tagSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + @Override + public ResourceTagJoinVO newResourceTagView(ResourceTag vr) { + + SearchCriteria sc = tagIdSearch.create(); + sc.setParameters("id", vr.getId()); + List vms = searchIncludingRemoved(sc, null, null, false); + assert vms != null && vms.size() == 1 : "No tag found for tag id " + vr.getId(); + return vms.get(0); + + } + +} diff --git a/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java new file mode 100644 index 00000000000..de1b72ae487 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.SecurityGroupResponse; + +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.network.security.SecurityGroup; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface SecurityGroupJoinDao extends GenericDao { + + SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller); + + SecurityGroupResponse setSecurityGroupResponse(SecurityGroupResponse vsgData, SecurityGroupJoinVO vsg); + + List newSecurityGroupView(SecurityGroup sg); + + List searchByIds(Long... ids); +} + diff --git a/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java new file mode 100644 index 00000000000..c35c4aae297 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java @@ -0,0 +1,225 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import com.cloud.network.security.SecurityGroup; +import com.cloud.network.security.SecurityRule.SecurityRuleType; +import com.cloud.user.Account; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={SecurityGroupJoinDao.class}) +public class SecurityGroupJoinDaoImpl extends GenericDaoBase implements SecurityGroupJoinDao { + public static final Logger s_logger = Logger.getLogger(SecurityGroupJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder sgSearch; + + private SearchBuilder sgIdSearch; + + protected SecurityGroupJoinDaoImpl() { + + sgSearch = createSearchBuilder(); + sgSearch.and("idIN", sgSearch.entity().getId(), SearchCriteria.Op.IN); + sgSearch.done(); + + sgIdSearch = createSearchBuilder(); + sgIdSearch.and("id", sgIdSearch.entity().getId(), SearchCriteria.Op.EQ); + sgIdSearch.done(); + + this._count = "select count(distinct id) from security_group_view WHERE "; + } + + @Override + public SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller) { + SecurityGroupResponse sgResponse = new SecurityGroupResponse(); + sgResponse.setId(vsg.getUuid()); + sgResponse.setName(vsg.getName()); + sgResponse.setDescription(vsg.getDescription()); + + ApiResponseHelper.populateOwner(sgResponse, vsg); + + Long rule_id = vsg.getRuleId(); + if (rule_id != null && rule_id.longValue() > 0) { + SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); + ruleData.setRuleId(vsg.getRuleUuid()); + ruleData.setProtocol(vsg.getRuleProtocol()); + + if ("icmp".equalsIgnoreCase(vsg.getRuleProtocol())) { + ruleData.setIcmpType(vsg.getRuleStartPort()); + ruleData.setIcmpCode(vsg.getRuleEndPort()); + } else { + ruleData.setStartPort(vsg.getRuleStartPort()); + ruleData.setEndPort(vsg.getRuleEndPort()); + } + + if (vsg.getRuleAllowedNetworkId() != null) { + List sgs = this.searchByIds(vsg.getRuleAllowedNetworkId()); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + ruleData.setSecurityGroupName(sg.getName()); + ruleData.setAccountName(sg.getAccountName()); + } + } else { + ruleData.setCidr(vsg.getRuleAllowedSourceIpCidr()); + } + + if (vsg.getRuleType() == SecurityRuleType.IngressRule) { + ruleData.setObjectName("ingressrule"); + sgResponse.addSecurityGroupIngressRule(ruleData); + } else { + ruleData.setObjectName("egressrule"); + sgResponse.addSecurityGroupEgressRule(ruleData); + } + } + + // update tag information + Long tag_id = vsg.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + sgResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + // set async job + sgResponse.setJobId(vsg.getJobUuid()); + sgResponse.setJobStatus(vsg.getJobStatus()); + + sgResponse.setObjectName("securitygroup"); + + return sgResponse; + } + + @Override + public SecurityGroupResponse setSecurityGroupResponse(SecurityGroupResponse vsgData, SecurityGroupJoinVO vsg) { + Long rule_id = vsg.getRuleId(); + if (rule_id != null && rule_id.longValue() > 0) { + SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); + ruleData.setRuleId(vsg.getRuleUuid()); + ruleData.setProtocol(vsg.getRuleProtocol()); + + if ("icmp".equalsIgnoreCase(vsg.getRuleProtocol())) { + ruleData.setIcmpType(vsg.getRuleStartPort()); + ruleData.setIcmpCode(vsg.getRuleEndPort()); + } else { + ruleData.setStartPort(vsg.getRuleStartPort()); + ruleData.setEndPort(vsg.getRuleEndPort()); + } + + if (vsg.getRuleAllowedNetworkId() != null) { + List sgs = this.searchByIds(vsg.getRuleAllowedNetworkId()); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + ruleData.setSecurityGroupName(sg.getName()); + ruleData.setAccountName(sg.getAccountName()); + } + } else { + ruleData.setCidr(vsg.getRuleAllowedSourceIpCidr()); + } + + if (vsg.getRuleType() == SecurityRuleType.IngressRule) { + ruleData.setObjectName("ingressrule"); + vsgData.addSecurityGroupIngressRule(ruleData); + } else { + ruleData.setObjectName("egressrule"); + vsgData.addSecurityGroupEgressRule(ruleData); + } + } + + // update tag information + Long tag_id = vsg.getTagId(); + if (tag_id != null && tag_id.longValue() > 0 ) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + vsgData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return vsgData; + } + + @Override + public List newSecurityGroupView(SecurityGroup sg) { + + SearchCriteria sc = sgIdSearch.create(); + sc.setParameters("id", sg.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + @Override + public List searchByIds(Long... sgIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( sgIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= sgIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = sgIds[j]; + } + SearchCriteria sc = sgSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < sgIds.length) { + int batch_size = (sgIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = sgIds[j]; + } + SearchCriteria sc = sgSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } +} diff --git a/server/src/com/cloud/api/query/dao/StoragePoolJoinDao.java b/server/src/com/cloud/api/query/dao/StoragePoolJoinDao.java new file mode 100644 index 00000000000..bbb02428981 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/StoragePoolJoinDao.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.StoragePoolResponse; + +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.storage.StoragePool; +import com.cloud.utils.db.GenericDao; + +public interface StoragePoolJoinDao extends GenericDao { + + StoragePoolResponse newStoragePoolResponse(StoragePoolJoinVO host); + + StoragePoolResponse setStoragePoolResponse(StoragePoolResponse response, StoragePoolJoinVO host); + + List newStoragePoolView(StoragePool group); + + List searchByIds(Long... spIds); + +} diff --git a/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java new file mode 100644 index 00000000000..44ed1303af5 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/StoragePoolJoinDaoImpl.java @@ -0,0 +1,185 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.StoragePoolJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; +import org.apache.cloudstack.api.response.StoragePoolResponse; + +import com.cloud.storage.StoragePool; +import com.cloud.storage.StorageStats; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={StoragePoolJoinDao.class}) +public class StoragePoolJoinDaoImpl extends GenericDaoBase implements StoragePoolJoinDao { + public static final Logger s_logger = Logger.getLogger(StoragePoolJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder spSearch; + + private SearchBuilder spIdSearch; + + + protected StoragePoolJoinDaoImpl() { + + spSearch = createSearchBuilder(); + spSearch.and("idIN", spSearch.entity().getId(), SearchCriteria.Op.IN); + spSearch.done(); + + spIdSearch = createSearchBuilder(); + spIdSearch.and("id", spIdSearch.entity().getId(), SearchCriteria.Op.EQ); + spIdSearch.done(); + + this._count = "select count(distinct id) from storage_pool_view WHERE "; + } + + + + + + @Override + public StoragePoolResponse newStoragePoolResponse(StoragePoolJoinVO pool) { + StoragePoolResponse poolResponse = new StoragePoolResponse(); + poolResponse.setId(pool.getUuid()); + poolResponse.setName(pool.getName()); + poolResponse.setState(pool.getStatus()); + poolResponse.setPath(pool.getPath()); + poolResponse.setIpAddress(pool.getHostAddress()); + poolResponse.setZoneId(pool.getZoneUuid()); + poolResponse.setZoneName(pool.getZoneName()); + if (pool.getPoolType() != null) { + poolResponse.setType(pool.getPoolType().toString()); + } + poolResponse.setPodId(pool.getPodUuid()); + poolResponse.setPodName(pool.getPodName()); + poolResponse.setCreated(pool.getCreated()); + + + long allocatedSize = pool.getUsedCapacity() + pool.getReservedCapacity(); + poolResponse.setDiskSizeTotal(pool.getCapacityBytes()); + poolResponse.setDiskSizeAllocated(allocatedSize); + + //TODO: StatsCollector does not persist data + StorageStats stats = ApiDBUtils.getStoragePoolStatistics(pool.getId()); + if (stats != null) { + Long used = stats.getByteUsed(); + poolResponse.setDiskSizeUsed(used); + } + + poolResponse.setClusterId(pool.getClusterUuid()); + poolResponse.setClusterName(pool.getClusterName()); + poolResponse.setTags(pool.getTag()); + + // set async job + poolResponse.setJobId(pool.getJobUuid()); + poolResponse.setJobStatus(pool.getJobStatus()); + + poolResponse.setObjectName("storagepool"); + return poolResponse; + } + + + + + + @Override + public StoragePoolResponse setStoragePoolResponse(StoragePoolResponse response, StoragePoolJoinVO sp) { + String tag = sp.getTag(); + if (tag != null) { + if ( response.getTags() != null && response.getTags().length() > 0){ + response.setTags(response.getTags() + "," + tag); + } + else{ + response.setTags(tag); + } + } + return response; + } + + + + @Override + public List newStoragePoolView(StoragePool host) { + SearchCriteria sc = spIdSearch.create(); + sc.setParameters("id", host.getId()); + return searchIncludingRemoved(sc, null, null, false); + + } + + + + @Override + public List searchByIds(Long... spIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( spIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= spIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = spIds[j]; + } + SearchCriteria sc = spSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < spIds.length) { + int batch_size = (spIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = spIds[j]; + } + SearchCriteria sc = spSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java b/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java new file mode 100644 index 00000000000..b48f19272bc --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.UserResponse; + +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.utils.db.GenericDao; + +public interface UserAccountJoinDao extends GenericDao { + + UserResponse newUserResponse(UserAccountJoinVO usr); + + UserAccountJoinVO newUserView(User usr); + + UserAccountJoinVO newUserView(UserAccount usr); + + List searchByAccountId(Long accountId); + +} diff --git a/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java new file mode 100644 index 00000000000..b1f5dcafeb3 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java @@ -0,0 +1,129 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; + +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.InstanceGroup; + + +@Local(value={UserAccountJoinDao.class}) +public class UserAccountJoinDaoImpl extends GenericDaoBase implements UserAccountJoinDao { + public static final Logger s_logger = Logger.getLogger(UserAccountJoinDaoImpl.class); + + + private SearchBuilder vrIdSearch; + + private SearchBuilder vrAcctIdSearch; + + + protected UserAccountJoinDaoImpl() { + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + vrAcctIdSearch = createSearchBuilder(); + vrAcctIdSearch.and("accountid", vrAcctIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + vrAcctIdSearch.done(); + + + this._count = "select count(distinct id) from user_view WHERE "; + } + + + + @Override + public UserResponse newUserResponse(UserAccountJoinVO usr) { + UserResponse userResponse = new UserResponse(); + userResponse.setAccountId(usr.getAccountUuid()); + userResponse.setAccountName(usr.getAccountName()); + userResponse.setAccountType(usr.getAccountType()); + userResponse.setCreated(usr.getCreated()); + userResponse.setDomainId(usr.getDomainUuid()); + userResponse.setDomainName(usr.getDomainName()); + userResponse.setEmail(usr.getEmail()); + userResponse.setFirstname(usr.getFirstname()); + userResponse.setId(usr.getUuid()); + userResponse.setLastname(usr.getLastname()); + userResponse.setState(usr.getState().toString()); + userResponse.setTimezone(usr.getTimezone()); + userResponse.setUsername(usr.getUsername()); + userResponse.setApiKey(usr.getApiKey()); + userResponse.setSecretKey(usr.getSecretKey()); + + // set async job + userResponse.setJobId(usr.getJobUuid()); + userResponse.setJobStatus(usr.getJobStatus()); + + userResponse.setObjectName("user"); + + return userResponse; + } + + + @Override + public UserAccountJoinVO newUserView(User usr) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", usr.getId()); + List users = searchIncludingRemoved(sc, null, null, false); + assert users != null && users.size() == 1 : "No user found for user id " + usr.getId(); + return users.get(0); + } + + + + + @Override + public UserAccountJoinVO newUserView(UserAccount usr) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", usr.getId()); + List users = searchIncludingRemoved(sc, null, null, false); + assert users != null && users.size() == 1 : "No user found for user id " + usr.getId(); + return users.get(0); + } + + + @Override + public List searchByAccountId(Long accountId) { + SearchCriteria sc = vrAcctIdSearch.create(); + sc.setParameters("accountId", accountId); + return searchIncludingRemoved(sc, null, null, false); + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/UserVmJoinDao.java b/server/src/com/cloud/api/query/dao/UserVmJoinDao.java new file mode 100644 index 00000000000..2617a7475ef --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserVmJoinDao.java @@ -0,0 +1,39 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.EnumSet; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.UserVmResponse; + +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; +import com.cloud.utils.db.GenericDao; + +public interface UserVmJoinDao extends GenericDao { + + UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller); + + UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo); + + List newUserVmView(UserVm... userVms); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java new file mode 100644 index 00000000000..3310518ee79 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java @@ -0,0 +1,331 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.NicResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.VmStats; + + +@Local(value={UserVmJoinDao.class}) +public class UserVmJoinDaoImpl extends GenericDaoBase implements UserVmJoinDao { + public static final Logger s_logger = Logger.getLogger(UserVmJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder VmDetailSearch; + + protected UserVmJoinDaoImpl() { + + VmDetailSearch = createSearchBuilder(); + VmDetailSearch.and("idIN", VmDetailSearch.entity().getId(), SearchCriteria.Op.IN); + VmDetailSearch.done(); + + this._count = "select count(distinct id) from user_vm_view WHERE "; + + + } + + public UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller) { + UserVmResponse userVmResponse = new UserVmResponse(); + + if (userVm.getHypervisorType() != null){ + userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); + } + userVmResponse.setId(userVm.getUuid()); + userVmResponse.setName(userVm.getName()); + + userVmResponse.setDisplayName(userVm.getDisplayName()); + + if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + userVmResponse.setProjectId(userVm.getProjectUuid()); + userVmResponse.setProjectName(userVm.getProjectName()); + } else { + userVmResponse.setAccountName(userVm.getAccountName()); + } + + userVmResponse.setDomainId(userVm.getDomainUuid()); + userVmResponse.setDomainName(userVm.getDomainName()); + + userVmResponse.setCreated(userVm.getCreated()); + + if (userVm.getState() != null) { + userVmResponse.setState(userVm.getState().toString()); + } + userVmResponse.setHaEnable(userVm.isHaEnabled()); + if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { + userVmResponse.setGroupId(userVm.getInstanceGroupUuid()); + userVmResponse.setGroup(userVm.getInstanceGroupName()); + } + userVmResponse.setZoneId(userVm.getDataCenterUuid()); + userVmResponse.setZoneName(userVm.getDataCenterName()); + if ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) { + userVmResponse.setInstanceName(userVm.getInstanceName()); + userVmResponse.setHostId(userVm.getHostUuid()); + userVmResponse.setHostName(userVm.getHostName()); + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { + userVmResponse.setTemplateId(userVm.getTemplateUuid()); + userVmResponse.setTemplateName(userVm.getTemplateName()); + userVmResponse.setTemplateDisplayText(userVm.getTemplateDisplayText()); + userVmResponse.setPasswordEnabled(userVm.isPasswordEnabled()); + } + if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { + userVmResponse.setIsoId(userVm.getIsoUuid()); + userVmResponse.setIsoName(userVm.getIsoName()); + userVmResponse.setIsoDisplayText(userVm.getIsoDisplayText()); + } + if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { + userVmResponse.setServiceOfferingId(userVm.getServiceOfferingUuid()); + userVmResponse.setServiceOfferingName(userVm.getServiceOfferingName()); + userVmResponse.setCpuNumber(userVm.getCpu()); + userVmResponse.setCpuSpeed(userVm.getSpeed()); + userVmResponse.setMemory(userVm.getRamSize()); + } + userVmResponse.setGuestOsId(userVm.getGuestOsUuid()); + if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { + userVmResponse.setRootDeviceId(userVm.getVolumeDeviceId()); + if (userVm.getVolumeType() != null) { + userVmResponse.setRootDeviceType(userVm.getVolumeType().toString()); + } + } + userVmResponse.setPassword(userVm.getPassword()); + userVmResponse.setJobId(userVm.getJobUuid()); + userVmResponse.setJobStatus(userVm.getJobStatus()); + //userVmResponse.setForVirtualNetwork(userVm.getForVirtualNetwork()); + + userVmResponse.setPublicIpId(userVm.getPublicIpUuid()); + userVmResponse.setPublicIp(userVm.getPublicIpAddress()); + userVmResponse.setKeyPairName(userVm.getKeypairName()); + + if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + // stats calculation + String cpuUsed = null; + VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); + if (vmStats != null) { + float cpuUtil = (float) vmStats.getCPUUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + userVmResponse.setCpuUsed(cpuUsed); + + Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); + userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); + + Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); + userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { + Long securityGroupId = userVm.getSecurityGroupId(); + if (securityGroupId != null && securityGroupId.longValue() != 0) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(userVm.getSecurityGroupUuid()); + resp.setName(userVm.getSecurityGroupName()); + resp.setDescription(userVm.getSecurityGroupDescription()); + resp.setObjectName("securitygroup"); + if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + resp.setProjectId(userVm.getProjectUuid()); + resp.setProjectName(userVm.getProjectName()); + } else { + resp.setAccountName(userVm.getAccountName()); + } + userVmResponse.addSecurityGroup(resp); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { + long nic_id = userVm.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(userVm.getNicUuid()); + nicResponse.setIpaddress(userVm.getIpAddress()); + nicResponse.setGateway(userVm.getGateway()); + nicResponse.setNetmask(userVm.getNetmask()); + nicResponse.setNetworkid(userVm.getNetworkUuid()); + nicResponse.setMacAddress(userVm.getMacAddress()); + if (userVm.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(userVm.getBroadcastUri().toString()); + } + if (userVm.getIsolationUri() != null) { + nicResponse.setIsolationUri(userVm.getIsolationUri().toString()); + } + if (userVm.getTrafficType() != null) { + nicResponse.setTrafficType(userVm.getTrafficType().toString()); + } + if (userVm.getGuestType() != null) { + nicResponse.setType(userVm.getGuestType().toString()); + } + nicResponse.setIsDefault(userVm.isDefaultNic()); + nicResponse.setObjectName("nic"); + userVmResponse.addNic(nicResponse); + } + } + + // update tag information + long tag_id = userVm.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + userVmResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + userVmResponse.setObjectName(objectName); + + return userVmResponse; + } + + public UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo) { + Long securityGroupId = uvo.getSecurityGroupId(); + if (securityGroupId != null && securityGroupId.longValue() != 0) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(uvo.getSecurityGroupUuid()); + resp.setName(uvo.getSecurityGroupName()); + resp.setDescription(uvo.getSecurityGroupDescription()); + resp.setObjectName("securitygroup"); + if (uvo.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + resp.setProjectId(uvo.getProjectUuid()); + resp.setProjectName(uvo.getProjectName()); + } else { + resp.setAccountName(uvo.getAccountName()); + } + userVmData.addSecurityGroup(resp); + } + + long nic_id = uvo.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(uvo.getNicUuid()); + nicResponse.setIpaddress(uvo.getIpAddress()); + nicResponse.setGateway(uvo.getGateway()); + nicResponse.setNetmask(uvo.getNetmask()); + nicResponse.setNetworkid(uvo.getNetworkUuid()); + nicResponse.setMacAddress(uvo.getMacAddress()); + if (uvo.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(uvo.getBroadcastUri().toString()); + } + if (uvo.getIsolationUri() != null) { + nicResponse.setIsolationUri(uvo.getIsolationUri().toString()); + } + if (uvo.getTrafficType() != null) { + nicResponse.setTrafficType(uvo.getTrafficType().toString()); + } + if (uvo.getGuestType() != null) { + nicResponse.setType(uvo.getGuestType().toString()); + } + nicResponse.setIsDefault(uvo.isDefaultNic()); + nicResponse.setObjectName("nic"); + userVmData.addNic(nicResponse); + } + + long tag_id = uvo.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + userVmData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return userVmData; + } + + + @Override + public List searchByIds(Long... vmIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( vmIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= vmIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = vmIds[j]; + } + SearchCriteria sc = VmDetailSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < vmIds.length) { + int batch_size = (vmIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = vmIds[j]; + } + SearchCriteria sc = VmDetailSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + @Override + public List newUserVmView(UserVm... userVms) { + + Hashtable userVmDataHash = new Hashtable(); + for (UserVm vm : userVms){ + if ( !userVmDataHash.containsKey(vm.getId())){ + userVmDataHash.put(vm.getId(), vm); + } + } + + Set vmIdSet = userVmDataHash.keySet(); + return searchByIds(vmIdSet.toArray(new Long[vmIdSet.size()])); + } + +} diff --git a/server/src/com/cloud/api/query/dao/VolumeJoinDao.java b/server/src/com/cloud/api/query/dao/VolumeJoinDao.java new file mode 100644 index 00000000000..67509cf5b29 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/VolumeJoinDao.java @@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.VolumeResponse; + + +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.storage.Volume; +import com.cloud.utils.db.GenericDao; + +public interface VolumeJoinDao extends GenericDao { + + VolumeResponse newVolumeResponse(VolumeJoinVO vol); + + VolumeResponse setVolumeResponse(VolumeResponse volData, VolumeJoinVO vol); + + List newVolumeView(Volume vol); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java new file mode 100644 index 00000000000..35ba2eb4537 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java @@ -0,0 +1,279 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.VolumeResponse; + +import com.cloud.offering.ServiceOffering; +import com.cloud.storage.Storage; +import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.Volume; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={VolumeJoinDao.class}) +public class VolumeJoinDaoImpl extends GenericDaoBase implements VolumeJoinDao { + public static final Logger s_logger = Logger.getLogger(VolumeJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder volSearch; + + private SearchBuilder volIdSearch; + + protected VolumeJoinDaoImpl() { + + volSearch = createSearchBuilder(); + volSearch.and("idIN", volSearch.entity().getId(), SearchCriteria.Op.IN); + volSearch.done(); + + volIdSearch = createSearchBuilder(); + volIdSearch.and("id", volIdSearch.entity().getId(), SearchCriteria.Op.EQ); + volIdSearch.done(); + + this._count = "select count(distinct id) from volume_view WHERE "; + } + + + + + @Override + public VolumeResponse newVolumeResponse(VolumeJoinVO volume) { + Account caller = UserContext.current().getCaller(); + + VolumeResponse volResponse = new VolumeResponse(); + volResponse.setId(volume.getUuid()); + + if (volume.getName() != null) { + volResponse.setName(volume.getName()); + } else { + volResponse.setName(""); + } + + volResponse.setZoneId(volume.getDataCenterUuid()); + volResponse.setZoneName(volume.getDataCenterName()); + + volResponse.setVolumeType(volume.getVolumeType().toString()); + volResponse.setDeviceId(volume.getDeviceId()); + + long instanceId = volume.getVmId(); + if (instanceId > 0 && volume.getState() != Volume.State.Destroy) { + volResponse.setVirtualMachineId(volume.getVmUuid()); + volResponse.setVirtualMachineName(volume.getVmName()); + volResponse.setVirtualMachineState(volume.getVmState().toString()); + volResponse.setVirtualMachineDisplayName(volume.getVmDisplayName()); + } + + // Show the virtual size of the volume + volResponse.setSize(volume.getSize()); + + volResponse.setCreated(volume.getCreated()); + volResponse.setState(volume.getState().toString()); + if (volume.getState() == Volume.State.UploadOp) { + // com.cloud.storage.VolumeHostVO volumeHostRef = + // ApiDBUtils.findVolumeHostRef(volume.getId(), + // volume.getDataCenterId()); + volResponse.setSize(volume.getVolumeHostSize()); + volResponse.setCreated(volume.getVolumeHostCreated()); + + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getFormat()).toString()); + if (volume.getDownloadState() != Status.DOWNLOADED) { + String volumeStatus = "Processing"; + if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { + if (volume.getDownloadPercent() == 100) { + volumeStatus = "Checking Volume"; + } else { + volumeStatus = volume.getDownloadPercent() + "% Uploaded"; + } + volResponse.setState("Uploading"); + } else { + volumeStatus = volume.getErrorString(); + if (volume.getDownloadState() == VMTemplateHostVO.Status.NOT_DOWNLOADED) { + volResponse.setState("UploadNotStarted"); + } else { + volResponse.setState("UploadError"); + } + } + volResponse.setStatus(volumeStatus); + } else if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { + volResponse.setStatus("Upload Complete"); + volResponse.setState("Uploaded"); + } else { + volResponse.setStatus("Successfully Installed"); + } + } + + // populate owner. + ApiResponseHelper.populateOwner(volResponse, volume); + + // DiskOfferingVO diskOffering = + // ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); + if (volume.getDiskOfferingId() > 0) { + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingId(volume.getDiskOfferingUuid()); + } else { + volResponse.setDiskOfferingId(volume.getDiskOfferingUuid()); + } + + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingName(volume.getDiskOfferingName()); + volResponse.setServiceOfferingDisplayText(volume.getDiskOfferingDisplayText()); + } else { + volResponse.setDiskOfferingName(volume.getDiskOfferingName()); + volResponse.setDiskOfferingDisplayText(volume.getDiskOfferingDisplayText()); + } + volResponse.setStorageType(volume.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared + .toString()); + } + Long poolId = volume.getPoolId(); + String poolName = (poolId == null) ? "none" : volume.getPoolName(); + volResponse.setStoragePoolName(poolName); + + // return hypervisor for ROOT and Resource domain only + if ((caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + && volume.getState() != Volume.State.UploadOp && volume.getHypervisorType() != null) { + volResponse.setHypervisor(volume.getHypervisorType().toString()); + } + + volResponse.setAttached(volume.getAttached()); + volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); + boolean isExtractable = true; + if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont + // have any + // template + // dependence. + if (volume.getTemplateId() > 0) { // For ISO based volumes template + // = null and we allow extraction + // of all ISO based volumes + isExtractable = volume.isExtractable() && volume.getTemplateType() != Storage.TemplateType.SYSTEM; + } + } + + // update tag information + long tag_id = volume.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if (vtag != null) { + volResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + volResponse.setExtractable(isExtractable); + + // set async job + volResponse.setJobId(volume.getJobUuid()); + volResponse.setJobStatus(volume.getJobStatus()); + + volResponse.setObjectName("volume"); + return volResponse; + } + + + + @Override + public VolumeResponse setVolumeResponse(VolumeResponse volData, VolumeJoinVO vol) { + long tag_id = vol.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + volData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return volData; + } + + + + + @Override + public List newVolumeView(Volume vol) { + SearchCriteria sc = volIdSearch.create(); + sc.setParameters("id", vol.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + + + + @Override + public List searchByIds(Long... volIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( volIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= volIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = volIds[j]; + } + SearchCriteria sc = volSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < volIds.length) { + int batch_size = (volIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = volIds[j]; + } + SearchCriteria sc = volSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/AccountJoinVO.java b/server/src/com/cloud/api/query/vo/AccountJoinVO.java new file mode 100644 index 00000000000..6d37f4de00e --- /dev/null +++ b/server/src/com/cloud/api/query/vo/AccountJoinVO.java @@ -0,0 +1,571 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import com.cloud.user.Account.State; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="account_view") +public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="type") + private short type; + + + @Column(name="state") + @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") + private String networkDomain; + + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName; + + @Column(name="bytesReceived") + private Long bytesReceived; + + @Column(name="bytesSent") + private Long bytesSent; + + @Column(name="vmLimit") + private Long vmLimit; + + @Column(name="vmTotal") + private Long vmTotal; + + + @Column(name="ipLimit") + private Long ipLimit; + + @Column(name="ipTotal") + private Long ipTotal; + + @Column(name="ipFree") + private Long ipFree; + + @Column(name="volumeLimit") + private Long volumeLimit; + + @Column(name="volumeTotal") + private Long volumeTotal; + + @Column(name="snapshotLimit") + private Long snapshotLimit; + + @Column(name="snapshotTotal") + private Long snapshotTotal; + + @Column(name="templateLimit") + private Long templateLimit; + + @Column(name="templateTotal") + private Long templateTotal; + + @Column(name="stoppedVms") + private Integer vmStopped; + + @Column(name="runningVms") + private Integer vmRunning; + + @Column(name="projectLimit") + private Long projectLimit; + + @Column(name="projectTotal") + private Long projectTotal; + + + @Column(name="networkLimit") + private Long networkLimit; + + @Column(name="networkTotal") + private Long networkTotal; + + + @Column(name="vpcLimit") + private Long vpcLimit; + + @Column(name="vpcTotal") + private Long vpcTotal; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + public AccountJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getType() { + return type; + } + + + public void setType(short type) { + this.type = type; + } + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public boolean isNeedsCleanup() { + return needsCleanup; + } + + + public void setNeedsCleanup(boolean needsCleanup) { + this.needsCleanup = needsCleanup; + } + + + public String getNetworkDomain() { + return networkDomain; + } + + + public void setNetworkDomain(String networkDomain) { + this.networkDomain = networkDomain; + } + + + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public long getDataCenterId() { + return dataCenterId; + } + + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + public void setDataCenterUuid(String dataCenterUuid) { + this.dataCenterUuid = dataCenterUuid; + } + + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String dataCenterName) { + this.dataCenterName = dataCenterName; + } + + + public Long getBytesReceived() { + return bytesReceived; + } + + + public void setBytesReceived(Long bytesReceived) { + this.bytesReceived = bytesReceived; + } + + + public Long getBytesSent() { + return bytesSent; + } + + + public void setBytesSent(Long bytesSent) { + this.bytesSent = bytesSent; + } + + + + + public Long getVmTotal() { + return vmTotal; + } + + + public void setVmTotal(Long vmTotal) { + this.vmTotal = vmTotal; + } + + + + + + public Long getIpTotal() { + return ipTotal; + } + + + public void setIpTotal(Long ipTotal) { + this.ipTotal = ipTotal; + } + + + public Long getIpFree() { + return ipFree; + } + + + public void setIpFree(Long ipFree) { + this.ipFree = ipFree; + } + + + + public Long getVolumeTotal() { + return volumeTotal; + } + + + public void setVolumeTotal(Long volumeTotal) { + this.volumeTotal = volumeTotal; + } + + + + public Long getSnapshotTotal() { + return snapshotTotal; + } + + + public void setSnapshotTotal(Long snapshotTotal) { + this.snapshotTotal = snapshotTotal; + } + + + + + public Long getTemplateTotal() { + return templateTotal; + } + + + public void setTemplateTotal(Long templateTotal) { + this.templateTotal = templateTotal; + } + + + public Integer getVmStopped() { + return vmStopped; + } + + + public void setVmStopped(Integer vmStopped) { + this.vmStopped = vmStopped; + } + + + public Integer getVmRunning() { + return vmRunning; + } + + + public void setVmRunning(Integer vmRunning) { + this.vmRunning = vmRunning; + } + + + + public Long getProjectTotal() { + return projectTotal; + } + + + public void setProjectTotal(Long projectTotal) { + this.projectTotal = projectTotal; + } + + + + public Long getNetworkTotal() { + return networkTotal; + } + + + public void setNetworkTotal(Long networkTotal) { + this.networkTotal = networkTotal; + } + + + + public Long getVpcTotal() { + return vpcTotal; + } + + + public void setVpcTotal(Long vpcTotal) { + this.vpcTotal = vpcTotal; + } + + + public Long getVmLimit() { + return vmLimit; + } + + + public void setVmLimit(Long vmLimit) { + this.vmLimit = vmLimit; + } + + + public Long getIpLimit() { + return ipLimit; + } + + + public void setIpLimit(Long ipLimit) { + this.ipLimit = ipLimit; + } + + + public Long getVolumeLimit() { + return volumeLimit; + } + + + public void setVolumeLimit(Long volumeLimit) { + this.volumeLimit = volumeLimit; + } + + + public Long getSnapshotLimit() { + return snapshotLimit; + } + + + public void setSnapshotLimit(Long snapshotLimit) { + this.snapshotLimit = snapshotLimit; + } + + + public Long getTemplateLimit() { + return templateLimit; + } + + + public void setTemplateLimit(Long templateLimit) { + this.templateLimit = templateLimit; + } + + + public Long getProjectLimit() { + return projectLimit; + } + + + public void setProjectLimit(Long projectLimit) { + this.projectLimit = projectLimit; + } + + + public Long getNetworkLimit() { + return networkLimit; + } + + + public void setNetworkLimit(Long networkLimit) { + this.networkLimit = networkLimit; + } + + + public Long getVpcLimit() { + return vpcLimit; + } + + + public void setVpcLimit(Long vpcLimit) { + this.vpcLimit = vpcLimit; + } + + + public long getJobId() { + return jobId; + } + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + public String getJobUuid() { + return jobUuid; + } + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + public int getJobStatus() { + return jobStatus; + } + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + +} diff --git a/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java b/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java new file mode 100644 index 00000000000..39bcb1777e6 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java @@ -0,0 +1,333 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.async.AsyncJob.Type; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="async_job_view") +public class AsyncJobJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + @Column(name="user_id") + private long userId; + + @Column(name="user_uuid") + private String userUuid; + + @Column(name="job_cmd") + private String cmd; + + @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; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Enumerated(value=EnumType.STRING) + @Column(name="instance_type", length=64) + private Type instanceType; + + @Column(name="instance_id", length=64) + private Long instanceId; + + @Column(name="instance_uuid") + private String instanceUuid; + + + public AsyncJobJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + public String getAccountUuid() { + return accountUuid; + } + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public long getUserId() { + return userId; + } + + + public void setUserId(long userId) { + this.userId = userId; + } + + + public String getUserUuid() { + return userUuid; + } + + + public void setUserUuid(String userUuid) { + this.userUuid = userUuid; + } + + + public String getCmd() { + return cmd; + } + + + public void setCmd(String cmd) { + this.cmd = cmd; + } + + + public int getStatus() { + return status; + } + + + public void setStatus(int status) { + this.status = status; + } + + + public int getProcessStatus() { + return processStatus; + } + + + public void setProcessStatus(int processStatus) { + this.processStatus = processStatus; + } + + + public int getResultCode() { + return resultCode; + } + + + public void setResultCode(int resultCode) { + this.resultCode = resultCode; + } + + + public String getResult() { + return result; + } + + + public void setResult(String result) { + this.result = result; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public Type getInstanceType() { + return instanceType; + } + + + public void setInstanceType(Type instanceType) { + this.instanceType = instanceType; + } + + + public Long getInstanceId() { + return instanceId; + } + + + public void setInstanceId(Long instanceId) { + this.instanceId = instanceId; + } + + + public String getInstanceUuid() { + return instanceUuid; + } + + + public void setInstanceUuid(String instanceUuid) { + this.instanceUuid = instanceUuid; + } + +} diff --git a/api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java b/server/src/com/cloud/api/query/vo/BaseViewVO.java similarity index 54% rename from api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java rename to server/src/com/cloud/api/query/vo/BaseViewVO.java index af90df9282b..6b1ddd6561a 100644 --- a/api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java +++ b/server/src/com/cloud/api/query/vo/BaseViewVO.java @@ -14,29 +14,34 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package com.cloud.api.query.vo; -import org.apache.log4j.Logger; +public abstract class BaseViewVO { -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.template.VirtualMachineTemplate; + public abstract long getId(); -public class ListTemplatePermissionsCmd extends ListTemplateOrIsoPermissionsCmd { - protected String getResponseName() { - return "listtemplatepermissionsresponse"; + public abstract void setId(long id); + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (getId() ^ (getId() >>> 32)); + return result; } - - @Override - public String getMediaType() { - return "template"; + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BaseViewVO other = (BaseViewVO) obj; + if (getId() != other.getId()) + return false; + return true; } - - @Override - protected Logger getLogger() { - return Logger.getLogger(ListTemplatePermissionsCmd.class.getName()); - } - - protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return !template.getFormat().equals(ImageFormat.ISO); - } } diff --git a/server/src/com/cloud/api/query/vo/ControlledViewEntity.java b/server/src/com/cloud/api/query/vo/ControlledViewEntity.java new file mode 100644 index 00000000000..12557504807 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ControlledViewEntity.java @@ -0,0 +1,48 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import org.apache.cloudstack.acl.ControlledEntity; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * This is the interface for all VO classes representing DB views created for previous ControlledEntity. + * + * @author minc + * + */ +public interface ControlledViewEntity extends ControlledEntity, InternalIdentity, Identity { + + public String getDomainPath(); + + public short getAccountType(); + + public String getAccountUuid(); + + public String getAccountName(); + + public String getDomainUuid(); + + public String getDomainName(); + + public String getProjectUuid(); + + public String getProjectName(); + +} diff --git a/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java b/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java new file mode 100644 index 00000000000..a9c04586a92 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java @@ -0,0 +1,923 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.net.URI; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.Network.GuestType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.router.VirtualRouter.RedundantState; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="domain_router_view") +public class DomainRouterJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name", updatable=false, nullable=false, length=255) + private String name = null; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + /** + * Note that state is intentionally missing the setter. Any updates to + * the state machine needs to go through the DAO object because someone + * else could be updating it as well. + */ + @Enumerated(value=EnumType.STRING) + @Column(name="state", updatable=true, nullable=false, length=32) + private State state = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="instance_name", updatable=true, nullable=false) + private String instanceName; + + @Column(name="pod_id", updatable=true, nullable=false) + private Long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName = null; + + @Column(name="dns1") + private String dns1 = null; + + @Column(name="dns2") + private String dns2 = null; + + + @Column(name="host_id", updatable=true, nullable=true) + private long hostId; + + @Column(name="host_uuid") + private String hostUuid; + + @Column(name="host_name", nullable=false) + private String hostName; + + @Column(name="template_id", updatable=true, nullable=true, length=17) + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="service_offering_id") + private long serviceOfferingId; + + @Column(name="service_offering_uuid") + private String serviceOfferingUuid; + + @Column(name="service_offering_name") + private String serviceOfferingName; + + + @Column(name = "vpc_id") + private long vpcId; + + @Column(name = "vpc_uuid") + private String vpcUuid; + + @Column(name = "nic_id") + private long nicId; + + @Column(name = "nic_uuid") + private String nicUuid; + + @Column(name = "is_default_nic") + private boolean isDefaultNic; + + @Column(name = "ip_address") + private String ipAddress; + + @Column(name = "gateway") + private String gateway; + + @Column(name = "netmask") + private String netmask; + + @Column(name = "mac_address") + private String macAddress; + + @Column(name = "broadcast_uri") + private URI broadcastUri; + + @Column(name = "isolation_uri") + private URI isolationUri; + + @Column(name="network_id") + private long networkId; + + @Column(name="network_uuid") + private String networkUuid; + + @Column(name="network_name") + private String networkName; + + @Column(name="network_domain") + private String networkDomain; + + @Column(name="traffic_type") + @Enumerated(value=EnumType.STRING) + private TrafficType trafficType; + + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + + @Column(name="uuid") + private String uuid; + + @Column(name="template_version") + private String templateVersion; + + @Column(name="scripts_version") + private String scriptsVersion; + + @Column(name="redundant_state") + @Enumerated(EnumType.STRING) + private RedundantState redundantState; + + @Column(name="is_redundant_router") + boolean isRedundantRouter; + + @Column(name="guest_type") + @Enumerated(value=EnumType.STRING) + private GuestType guestType; + + + public DomainRouterJoinVO() { + } + + + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + + + + @Override + public String getUuid() { + return uuid; + } + + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + + + @Override + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + + @Override + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + @Override + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + @Override + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + + @Override + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public String getInstanceName() { + return instanceName; + } + + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public String getPodUuid() { + return podUuid; + } + + + + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + public void setDataCenterUuid(String zoneUuid) { + this.dataCenterUuid = zoneUuid; + } + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String zoneName) { + this.dataCenterName = zoneName; + } + + + public Long getHostId() { + return hostId; + } + + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + + public String getHostUuid() { + return hostUuid; + } + + + + + public void setHostUuid(String hostUuid) { + this.hostUuid = hostUuid; + } + + + + + public String getHostName() { + return hostName; + } + + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + + public long getTemplateId() { + return templateId; + } + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + + + public String getServiceOfferingUuid() { + return serviceOfferingUuid; + } + + + public void setServiceOfferingUuid(String serviceOfferingUuid) { + this.serviceOfferingUuid = serviceOfferingUuid; + } + + + + + public String getServiceOfferingName() { + return serviceOfferingName; + } + + + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } + + public long getVpcId() { + return vpcId; + } + + public void setVpcId(long vpcId) { + this.vpcId = vpcId; + } + + + + + public long getNicId() { + return nicId; + } + + + public void setNicId(long nicId) { + this.nicId = nicId; + } + + + public boolean isDefaultNic() { + return isDefaultNic; + } + + + public void setDefaultNic(boolean isDefaultNic) { + this.isDefaultNic = isDefaultNic; + } + + + public String getIpAddress() { + return ipAddress; + } + + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + + public String getGateway() { + return gateway; + } + + + public void setGateway(String gateway) { + this.gateway = gateway; + } + + + public String getNetmask() { + return netmask; + } + + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + + public String getMacAddress() { + return macAddress; + } + + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + + public URI getBroadcastUri() { + return broadcastUri; + } + + + public void setBroadcastUri(URI broadcastUri) { + this.broadcastUri = broadcastUri; + } + + + public URI getIsolationUri() { + return isolationUri; + } + + + public void setIsolationUri(URI isolationUri) { + this.isolationUri = isolationUri; + } + + + public long getNetworkId() { + return networkId; + } + + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } + + + public String getNetworkName() { + return networkName; + } + + + + + public void setNetworkName(String networkName) { + this.networkName = networkName; + } + + + + + public String getNetworkDomain() { + return networkDomain; + } + + + + + public void setNetworkDomain(String networkDomain) { + this.networkDomain = networkDomain; + } + + + + + public TrafficType getTrafficType() { + return trafficType; + } + + + public void setTrafficType(TrafficType trafficType) { + this.trafficType = trafficType; + } + + + + public long getServiceOfferingId() { + return serviceOfferingId; + } + + + + + public void setServiceOfferingId(long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + + + + public long getProjectId() { + return projectId; + } + + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + + @Override + public String getProjectName() { + return projectName; + } + + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + + + public String getVpcUuid() { + return vpcUuid; + } + + + + + public void setVpcUuid(String vpcUuid) { + this.vpcUuid = vpcUuid; + } + + + + + public String getNicUuid() { + return nicUuid; + } + + + + + public void setNicUuid(String nicUuid) { + this.nicUuid = nicUuid; + } + + + + + public String getNetworkUuid() { + return networkUuid; + } + + + + + public void setNetworkUuid(String networkUuid) { + this.networkUuid = networkUuid; + } + + + public long getJobId() { + return jobId; + } + + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + + public String getJobUuid() { + return jobUuid; + } + + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + + public int getJobStatus() { + return jobStatus; + } + + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + public Long getPodId() { + return podId; + } + + + + + public void setPodId(Long podId) { + this.podId = podId; + } + + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + + public void setDataCenterId(long zoneId) { + this.dataCenterId = zoneId; + } + + + + + public String getDns1() { + return dns1; + } + + + + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + + + + public String getDns2() { + return dns2; + } + + + + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + + + + public String getTemplateVersion() { + return templateVersion; + } + + + + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + + + + public String getScriptsVersion() { + return scriptsVersion; + } + + + + + public void setScriptsVersion(String scriptsVersion) { + this.scriptsVersion = scriptsVersion; + } + + + + + public RedundantState getRedundantState() { + return redundantState; + } + + + + + public void setRedundantState(RedundantState redundantState) { + this.redundantState = redundantState; + } + + + + + public boolean isRedundantRouter() { + return isRedundantRouter; + } + + + + + public void setRedundantRouter(boolean isRedundantRouter) { + this.isRedundantRouter = isRedundantRouter; + } + + + + + public GuestType getGuestType() { + return guestType; + } + + + + + public void setGuestType(GuestType guestType) { + this.guestType = guestType; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/EventJoinVO.java b/server/src/com/cloud/api/query/vo/EventJoinVO.java new file mode 100644 index 00000000000..f29a942a59f --- /dev/null +++ b/server/src/com/cloud/api/query/vo/EventJoinVO.java @@ -0,0 +1,317 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import com.cloud.event.Event.State; + +@Entity +@Table(name="event_view") +public class EventJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="type") + private String type; + + @Enumerated(value=EnumType.STRING) + @Column(name="state") + private State state; + + @Column(name="description") + private String description; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date createDate; + + @Column(name="user_id") + private long userId; + + @Column(name="user_name") + private String userName; + + @Column(name="level") + private String level; + + @Column(name="start_id") + private long startId; + + @Column(name="start_uuid") + private String startUuid; + + @Column(name="parameters", length=1024) + private String parameters; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public EventJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getStartId() { + return startId; + } + + public void setStartId(long startId) { + this.startId = startId; + } + + + public String getStartUuid() { + return startUuid; + } + + public void setStartUuid(String startUuid) { + this.startUuid = startUuid; + } + + public String getParameters() { + return parameters; + } + + public void setParameters(String parameters) { + this.parameters = parameters; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/HostJoinVO.java b/server/src/com/cloud/api/query/vo/HostJoinVO.java new file mode 100644 index 00000000000..a3796b97eba --- /dev/null +++ b/server/src/com/cloud/api/query/vo/HostJoinVO.java @@ -0,0 +1,509 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import com.cloud.host.Status; +import com.cloud.host.Host.Type; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.org.Cluster; +import com.cloud.resource.ResourceState; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * Host DB view. + * @author minc + * + */ +@Entity +@Table(name="host_view") +public class HostJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + + @Column(name="status") + private Status status = null; + + @Column(name="type") + @Enumerated(value=EnumType.STRING) + private Type type; + + @Column(name="private_ip_address") + private String privateIpAddress; + + @Column(name="disconnected") + @Temporal(value=TemporalType.TIMESTAMP) + private Date disconnectedOn; + + @Column(name="version") + private String version; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + @Column(name="hypervisor_version") + private String hypervisorVersion; + + @Column(name="capabilities") + private String caps; + + @Column(name="last_ping") + private long lastPinged; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="resource_state") + @Enumerated(value=EnumType.STRING) + private ResourceState resourceState; + + @Column(name="mgmt_server_id") + private Long managementServerId; + + @Column(name="cpus") + private Integer cpus; + + @Column(name="speed") + private Long speed; + + @Column(name="ram") + private long totalMemory; + + @Column(name="cluster_id") + private long clusterId; + + @Column(name="cluster_uuid") + private String clusterUuid; + + @Column(name="cluster_name") + private String clusterName; + + @Column(name="cluster_type") + @Enumerated(value=EnumType.STRING) + Cluster.ClusterType clusterType; + + @Column(name="data_center_id") + private long zoneId; + + @Column(name="data_center_uuid") + private String zoneUuid; + + @Column(name="data_center_name") + private String zoneName; + + @Column(name="pod_id") + private long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="pod_name") + private String podName; + + + @Column(name="guest_os_category_id") + private long osCategoryId; + + @Column(name="guest_os_category_uuid") + private String osCategoryUuid; + + @Column(name="guest_os_category_name") + private String osCategoryName; + + @Column(name="tag") + private String tag; + + @Column(name="memory_used_capacity") + private long memUsedCapacity; + + @Column(name="memory_reserved_capacity") + private long memReservedCapacity; + + @Column(name="cpu_used_capacity") + private long cpuUsedCapacity; + + @Column(name="cpu_reserved_capacity") + private long cpuReservedCapacity; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + + /* (non-Javadoc) + * @see com.cloud.api.query.vo.BaseViewVO#getId() + */ + @Override + public long getId() { + return this.id; + } + + /* (non-Javadoc) + * @see com.cloud.api.query.vo.BaseViewVO#setId(long) + */ + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public long getZoneId() { + return zoneId; + } + + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public String getZoneUuid() { + return zoneUuid; + } + + public void setZoneUuid(String zoneUuid) { + this.zoneUuid = zoneUuid; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + public String getPrivateIpAddress() { + return privateIpAddress; + } + + public void setPrivateIpAddress(String privateIpAddress) { + this.privateIpAddress = privateIpAddress; + } + + public Date getDisconnectedOn() { + return disconnectedOn; + } + + public void setDisconnectedOn(Date disconnectedOn) { + this.disconnectedOn = disconnectedOn; + } + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + public String getHypervisorVersion() { + return hypervisorVersion; + } + + public void setHypervisorVersion(String hypervisorVersion) { + this.hypervisorVersion = hypervisorVersion; + } + + public String getCapabilities() { + return caps; + } + + public void setCapabilities(String caps) { + this.caps = caps; + } + + public long getLastPinged() { + return lastPinged; + } + + public void setLastPinged(long lastPinged) { + this.lastPinged = lastPinged; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public ResourceState getResourceState() { + return resourceState; + } + + public void setResourceState(ResourceState resourceState) { + this.resourceState = resourceState; + } + + public Long getManagementServerId() { + return managementServerId; + } + + public void setManagementServerId(Long managementServerId) { + this.managementServerId = managementServerId; + } + + public Integer getCpus() { + return cpus; + } + + public void setCpus(Integer cpus) { + this.cpus = cpus; + } + + public Long getSpeed() { + return speed; + } + + public void setSpeed(Long speed) { + this.speed = speed; + } + + public long getTotalMemory() { + return totalMemory; + } + + public void setTotalMemory(long totalMemory) { + this.totalMemory = totalMemory; + } + + public long getClusterId() { + return clusterId; + } + + public void setClusterId(long clusterId) { + this.clusterId = clusterId; + } + + public String getClusterUuid() { + return clusterUuid; + } + + public void setClusterUuid(String clusterUuid) { + this.clusterUuid = clusterUuid; + } + + public String getClusterName() { + return clusterName; + } + + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + public Cluster.ClusterType getClusterType() { + return clusterType; + } + + public void setClusterType(Cluster.ClusterType clusterType) { + this.clusterType = clusterType; + } + + public long getOsCategoryId() { + return osCategoryId; + } + + public void setOsCategoryId(long osCategoryId) { + this.osCategoryId = osCategoryId; + } + + public String getOsCategoryUuid() { + return osCategoryUuid; + } + + public void setOsCategoryUuid(String osCategoryUuid) { + this.osCategoryUuid = osCategoryUuid; + } + + public String getOsCategoryName() { + return osCategoryName; + } + + public void setOsCategoryName(String osCategoryName) { + this.osCategoryName = osCategoryName; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + public long getPodId() { + return podId; + } + + public void setPodId(long podId) { + this.podId = podId; + } + + public String getPodUuid() { + return podUuid; + } + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + public String getPodName() { + return podName; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public long getMemUsedCapacity() { + return memUsedCapacity; + } + + public void setMemUsedCapacity(long memUsedCapacity) { + this.memUsedCapacity = memUsedCapacity; + } + + public long getMemReservedCapacity() { + return memReservedCapacity; + } + + public void setMemReservedCapacity(long memReservedCapacity) { + this.memReservedCapacity = memReservedCapacity; + } + + public long getCpuUsedCapacity() { + return cpuUsedCapacity; + } + + public void setCpuUsedCapacity(long cpuUsedCapacity) { + this.cpuUsedCapacity = cpuUsedCapacity; + } + + public long getCpuReservedCapacity() { + return cpuReservedCapacity; + } + + public void setCpuReservedCapacity(long cpuReservedCapacity) { + this.cpuReservedCapacity = cpuReservedCapacity; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java b/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java new file mode 100644 index 00000000000..3fb43094ad3 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java @@ -0,0 +1,233 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="instance_group_view") +public class InstanceGroupJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + String name; + + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public InstanceGroupJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java new file mode 100644 index 00000000000..1a8818a22e4 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java @@ -0,0 +1,216 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.projects.ProjectAccount.Role; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="project_account_view") +public class ProjectAccountJoinVO extends BaseViewVO implements InternalIdentity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName; + + @Column(name="account_type") + private short accountType; + + @Column(name="account_role") + @Enumerated(value=EnumType.STRING) + private Role accountRole; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + public ProjectAccountJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + + public String getAccountUuid() { + return accountUuid; + } + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + public String getAccountName() { + return accountName; + } + + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + + public short getAccountType() { + return accountType; + } + + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + + public Role getAccountRole() { + return accountRole; + } + + + + public void setAccountRole(Role accountRole) { + this.accountRole = accountRole; + } + + + + public long getProjectId() { + return projectId; + } + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + public String getProjectUuid() { + return projectUuid; + } + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + public String getProjectName() { + return projectName; + } + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java new file mode 100644 index 00000000000..a60c9370530 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java @@ -0,0 +1,235 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="project_invitation_view") +public class ProjectInvitationJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name = "email") + private String email; + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private State state; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + public ProjectInvitationJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectJoinVO.java new file mode 100644 index 00000000000..73ec9313289 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectJoinVO.java @@ -0,0 +1,304 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="project_view") +public class ProjectJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="display_text") + String displayText; + + + @Column(name="owner") + String owner; + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + private State state; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + public ProjectJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public long getTagId() { + return tagId; + } + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + public String getTagUuid() { + return tagUuid; + } + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + public String getTagKey() { + return tagKey; + } + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public long getTagDomainId() { + return tagDomainId; + } + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + public long getTagAccountId() { + return tagAccountId; + } + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + public long getTagResourceId() { + return tagResourceId; + } + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + public String getTagCustomer() { + return tagCustomer; + } + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + +} diff --git a/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java b/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java new file mode 100644 index 00000000000..9ce9555d1be --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java @@ -0,0 +1,268 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.server.ResourceTag.TaggedResourceType; + +@Entity +@Table(name="resource_tag_view") +public class ResourceTagJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="key") + private String key; + + @Column(name="value") + String value; + + + @Column(name="resource_id") + long resourceId; + + @Column(name="resource_uuid") + private String resourceUuid; + + @Column(name="resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType resourceType; + + @Column(name="customer") + String customer; + + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public ResourceTagJoinVO() { + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public long getResourceId() { + return resourceId; + } + + public void setResourceId(long resourceId) { + this.resourceId = resourceId; + } + + public String getResourceUuid() { + return resourceUuid; + } + + public void setResourceUuid(String resourceUuid) { + this.resourceUuid = resourceUuid; + } + + public TaggedResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(TaggedResourceType resourceType) { + this.resourceType = resourceType; + } + + public String getCustomer() { + return customer; + } + + public void setCustomer(String customer) { + this.customer = customer; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java b/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java new file mode 100644 index 00000000000..922e130ed30 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java @@ -0,0 +1,452 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.security.SecurityRule.SecurityRuleType; +import com.cloud.server.ResourceTag.TaggedResourceType; + +@Entity +@Table(name="security_group_view") +public class SecurityGroupJoinVO extends BaseViewVO implements ControlledViewEntity{ + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "uuid") + private String uuid; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name = "rule_id") + private Long ruleId; + + @Column(name = "rule_uuid") + private String ruleUuid; + + @Column(name = "rule_start_port") + private int ruleStartPort; + + @Column(name = "rule_end_port") + private int ruleEndPort; + + @Column(name = "rule_protocol") + private String ruleProtocol; + + @Column(name = "rule_type") + private String ruleType; + + @Column(name = "rule_allowed_network_id") + private Long ruleAllowedNetworkId = null; + + @Column(name = "rule_allowed_ip_cidr") + private String ruleAllowedSourceIpCidr = null; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + public SecurityGroupJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Long getRuleId() { + return ruleId; + } + + public void setRuleId(Long ruleId) { + this.ruleId = ruleId; + } + + public String getRuleUuid() { + return ruleUuid; + } + + public void setRuleUuid(String ruleUuid) { + this.ruleUuid = ruleUuid; + } + + public int getRuleStartPort() { + return ruleStartPort; + } + + public void setRuleStartPort(int ruleStartPort) { + this.ruleStartPort = ruleStartPort; + } + + public int getRuleEndPort() { + return ruleEndPort; + } + + public void setRuleEndPort(int ruleEndPort) { + this.ruleEndPort = ruleEndPort; + } + + public String getRuleProtocol() { + return ruleProtocol; + } + + public void setRuleProtocol(String ruleProtocol) { + this.ruleProtocol = ruleProtocol; + } + + public SecurityRuleType getRuleType() { + if ("ingress".equalsIgnoreCase(ruleType)) { + return SecurityRuleType.IngressRule; + } else { + return SecurityRuleType.EgressRule; + } + } + + public void setRuleType(String ruleType) { + this.ruleType = ruleType; + } + + public Long getRuleAllowedNetworkId() { + return ruleAllowedNetworkId; + } + + public void setRuleAllowedNetworkId(Long ruleAllowedNetworkId) { + this.ruleAllowedNetworkId = ruleAllowedNetworkId; + } + + public String getRuleAllowedSourceIpCidr() { + return ruleAllowedSourceIpCidr; + } + + public void setRuleAllowedSourceIpCidr(String ruleAllowedSourceIpCidr) { + this.ruleAllowedSourceIpCidr = ruleAllowedSourceIpCidr; + } + + public long getTagId() { + return tagId; + } + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + public String getTagUuid() { + return tagUuid; + } + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + public String getTagKey() { + return tagKey; + } + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public long getTagDomainId() { + return tagDomainId; + } + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + public long getTagAccountId() { + return tagAccountId; + } + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + public long getTagResourceId() { + return tagResourceId; + } + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + public String getTagCustomer() { + return tagCustomer; + } + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + +} diff --git a/server/src/com/cloud/api/query/vo/StoragePoolJoinVO.java b/server/src/com/cloud/api/query/vo/StoragePoolJoinVO.java new file mode 100644 index 00000000000..fd837bd5d88 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/StoragePoolJoinVO.java @@ -0,0 +1,341 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import com.cloud.org.Cluster; +import com.cloud.storage.StoragePoolStatus; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * Storage Pool DB view. + * @author minc + * + */ +@Entity +@Table(name="storage_pool_view") +public class StoragePoolJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="path") + private String path; + + @Column(name="host_address") + private String hostAddress; + + + @Column(name="status") + @Enumerated(value=EnumType.STRING) + private StoragePoolStatus status; + + @Column(name="pool_type") + @Enumerated(value=EnumType.STRING) + private StoragePoolType poolType; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="capacity_bytes") + private long capacityBytes; + + @Column(name="cluster_id") + private long clusterId; + + @Column(name="cluster_uuid") + private String clusterUuid; + + @Column(name="cluster_name") + private String clusterName; + + @Column(name="cluster_type") + @Enumerated(value=EnumType.STRING) + private Cluster.ClusterType clusterType; + + @Column(name="data_center_id") + private long zoneId; + + @Column(name="data_center_uuid") + private String zoneUuid; + + @Column(name="data_center_name") + private String zoneName; + + @Column(name="pod_id") + private long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="pod_name") + private String podName; + + + @Column(name="tag") + private String tag; + + @Column(name="disk_used_capacity") + private long usedCapacity; + + @Column(name="disk_reserved_capacity") + private long reservedCapacity; + + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getHostAddress() { + return hostAddress; + } + + public void setHostAddress(String hostAddress) { + this.hostAddress = hostAddress; + } + + public StoragePoolStatus getStatus() { + return status; + } + + public void setStatus(StoragePoolStatus status) { + this.status = status; + } + + public StoragePoolType getPoolType() { + return poolType; + } + + public void setPoolType(StoragePoolType poolType) { + this.poolType = poolType; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public long getCapacityBytes() { + return capacityBytes; + } + + public void setCapacityBytes(long capacityBytes) { + this.capacityBytes = capacityBytes; + } + + public long getClusterId() { + return clusterId; + } + + public void setClusterId(long clusterId) { + this.clusterId = clusterId; + } + + public String getClusterUuid() { + return clusterUuid; + } + + public void setClusterUuid(String clusterUuid) { + this.clusterUuid = clusterUuid; + } + + public String getClusterName() { + return clusterName; + } + + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + public Cluster.ClusterType getClusterType() { + return clusterType; + } + + public void setClusterType(Cluster.ClusterType clusterType) { + this.clusterType = clusterType; + } + + public long getZoneId() { + return zoneId; + } + + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public String getZoneUuid() { + return zoneUuid; + } + + public void setZoneUuid(String zoneUuid) { + this.zoneUuid = zoneUuid; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public long getPodId() { + return podId; + } + + public void setPodId(long podId) { + this.podId = podId; + } + + public String getPodUuid() { + return podUuid; + } + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + public String getPodName() { + return podName; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + public long getUsedCapacity() { + return usedCapacity; + } + + public void setUsedCapacity(long usedCapacity) { + this.usedCapacity = usedCapacity; + } + + public long getReservedCapacity() { + return reservedCapacity; + } + + public void setReservedCapacity(long reservedCapacity) { + this.reservedCapacity = reservedCapacity; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java b/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java new file mode 100644 index 00000000000..44637db3400 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java @@ -0,0 +1,350 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.Encrypt; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="user_view") +public class UserAccountJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @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="email") + private String email = null; + + @Column(name="state") + private String state; + + @Column(name="api_key") + private String apiKey = null; + + @Encrypt + @Column(name="secret_key") + 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; + + @Column(name="registration_token") + private String registrationToken = null; + + @Column(name="is_registered") + boolean registered; + + @Column (name="incorrect_login_attempts") + int loginAttempts; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + public UserAccountJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getRegistrationToken() { + return registrationToken; + } + + public void setRegistrationToken(String registrationToken) { + this.registrationToken = registrationToken; + } + + public boolean isRegistered() { + return registered; + } + + public void setRegistered(boolean registered) { + this.registered = registered; + } + + public int getLoginAttempts() { + return loginAttempts; + } + + public void setLoginAttempts(int loginAttempts) { + this.loginAttempts = loginAttempts; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/UserVmJoinVO.java b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java new file mode 100644 index 00000000000..025db47d599 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java @@ -0,0 +1,1614 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.net.URI; +import java.util.Date; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.storage.Volume; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.utils.db.Encrypt; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="user_vm_view") +public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name", updatable=false, nullable=false, length=255) + private String name = null; + + @Column(name="display_name", updatable=false, nullable=false, length=255) + private String displayName = null; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="instance_group_id") + private long instanceGroupId; + + @Column(name="instance_group_uuid") + private String instanceGroupUuid; + + @Column(name="instance_group_name") + private String instanceGroupName; + + @Column(name="vm_type", updatable=false, nullable=false, length=32) + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.Type type; + + /** + * Note that state is intentionally missing the setter. Any updates to + * the state machine needs to go through the DAO object because someone + * else could be updating it as well. + */ + @Enumerated(value=EnumType.STRING) + @Column(name="state", updatable=true, nullable=false, length=32) + private State state = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="instance_name", updatable=true, nullable=false) + private String instanceName; + + @Column(name="guest_os_id", nullable=false, length=17) + private long guestOsId; + + @Column(name="guest_os_uuid") + private String guestOsUuid; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + @Column(name="ha_enabled", updatable=true, nullable=true) + private boolean haEnabled; + + @Encrypt + @Column(name="vnc_password", updatable=true, nullable=false, length=255) + protected String vncPassword; + + @Column(name="limit_cpu_use", updatable=true, nullable=true) + private boolean limitCpuUse; + + @Column(name="last_host_id", updatable=true, nullable=true) + private Long lastHostId; + + @Column(name="private_ip_address", updatable=true) + private String privateIpAddress; + + + @Column(name="private_mac_address", updatable=true, nullable=true) + private String privateMacAddress; + + @Column(name="pod_id", updatable=true, nullable=false) + private Long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName = null; + + @Column(name="security_group_enabled") + private boolean securityGroupEnabled; + + @Column(name="host_id", updatable=true, nullable=true) + private long hostId; + + @Column(name="host_uuid") + private String hostUuid; + + @Column(name="host_name", nullable=false) + private String hostName; + + @Column(name="template_id", updatable=true, nullable=true, length=17) + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="template_name") + private String templateName; + + @Column(name="template_display_text", length=4096) + private String templateDisplayText; + + @Column(name="password_enabled") + private boolean passwordEnabled; + + @Column(name="iso_id", updatable=true, nullable=true, length=17) + private long isoId; + + @Column(name="iso_uuid") + private String isoUuid; + + @Column(name="iso_name") + private String isoName; + + @Column(name="iso_display_text", length=4096) + private String isoDisplayText; + + @Column(name="service_offering_id") + private long serviceOfferingId; + + @Column(name="service_offering_uuid") + private String serviceOfferingUuid; + + @Column(name="service_offering_name") + private String serviceOfferingName; + + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="pool_id", updatable=false, nullable = false) + private long poolId; + + @Column(name="pool_uuid") + private String poolUuid; + + @Column(name="pool_type", updatable=false, nullable=false, length=32) + @Enumerated(value=EnumType.STRING) + private StoragePoolType poolType; + + @Column(name = "volume_id") + private long volume_id; + + @Column(name = "volume_uuid") + private String volume_uuid; + + @Column(name = "volume_device_id") + private Long volumeDeviceId = null; + + @Column(name = "volume_type") + @Enumerated(EnumType.STRING) + private Volume.Type volumeType; + + @Column(name = "security_group_id") + private long securityGroupId; + + @Column(name = "security_group_uuid") + private String securityGroupUuid; + + @Column(name = "security_group_name") + private String securityGroupName; + + @Column(name = "security_group_description") + private String securityGroupDescription; + + @Column(name = "vpc_id") + private long vpcId; + + @Column(name = "vpc_uuid") + private String vpcUuid; + + @Column(name = "nic_id") + private long nicId; + + @Column(name = "nic_uuid") + private String nicUuid; + + @Column(name = "is_default_nic") + private boolean isDefaultNic; + + @Column(name = "ip_address") + private String ipAddress; + + @Column(name = "gateway") + private String gateway; + + @Column(name = "netmask") + private String netmask; + + @Column(name = "mac_address") + private String macAddress; + + @Column(name = "broadcast_uri") + private URI broadcastUri; + + @Column(name = "isolation_uri") + private URI isolationUri; + + @Column(name="network_id") + private long networkId; + + @Column(name="network_uuid") + private String networkUuid; + + @Column(name="traffic_type") + @Enumerated(value=EnumType.STRING) + private TrafficType trafficType; + + @Column(name="guest_type") + @Enumerated(value=EnumType.STRING) + private GuestType guestType; + + @Column(name = "public_ip_id") + private long publicIpId; + + @Column(name = "public_ip_uuid") + private String publicIpUuid; + + @Column(name = "public_ip_address") + private String publicIpAddress; + + @Column(name="user_data", updatable=true, nullable=true, length=2048) + private String userData; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="keypair_name") + private String keypairName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + transient String password; + + @Transient + Map details; + + @Column(name="uuid") + private String uuid; + + public UserVmJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public String getDisplayName() { + return displayName; + } + + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + + @Override + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + + @Override + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + @Override + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + @Override + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + + @Override + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + @Override + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + + + public long getInstanceGroupId() { + return instanceGroupId; + } + + + public void setInstanceGroupId(long instanceGroupId) { + this.instanceGroupId = instanceGroupId; + } + + + public String getInstanceGroupUuid() { + return instanceGroupUuid; + } + + + + + public void setInstanceGroupUuid(String instanceGroupUuid) { + this.instanceGroupUuid = instanceGroupUuid; + } + + + + + public String getInstanceGroupName() { + return instanceGroupName; + } + + + public void setInstanceGroupName(String instanceGroupName) { + this.instanceGroupName = instanceGroupName; + } + + + public VirtualMachine.Type getType() { + return type; + } + + + + + public void setType(VirtualMachine.Type type) { + this.type = type; + } + + + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public String getInstanceName() { + return instanceName; + } + + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public long getGuestOSId() { + return guestOsId; + } + + + public void setGuestOSId(long guestOSId) { + this.guestOsId = guestOSId; + } + + + public String getGuestOsUuid() { + return guestOsUuid; + } + + + + + public void setGuestOsUuid(String guestOsUuid) { + this.guestOsUuid = guestOsUuid; + } + + + + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + + public boolean isHaEnabled() { + return haEnabled; + } + + + public void setHaEnabled(boolean haEnabled) { + this.haEnabled = haEnabled; + } + + public void setVncPassword(String vncPassword) { + this.vncPassword = vncPassword; + } + + public String getVncPassword() { + return vncPassword; + } + + + + + public String getPrivateIpAddress() { + return privateIpAddress; + } + + + + + public void setPrivateIpAddress(String privateIpAddress) { + this.privateIpAddress = privateIpAddress; + } + + + + + public String getPrivateMacAddress() { + return privateMacAddress; + } + + + + + public void setPrivateMacAddress(String privateMacAddress) { + this.privateMacAddress = privateMacAddress; + } + + + + + public Long getLastHostId() { + return lastHostId; + } + + + + + public void setLastHostId(Long lastHostId) { + this.lastHostId = lastHostId; + } + + + + + + + public Long getPodId() { + return podId; + } + + + + + public void setPodId(Long podIdToDeployIn) { + this.podId = podIdToDeployIn; + } + + + + + public String getPodUuid() { + return podUuid; + } + + + + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + + public void setDataCenterId(long dataCenterIdToDeployIn) { + this.dataCenterId = dataCenterIdToDeployIn; + } + + + public boolean limitCpuUse() { + return limitCpuUse; + } + + public void setLimitCpuUse(boolean value) { + limitCpuUse = value; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + + + public void setDataCenterUuid(String zoneUuid) { + this.dataCenterUuid = zoneUuid; + } + + + + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String zoneName) { + this.dataCenterName = zoneName; + } + + + public boolean isSecurityGroupEnabled() { + return securityGroupEnabled; + } + + + public void setSecurityGroupEnabled(boolean securityGroupEnabled) { + this.securityGroupEnabled = securityGroupEnabled; + } + + + public Long getHostId() { + return hostId; + } + + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + + public String getHostUuid() { + return hostUuid; + } + + + + + public void setHostUuid(String hostUuid) { + this.hostUuid = hostUuid; + } + + + + + public String getHostName() { + return hostName; + } + + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + + public long getTemplateId() { + return templateId; + } + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + + public String getTemplateName() { + return templateName; + } + + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + + public String getTemplateDisplayText() { + return templateDisplayText; + } + + + public void setTemplateDisplayText(String templateDisplayText) { + this.templateDisplayText = templateDisplayText; + } + + + public boolean isPasswordEnabled() { + return passwordEnabled; + } + + + public void setPasswordEnabled(boolean passwordEnabled) { + this.passwordEnabled = passwordEnabled; + } + + + public Long getIsoId() { + return isoId; + } + + + public void setIsoId(long isoId) { + this.isoId = isoId; + } + + + public String getIsoUuid() { + return isoUuid; + } + + + + + public void setIsoUuid(String isoUuid) { + this.isoUuid = isoUuid; + } + + + + + public String getIsoName() { + return isoName; + } + + + public void setIsoName(String isoName) { + this.isoName = isoName; + } + + + public String getIsoDisplayText() { + return isoDisplayText; + } + + public void setIsoDisplayText(String isoDisplayText) { + this.isoDisplayText = isoDisplayText; + } + + + + + public String getServiceOfferingUuid() { + return serviceOfferingUuid; + } + + + + + public void setServiceOfferingUuid(String serviceOfferingUuid) { + this.serviceOfferingUuid = serviceOfferingUuid; + } + + + + + public String getServiceOfferingName() { + return serviceOfferingName; + } + + + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } + + + public int getCpu() { + return cpu; + } + + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + + public int getSpeed() { + return speed; + } + + + public void setSpeed(int speed) { + this.speed = speed; + } + + + public int getRamSize() { + return ramSize; + } + + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + + public long getPoolId() { + return poolId; + } + + + public void setPoolId(long poolId) { + this.poolId = poolId; + } + + + public StoragePoolType getPoolType() { + return poolType; + } + + + public void setPoolType(StoragePoolType poolType) { + this.poolType = poolType; + } + + + public long getVolume_id() { + return volume_id; + } + + + public void setVolume_id(long volume_id) { + this.volume_id = volume_id; + } + + + public Long getVolumeDeviceId() { + return volumeDeviceId; + } + + + public void setVolumeDeviceId(Long volumeDeviceId) { + this.volumeDeviceId = volumeDeviceId; + } + + + public Volume.Type getVolumeType() { + return volumeType; + } + + + public void setVolumeType(Volume.Type volumeType) { + this.volumeType = volumeType; + } + + + public long getSecurityGroupId() { + return securityGroupId; + } + + + public void setSecurityGroupId(long securityGroupId) { + this.securityGroupId = securityGroupId; + } + + + public String getSecurityGroupName() { + return securityGroupName; + } + + + public void setSecurityGroupName(String securityGroupName) { + this.securityGroupName = securityGroupName; + } + + + public String getSecurityGroupDescription() { + return securityGroupDescription; + } + + + public void setSecurityGroupDescription(String securityGroupDescription) { + this.securityGroupDescription = securityGroupDescription; + } + + + public long getVpcId() { + return vpcId; + } + + + + public void setVpcId(long vpcId) { + this.vpcId = vpcId; + } + + + + + public long getNicId() { + return nicId; + } + + + public void setNicId(long nicId) { + this.nicId = nicId; + } + + + public boolean isDefaultNic() { + return isDefaultNic; + } + + + public void setDefaultNic(boolean isDefaultNic) { + this.isDefaultNic = isDefaultNic; + } + + + public String getIpAddress() { + return ipAddress; + } + + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + + public String getGateway() { + return gateway; + } + + + public void setGateway(String gateway) { + this.gateway = gateway; + } + + + public String getNetmask() { + return netmask; + } + + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + + public String getMacAddress() { + return macAddress; + } + + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + + public URI getBroadcastUri() { + return broadcastUri; + } + + + public void setBroadcastUri(URI broadcastUri) { + this.broadcastUri = broadcastUri; + } + + + public URI getIsolationUri() { + return isolationUri; + } + + + public void setIsolationUri(URI isolationUri) { + this.isolationUri = isolationUri; + } + + + public long getNetworkId() { + return networkId; + } + + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } + + + public TrafficType getTrafficType() { + return trafficType; + } + + + public void setTrafficType(TrafficType trafficType) { + this.trafficType = trafficType; + } + + + public GuestType getGuestType() { + return guestType; + } + + + public void setGuestType(GuestType guestType) { + this.guestType = guestType; + } + + + public long getPublicIpId() { + return publicIpId; + } + + + + + public void setPublicIpId(long publicIpId) { + this.publicIpId = publicIpId; + } + + + + + public String getPublicIpAddress() { + return publicIpAddress; + } + + + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } + + + + public long getServiceOfferingId() { + return serviceOfferingId; + } + + + + + public void setServiceOfferingId(long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + + 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 setUserData(String userData) { + this.userData = userData; + } + + public String getUserData() { + return userData; + } + + + + public long getGuestOsId() { + return guestOsId; + } + + + + + public void setGuestOsId(long guestOsId) { + this.guestOsId = guestOsId; + } + + + + + public long getProjectId() { + return projectId; + } + + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + + @Override + public String getProjectName() { + return projectName; + } + + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + public String getKeypairName() { + return keypairName; + } + + + + + public void setKeypairName(String keypairName) { + this.keypairName = keypairName; + } + + + + + public long getTagId() { + return tagId; + } + + + + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + + + + public String getTagUuid() { + return tagUuid; + } + + + + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + + + + public String getTagKey() { + return tagKey; + } + + + + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + + + + public String getTagValue() { + return tagValue; + } + + + + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + + + + public long getTagDomainId() { + return tagDomainId; + } + + + + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + + + + public long getTagAccountId() { + return tagAccountId; + } + + + + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + + + + public long getTagResourceId() { + return tagResourceId; + } + + + + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + + + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + + + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + + + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + + + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + + + + public String getTagCustomer() { + return tagCustomer; + } + + + + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + + + + public boolean isLimitCpuUse() { + return limitCpuUse; + } + + + + public String getPoolUuid() { + return poolUuid; + } + + + + + public void setPoolUuid(String poolUuid) { + this.poolUuid = poolUuid; + } + + + + + public String getVolume_uuid() { + return volume_uuid; + } + + + + + public void setVolume_uuid(String volume_uuid) { + this.volume_uuid = volume_uuid; + } + + + + + public String getSecurityGroupUuid() { + return securityGroupUuid; + } + + + + + public void setSecurityGroupUuid(String securityGroupUuid) { + this.securityGroupUuid = securityGroupUuid; + } + + + + + public String getVpcUuid() { + return vpcUuid; + } + + + + + public void setVpcUuid(String vpcUuid) { + this.vpcUuid = vpcUuid; + } + + + + + public String getNicUuid() { + return nicUuid; + } + + + + + public void setNicUuid(String nicUuid) { + this.nicUuid = nicUuid; + } + + + + + public String getNetworkUuid() { + return networkUuid; + } + + + + + public void setNetworkUuid(String networkUuid) { + this.networkUuid = networkUuid; + } + + + + + public String getPublicIpUuid() { + return publicIpUuid; + } + + + + + public void setPublicIpUuid(String publicIpUuid) { + this.publicIpUuid = publicIpUuid; + } + + + + public long getJobId() { + return jobId; + } + + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + + public String getJobUuid() { + return jobUuid; + } + + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + + public int getJobStatus() { + return jobStatus; + } + + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + transient String toString; + @Override + public String toString() { + if (toString == null) { + toString = new StringBuilder("VM[").append(id).append("|").append(hostName).append("]").toString(); + } + return toString; + } + +} diff --git a/server/src/com/cloud/api/query/vo/VolumeJoinVO.java b/server/src/com/cloud/api/query/vo/VolumeJoinVO.java new file mode 100644 index 00000000000..4f6b35bab82 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/VolumeJoinVO.java @@ -0,0 +1,1034 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.storage.Storage; +import com.cloud.storage.Volume; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine; + +@Entity +@Table(name="volume_view") +public class VolumeJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + + @Column(name="name") + private String name; + + @Column(name = "device_id") + Long deviceId = null; + + @Column(name = "volume_type") + @Enumerated(EnumType.STRING) + Volume.Type volumeType; + + @Column(name = "size") + long size; + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private Volume.State state; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name = "attached") + @Temporal(value = TemporalType.TIMESTAMP) + Date attached; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="pod_id") + private long podId; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName; + + @Column(name="vm_id") + private long vmId; + + @Column(name="vm_uuid") + private String vmUuid; + + @Column(name="vm_name") + private String vmName; + + @Column(name="vm_display_name") + private String vmDisplayName; + + @Column(name="vm_state") + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.State vmState = null; + + @Column(name="vm_type") + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.Type vmType; + + @Column (name="volume_host_size") + private long volumeHostSize; + + @Column(name="volume_host_created") + private Date volumeHostCreated; + + @Column(name="format") + private Storage.ImageFormat format; + + @Column (name="download_pct") + private int downloadPercent; + + @Column (name="download_state") + @Enumerated(EnumType.STRING) + private Status downloadState; + + @Column (name="error_str") + private String errorString; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + + @Column(name="disk_offering_id") + private long diskOfferingId; + + @Column(name="disk_offering_uuid") + private String diskOfferingUuid; + + @Column(name="disk_offering_name") + private String diskOfferingName; + + @Column(name="disk_offering_display_text") + private String diskOfferingDisplayText; + + @Column(name="system_use") + private boolean systemUse; + + + @Column(name="use_local_storage") + private boolean useLocalStorage; + + @Column(name="pool_id") + private long poolId; + + @Column(name="pool_uuid") + private String poolUuid; + + @Column(name="pool_name") + private String poolName; + + @Column(name="template_id") + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="extractable") + private boolean extractable; + + @Column(name="template_type") + private Storage.TemplateType templateType; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + + + public VolumeJoinVO() { + } + + + + @Override + public long getId() { + return id; + } + + + + @Override + public void setId(long id) { + this.id = id; + } + + + + @Override + public String getUuid() { + return uuid; + } + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + + public String getName() { + return name; + } + + + + public void setName(String name) { + this.name = name; + } + + + + public Long getDeviceId() { + return deviceId; + } + + + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + + + public Volume.Type getVolumeType() { + return volumeType; + } + + + + public void setVolumeType(Volume.Type volumeType) { + this.volumeType = volumeType; + } + + + + public long getSize() { + return size; + } + + + + public void setSize(long size) { + this.size = size; + } + + + + public Volume.State getState() { + return state; + } + + + + public void setState(Volume.State state) { + this.state = state; + } + + + + public Date getCreated() { + return created; + } + + + + public void setCreated(Date created) { + this.created = created; + } + + + + public Date getAttached() { + return attached; + } + + + + public void setAttached(Date attached) { + this.attached = attached; + } + + + + public Date getRemoved() { + return removed; + } + + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + + @Override + public long getAccountId() { + return accountId; + } + + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + @Override + public String getAccountName() { + return accountName; + } + + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + + @Override + public short getAccountType() { + return accountType; + } + + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + + @Override + public long getDomainId() { + return domainId; + } + + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + @Override + public String getDomainName() { + return domainName; + } + + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + + @Override + public String getDomainPath() { + return domainPath; + } + + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + + public long getProjectId() { + return projectId; + } + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + @Override + public String getProjectName() { + return projectName; + } + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + public long getVmId() { + return vmId; + } + + + + public void setVmId(long vmId) { + this.vmId = vmId; + } + + + + public String getVmUuid() { + return vmUuid; + } + + + + public void setVmUuid(String vmUuid) { + this.vmUuid = vmUuid; + } + + + + public String getVmName() { + return vmName; + } + + + + public void setVmName(String vmName) { + this.vmName = vmName; + } + + + + public String getVmDisplayName() { + return vmDisplayName; + } + + + + public void setVmDisplayName(String vmDisplayName) { + this.vmDisplayName = vmDisplayName; + } + + + + public VirtualMachine.State getVmState() { + return vmState; + } + + + + public void setVmState(VirtualMachine.State vmState) { + this.vmState = vmState; + } + + + + public VirtualMachine.Type getVmType() { + return vmType; + } + + + + public void setVmType(VirtualMachine.Type vmType) { + this.vmType = vmType; + } + + + + public long getVolumeHostSize() { + return volumeHostSize; + } + + + + public void setVolumeHostSize(long volumeHostSize) { + this.volumeHostSize = volumeHostSize; + } + + + + public Date getVolumeHostCreated() { + return volumeHostCreated; + } + + + + public void setVolumeHostCreated(Date volumeHostCreated) { + this.volumeHostCreated = volumeHostCreated; + } + + + + public Storage.ImageFormat getFormat() { + return format; + } + + + + public void setFormat(Storage.ImageFormat format) { + this.format = format; + } + + + + public int getDownloadPercent() { + return downloadPercent; + } + + + + public void setDownloadPercent(int downloadPercent) { + this.downloadPercent = downloadPercent; + } + + + + public Status getDownloadState() { + return downloadState; + } + + + + public void setDownloadState(Status downloadState) { + this.downloadState = downloadState; + } + + + + public String getErrorString() { + return errorString; + } + + + + public void setErrorString(String errorString) { + this.errorString = errorString; + } + + + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + + + public long getDiskOfferingId() { + return diskOfferingId; + } + + + + public void setDiskOfferingId(long diskOfferingId) { + this.diskOfferingId = diskOfferingId; + } + + + + public String getDiskOfferingUuid() { + return diskOfferingUuid; + } + + + + public void setDiskOfferingUuid(String diskOfferingUuid) { + this.diskOfferingUuid = diskOfferingUuid; + } + + + + public String getDiskOfferingName() { + return diskOfferingName; + } + + + + public void setDiskOfferingName(String diskOfferingName) { + this.diskOfferingName = diskOfferingName; + } + + + + public String getDiskOfferingDisplayText() { + return diskOfferingDisplayText; + } + + + + public void setDiskOfferingDisplayText(String diskOfferingDisplayText) { + this.diskOfferingDisplayText = diskOfferingDisplayText; + } + + + + public boolean isUseLocalStorage() { + return useLocalStorage; + } + + + + public void setUseLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } + + + + public long getPoolId() { + return poolId; + } + + + + public void setPoolId(long poolId) { + this.poolId = poolId; + } + + + + public String getPoolUuid() { + return poolUuid; + } + + + + public void setPoolUuid(String poolUuid) { + this.poolUuid = poolUuid; + } + + + + public String getPoolName() { + return poolName; + } + + + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + + + public long getTemplateId() { + return templateId; + } + + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + public boolean isExtractable() { + return extractable; + } + + + + public void setExtractable(boolean extractable) { + this.extractable = extractable; + } + + + + public Storage.TemplateType getTemplateType() { + return templateType; + } + + + + public void setTemplateType(Storage.TemplateType templateType) { + this.templateType = templateType; + } + + + + public long getJobId() { + return jobId; + } + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + public String getJobUuid() { + return jobUuid; + } + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + public int getJobStatus() { + return jobStatus; + } + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + public long getTagId() { + return tagId; + } + + + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + + + public String getTagUuid() { + return tagUuid; + } + + + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + + + public String getTagKey() { + return tagKey; + } + + + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + + + public String getTagValue() { + return tagValue; + } + + + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + + + public long getTagDomainId() { + return tagDomainId; + } + + + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + + + public long getTagAccountId() { + return tagAccountId; + } + + + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + + + public long getTagResourceId() { + return tagResourceId; + } + + + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + + + public String getTagCustomer() { + return tagCustomer; + } + + + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + + public void setDataCenterUuid(String dataCenterUuid) { + this.dataCenterUuid = dataCenterUuid; + } + + + + public String getDataCenterName() { + return dataCenterName; + } + + + + public void setDataCenterName(String dataCenterName) { + this.dataCenterName = dataCenterName; + } + + + + public long getPodId() { + return podId; + } + + + + public void setPodId(long podId) { + this.podId = podId; + } + + + + public boolean isSystemUse() { + return systemUse; + } + + + + public void setSystemUse(boolean systemUse) { + this.systemUse = systemUse; + } + + + + +} diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java index 4be5dfab9d5..11aee3d9390 100644 --- a/server/src/com/cloud/api/response/ApiResponseSerializer.java +++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java @@ -21,20 +21,22 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiResponseGsonHelper; import com.cloud.api.ApiServer; -import com.cloud.api.BaseCmd; -import com.cloud.api.ResponseObject; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ResponseObject; import com.cloud.utils.encoding.URLEncoder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.uuididentity.dao.IdentityDao; @@ -46,6 +48,7 @@ public class ApiResponseSerializer { private static final Logger s_logger = Logger.getLogger(ApiResponseSerializer.class.getName()); public static String toSerializedString(ResponseObject result, String responseType) { + s_logger.trace("===Serializing Response==="); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { return toJSONSerializedString(result); } else { @@ -67,7 +70,7 @@ public class ApiResponseSerializer { public static String toJSONSerializedString(ResponseObject result) { if (result != null) { Gson gson = ApiResponseGsonHelper.getBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); - + StringBuilder sb = new StringBuilder(); sb.append("{ \"").append(result.getResponseName()).append("\" : "); @@ -78,15 +81,15 @@ public class ApiResponseSerializer { if (nonZeroCount) { sb.append("{ \"").append(ApiConstants.COUNT).append("\":").append(count); } - + if ((responses != null) && !responses.isEmpty()) { - String jsonStr = gson.toJson(responses.get(0)); + String jsonStr = gson.toJson(responses.get(0)); jsonStr = unescape(jsonStr); if (nonZeroCount) { sb.append(" ,\"").append(responses.get(0).getObjectName()).append("\" : [ ").append(jsonStr); } - + for (int i = 1; i < ((ListResponse) result).getResponses().size(); i++) { jsonStr = gson.toJson(responses.get(i)); jsonStr = unescape(jsonStr); @@ -94,18 +97,18 @@ public class ApiResponseSerializer { } sb.append(" ] }"); } else { - if (!nonZeroCount){ + if (!nonZeroCount){ sb.append("{"); } - + sb.append(" }"); } } else if (result instanceof SuccessResponse) { sb.append("{ \"success\" : \"").append(((SuccessResponse) result).getSuccess()).append("\"} "); - } else if (result instanceof ExceptionResponse) { + } else if (result instanceof ExceptionResponse) { String jsonErrorText = gson.toJson((ExceptionResponse) result); jsonErrorText = unescape(jsonErrorText); - sb.append(jsonErrorText); + sb.append(jsonErrorText); } else { String jsonStr = gson.toJson(result); if ((jsonStr != null) && !"".equals(jsonStr)) { @@ -119,7 +122,9 @@ public class ApiResponseSerializer { sb.append("{ }"); } } - sb.append(" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); return sb.toString(); } return null; @@ -128,7 +133,7 @@ public class ApiResponseSerializer { private static String toXMLSerializedString(ResponseObject result) { StringBuilder sb = new StringBuilder(); sb.append(""); - sb.append("<").append(result.getResponseName()).append(" cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">"); + sb.append("<").append(result.getResponseName()).append(" cloudstack-version=\"").append(ApiDBUtils.getVersion()).append("\">"); if (result instanceof ListResponse) { Integer count = ((ListResponse) result).getCount(); @@ -173,7 +178,7 @@ public class ApiResponseSerializer { } return fields.toArray(new Field[] {}); } - + private static void serializeResponseObjFieldsXML(StringBuilder sb, ResponseObject obj) { boolean isAsync = false; if (obj instanceof AsyncJobResponse) @@ -210,8 +215,8 @@ public class ApiResponseSerializer { if (isAsync) { sb.append(""); } - } else if (fieldValue instanceof List) { - List subResponseList = (List) fieldValue; + } else if (fieldValue instanceof Collection) { + Collection subResponseList = (Collection) fieldValue; boolean usedUuidList = false; for (Object value : subResponseList) { if (value instanceof ResponseObject) { @@ -220,28 +225,18 @@ public class ApiResponseSerializer { subObj.setObjectName(serializedName.value()); } serializeResponseObjXML(sb, subObj); - } else if (value instanceof IdentityProxy) { - // Only exception reponses carry a list of IdentityProxy objects. - IdentityProxy idProxy = (IdentityProxy)value; - String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : ""); - if(!id.isEmpty()) { - IdentityDao identityDao = new IdentityDaoImpl(); - id = identityDao.getIdentityUuid(idProxy.getTableName(), id); - } - if(id != null && !id.isEmpty()) { - // If this is the first IdentityProxy field encountered, put in a uuidList tag. - if (!usedUuidList) { - sb.append("<").append(serializedName.value()).append(">"); - usedUuidList = true; - } - sb.append("").append(id).append(""); - } - // Append the new idFieldName property also. - String idFieldName = idProxy.getidFieldName(); - if (idFieldName != null) { - sb.append("").append(idFieldName).append(""); - } - } + } else { + // Only exception reponses carry a list of uuid + // strings. + // If this is the first IdentityProxy field + // encountered, put in a uuidList tag. + if (!usedUuidList) { + sb.append("<").append(serializedName.value()).append(">"); + usedUuidList = true; + } + sb.append("").append(value).append(""); + // We have removed uuid property field due to removal of IdentityProxy class. + } } if (usedUuidList) { // close the uuidList. @@ -249,26 +244,13 @@ public class ApiResponseSerializer { } } else if (fieldValue instanceof Date) { sb.append("<").append(serializedName.value()).append(">").append(BaseCmd.getDateString((Date) fieldValue)). - append(""); - } else if (fieldValue instanceof IdentityProxy) { - IdentityProxy idProxy = (IdentityProxy)fieldValue; - String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : ""); - if(!id.isEmpty()) { - IdentityDao identityDao = new IdentityDaoImpl(); - if(idProxy.getTableName() != null) { - id = identityDao.getIdentityUuid(idProxy.getTableName(), id); - } else { - s_logger.warn("IdentityProxy sanity check issue, invalid IdentityProxy table name found in class: " + obj.getClass().getName()); - } - } - if(id != null && !id.isEmpty()) - sb.append("<").append(serializedName.value()).append(">").append(id).append(""); + append(""); } else { String resultString = escapeSpecialXmlChars(fieldValue.toString()); if (!(obj instanceof ExceptionResponse)) { resultString = encodeParam(resultString); } - + sb.append("<").append(serializedName.value()).append(">").append(resultString).append(""); } } @@ -335,10 +317,10 @@ public class ApiResponseSerializer { resultString.append(singleChar); } } - + return resultString.toString(); } - + private static String encodeParam(String value) { if (!ApiServer.encodeApiResponse) { return value; @@ -350,5 +332,5 @@ public class ApiResponseSerializer { } return value; } - + } diff --git a/server/src/com/cloud/api/response/SecurityGroupResultObject.java b/server/src/com/cloud/api/response/SecurityGroupResultObject.java index 5c3b7633c5d..aab13cdc529 100644 --- a/server/src/com/cloud/api/response/SecurityGroupResultObject.java +++ b/server/src/com/cloud/api/response/SecurityGroupResultObject.java @@ -21,14 +21,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.api.ApiDBUtils; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupRules; import com.cloud.serializer.Param; import com.cloud.user.Account; +import org.apache.cloudstack.api.InternalIdentity; -public class SecurityGroupResultObject implements ControlledEntity{ +public class SecurityGroupResultObject implements ControlledEntity, InternalIdentity { @Param(name = "id") private Long id; @@ -63,7 +64,7 @@ public class SecurityGroupResultObject implements ControlledEntity{ this.securityGroupRules = ingressRules; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/async/AsyncCommandQueued.java b/server/src/com/cloud/async/AsyncCommandQueued.java index 200b40e71b5..f01c214564b 100644 --- a/server/src/com/cloud/async/AsyncCommandQueued.java +++ b/server/src/com/cloud/async/AsyncCommandQueued.java @@ -17,9 +17,9 @@ package com.cloud.async; import com.cloud.utils.SerialVersionUID; -import com.cloud.utils.exception.RuntimeCloudException; +import com.cloud.utils.exception.CloudRuntimeException; -public class AsyncCommandQueued extends RuntimeCloudException { +public class AsyncCommandQueued extends CloudRuntimeException { private static final long serialVersionUID = SerialVersionUID.AsyncCommandQueued; private SyncQueueVO _queue = null; diff --git a/server/src/com/cloud/async/AsyncJobManager.java b/server/src/com/cloud/async/AsyncJobManager.java index 482499714c6..4cd67f3e39c 100644 --- a/server/src/com/cloud/async/AsyncJobManager.java +++ b/server/src/com/cloud/async/AsyncJobManager.java @@ -18,7 +18,7 @@ package com.cloud.async; import java.util.List; -import com.cloud.api.commands.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; import com.cloud.utils.component.Manager; public interface AsyncJobManager extends Manager { diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index 5fb5105857c..7bf5c5a83cc 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.async; - +package com.cloud.async; + import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Type; @@ -34,17 +34,17 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; import com.cloud.api.ApiSerializerHelper; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.ExceptionResponse; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExceptionResponse; import com.cloud.async.dao.AsyncJobDao; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; @@ -73,22 +73,22 @@ import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.net.MacAddress; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; - -@Local(value={AsyncJobManager.class}) -public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { - public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); + +@Local(value={AsyncJobManager.class}) +public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListener { + public static final Logger s_logger = Logger.getLogger(AsyncJobManagerImpl.class.getName()); private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds - - private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; + + private static final int MAX_ONETIME_SCHEDULE_SIZE = 50; private static final int HEARTBEAT_INTERVAL = 2000; private static final int GC_INTERVAL = 10000; // 10 seconds - - private String _name; - - private AsyncJobExecutorContext _context; - private SyncQueueManager _queueMgr; + + private String _name; + + private AsyncJobExecutorContext _context; + private SyncQueueManager _queueMgr; private ClusterManager _clusterMgr; - private AccountManager _accountMgr; + private AccountManager _accountMgr; private AccountDao _accountDao; private AsyncJobDao _jobDao; private long _jobExpireSeconds = 86400; // 1 day @@ -118,100 +118,100 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe @Override public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId) { return _jobDao.findInstancePendingAsyncJobs(instanceType, accountId); - } - - @Override - public long submitAsyncJob(AsyncJobVO job) { - return submitAsyncJob(job, false); - } + } + + @Override + public long submitAsyncJob(AsyncJobVO job) { + return submitAsyncJob(job, false); + } - @Override @DB + @Override @DB public long submitAsyncJob(AsyncJobVO job, boolean scheduleJobExecutionInContext) { - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); job.setInitMsid(getMsid()); - _jobDao.persist(job); - txt.commit(); + _jobDao.persist(job); + txt.commit(); // no sync source originally - job.setSyncSource(null); + job.setSyncSource(null); scheduleExecution(job, scheduleJobExecutionInContext); if(s_logger.isDebugEnabled()) { s_logger.debug("submit async job-" + job.getId() + ", details: " + job.toString()); } - return job.getId(); + return job.getId(); } catch(Exception e) { txt.rollback(); String errMsg = "Unable to schedule async job for command " + job.getCmd() + ", unexpected exception."; s_logger.warn(errMsg, e); throw new CloudRuntimeException(errMsg); - } - } - - @Override @DB - public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { + } + } + + @Override @DB + public void completeAsyncJob(long jobId, int jobStatus, int resultCode, Object resultObject) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + + s_logger.debug("Complete async job-" + jobId + ", jobStatus: " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { if(s_logger.isDebugEnabled()) { - s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + + s_logger.debug("job-" + jobId + " no longer exists, we just log completion info here. " + jobStatus + ", resultCode: " + resultCode + ", result: " + resultObject); - } - - txt.rollback(); - return; - } + } + + txt.rollback(); + return; + } - job.setCompleteMsid(getMsid()); - job.setStatus(jobStatus); - job.setResultCode(resultCode); + job.setCompleteMsid(getMsid()); + job.setStatus(jobStatus); + job.setResultCode(resultCode); - // reset attached object - job.setInstanceType(null); - job.setInstanceId(null); + // reset attached object + job.setInstanceType(null); + job.setInstanceId(null); if (resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); - } + } - job.setLastUpdated(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while completing async job-" + jobId, e); - txt.rollback(); - } - } + job.setLastUpdated(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while completing async job-" + jobId, e); + txt.rollback(); + } + } - @Override @DB - public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { + @Override @DB + public void updateAsyncJobStatus(long jobId, int processStatus, Object resultObject) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + + s_logger.debug("Update async-job progress, job-" + jobId + ", processStatus: " + processStatus + ", result: " + resultObject); - } - - Transaction txt = Transaction.currentTxn(); - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job == null) { + } + + Transaction txt = Transaction.currentTxn(); + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job == null) { if(s_logger.isDebugEnabled()) { s_logger.debug("job-" + jobId + " no longer exists, we just log progress info here. progress status: " + processStatus); - } - - txt.rollback(); - return; - } - - job.setProcessStatus(processStatus); + } + + txt.rollback(); + return; + } + + job.setProcessStatus(processStatus); if(resultObject != null) { job.setResult(ApiSerializerHelper.toSerializedStringOld(resultObject)); } @@ -315,60 +315,60 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe return _jobDao.findById(cmd.getId()); } - @Override @DB - public AsyncJobResult queryAsyncJobResult(long jobId) { + @Override @DB + public AsyncJobResult queryAsyncJobResult(long jobId) { if(s_logger.isTraceEnabled()) { s_logger.trace("Query async-job status, job-" + jobId); - } - - Transaction txt = Transaction.currentTxn(); - AsyncJobResult jobResult = new AsyncJobResult(jobId); - - try { - txt.start(); - AsyncJobVO job = _jobDao.findById(jobId); - if(job != null) { - jobResult.setCmdOriginator(job.getCmdOriginator()); - jobResult.setJobStatus(job.getStatus()); - jobResult.setProcessStatus(job.getProcessStatus()); - jobResult.setResult(job.getResult()); + } + + Transaction txt = Transaction.currentTxn(); + AsyncJobResult jobResult = new AsyncJobResult(jobId); + + try { + txt.start(); + AsyncJobVO job = _jobDao.findById(jobId); + if(job != null) { + jobResult.setCmdOriginator(job.getCmdOriginator()); + jobResult.setJobStatus(job.getStatus()); + jobResult.setProcessStatus(job.getProcessStatus()); + jobResult.setResult(job.getResult()); jobResult.setResultCode(job.getResultCode()); - jobResult.setUuid(job.getUuid()); - - if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || - job.getStatus() == AsyncJobResult.STATUS_FAILED) { - + jobResult.setUuid(job.getUuid()); + + if(job.getStatus() == AsyncJobResult.STATUS_SUCCEEDED || + job.getStatus() == AsyncJobResult.STATUS_FAILED) { + if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " completed"); - } - } else { - job.setLastPolled(DateUtil.currentGMTTime()); - _jobDao.update(jobId, job); - } - } else { + } + } else { + job.setLastPolled(DateUtil.currentGMTTime()); + _jobDao.update(jobId, job); + } + } else { if(s_logger.isDebugEnabled()) { s_logger.debug("Async job-" + jobId + " does not exist, invalid job id?"); - } - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("job-" + jobId + " does not exist"); - } - txt.commit(); - } catch(Exception e) { - s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); - - jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); - jobResult.setResult("Exception: " + e.toString()); - txt.rollback(); - } - + } + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("job-" + jobId + " does not exist"); + } + txt.commit(); + } catch(Exception e) { + s_logger.error("Unexpected exception while querying async job-" + jobId + " status: ", e); + + jobResult.setJobStatus(AsyncJobResult.STATUS_FAILED); + jobResult.setResult("Exception: " + e.toString()); + txt.rollback(); + } + if(s_logger.isTraceEnabled()) { s_logger.trace("Job status: " + jobResult.toString()); - } - - return jobResult; + } + + return jobResult; } - + private void scheduleExecution(final AsyncJobVO job) { scheduleExecution(job, false); } @@ -506,7 +506,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } }; } - + private void executeQueueItem(SyncQueueItemVO item, boolean fromPreviousSession) { AsyncJobVO job = _jobDao.findById(item.getContentId()); if (job != null) { @@ -536,61 +536,61 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } - @Override - public void releaseSyncSource(AsyncJobExecutor executor) { - if(executor.getSyncSource() != null) { + @Override + public void releaseSyncSource(AsyncJobExecutor executor) { + if(executor.getSyncSource() != null) { if(s_logger.isDebugEnabled()) { - s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " - + executor.getSyncSource().getContentType() + "-" + s_logger.debug("Release sync source for job-" + executor.getJob().getId() + " sync source: " + + executor.getSyncSource().getContentType() + "-" + executor.getSyncSource().getContentId()); - } - - _queueMgr.purgeItem(executor.getSyncSource().getId()); - checkQueue(executor.getSyncSource().getQueueId()); - } - } - - private void checkQueue(long queueId) { - while(true) { - try { - SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); - if(item != null) { + } + + _queueMgr.purgeItem(executor.getSyncSource().getId()); + checkQueue(executor.getSyncSource().getQueueId()); + } + } + + private void checkQueue(long queueId) { + while(true) { + try { + SyncQueueItemVO item = _queueMgr.dequeueFromOne(queueId, getMsid()); + if(item != null) { if(s_logger.isDebugEnabled()) { s_logger.debug("Executing sync queue item: " + item.toString()); - } - - executeQueueItem(item, false); - } else { - break; - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); - break; - } - } - } - - private Runnable getHeartbeatTask() { - return new Runnable() { + } + + executeQueueItem(item, false); + } else { + break; + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when kicking sync queue-" + queueId, e); + break; + } + } + } + + private Runnable getHeartbeatTask() { + return new Runnable() { @Override - public void run() { + public void run() { try { - List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item: l) { + List l = _queueMgr.dequeueFromAny(getMsid(), MAX_ONETIME_SCHEDULE_SIZE); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item: l) { if(s_logger.isDebugEnabled()) { s_logger.debug("Execute sync-queue item: " + item.toString()); } executeQueueItem(item, false); - } - } - } catch(Throwable e) { - s_logger.error("Unexpected exception when trying to execute queue item, ", e); + } + } + } catch(Throwable e) { + s_logger.error("Unexpected exception when trying to execute queue item, ", e); } finally { StackMaid.current().exitCleanup(); - } - } - }; + } + } + }; } @DB @@ -666,10 +666,10 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe private long getMsid() { if(_clusterMgr != null) { return _clusterMgr.getManagementNodeId(); - } - - return MacAddress.getMacAddress().toLong(); - } + } + + return MacAddress.getMacAddress().toLong(); + } private void cleanupPendingJobs(List l) { if(l != null && l.size() > 0) { @@ -713,25 +713,25 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe _accountDao = locator.getDao(AccountDao.class); if (_accountDao == null) { throw new ConfigurationException("Unable to get " + AccountDao.class.getName()); - } - _jobDao = locator.getDao(AsyncJobDao.class); - if (_jobDao == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobDao.class.getName()); - } - - _context = locator.getManager(AsyncJobExecutorContext.class); - if (_context == null) { - throw new ConfigurationException("Unable to get " - + AsyncJobExecutorContext.class.getName()); - } - - _queueMgr = locator.getManager(SyncQueueManager.class); - if(_queueMgr == null) { - throw new ConfigurationException("Unable to get " - + SyncQueueManager.class.getName()); - } - + } + _jobDao = locator.getDao(AsyncJobDao.class); + if (_jobDao == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobDao.class.getName()); + } + + _context = locator.getManager(AsyncJobExecutorContext.class); + if (_context == null) { + throw new ConfigurationException("Unable to get " + + AsyncJobExecutorContext.class.getName()); + } + + _queueMgr = locator.getManager(SyncQueueManager.class); + if(_queueMgr == null) { + throw new ConfigurationException("Unable to get " + + SyncQueueManager.class.getName()); + } + _clusterMgr = locator.getManager(ClusterManager.class); _accountMgr = locator.getManager(AccountManager.class); @@ -754,7 +754,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe throw new ConfigurationException("Unable to load db.properties to configure AsyncJobManagerImpl"); } - return true; + return true; } @Override @@ -783,8 +783,8 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe @Override public void onManagementNodeIsolated() { } - - @Override + + @Override public boolean start() { try { List l = _queueMgr.getActiveQueueItems(getMsid(), false); @@ -811,17 +811,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe private static String getSerializedErrorMessage(String errorMessage) { return ApiSerializerHelper.toSerializedStringOld(getResetResultResponse(errorMessage)); - } - - @Override - public boolean stop() { - _heartbeatScheduler.shutdown(); - _executor.shutdown(); - return true; - } - - @Override - public String getName() { - return _name; - } -} + } + + @Override + public boolean stop() { + _heartbeatScheduler.shutdown(); + _executor.shutdown(); + return true; + } + + @Override + public String getName() { + return _name; + } +} diff --git a/server/src/com/cloud/baremetal/BareMetalDiscoverer.java b/server/src/com/cloud/baremetal/BareMetalDiscoverer.java index 944e3714550..7d368688783 100755 --- a/server/src/com/cloud/baremetal/BareMetalDiscoverer.java +++ b/server/src/com/cloud/baremetal/BareMetalDiscoverer.java @@ -30,7 +30,7 @@ import org.apache.log4j.Logger; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; diff --git a/server/src/com/cloud/baremetal/BareMetalResourceBase.java b/server/src/com/cloud/baremetal/BareMetalResourceBase.java index 8c14ccecf2e..a922db911ef 100755 --- a/server/src/com/cloud/baremetal/BareMetalResourceBase.java +++ b/server/src/com/cloud/baremetal/BareMetalResourceBase.java @@ -53,7 +53,7 @@ import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev; import com.cloud.agent.api.baremetal.IpmiBootorResetCommand; import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor; import com.cloud.resource.ServerResource; diff --git a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java index e03cddabbcb..25298a9eebd 100755 --- a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java +++ b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java @@ -21,11 +21,11 @@ import java.util.List; import javax.ejb.Local; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index 31639a6a14c..57cfb396d3e 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -25,6 +25,11 @@ import java.util.concurrent.Executors; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; @@ -32,12 +37,7 @@ import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmiBootorResetCommand; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; diff --git a/server/src/com/cloud/baremetal/DhcpServerResponse.java b/server/src/com/cloud/baremetal/DhcpServerResponse.java index 761f604e8f3..db46ccd1a1d 100644 --- a/server/src/com/cloud/baremetal/DhcpServerResponse.java +++ b/server/src/com/cloud/baremetal/DhcpServerResponse.java @@ -16,21 +16,20 @@ // under the License. package com.cloud.baremetal; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class DhcpServerResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the Dhcp server") - private IdentityProxy id = new IdentityProxy("host"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java index 0da4029784e..c1f0fff6d3c 100755 --- a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java +++ b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java @@ -71,7 +71,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta @Inject UserVmDao _userVmDao; @Inject ResourceManager _resourceMgr; @Inject NicDao _nicDao; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); @@ -97,26 +97,26 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta protected String getDhcpServerGuid(String zoneId, String name, String ip) { return zoneId + "-" + name + "-" + ip; } - - + + @Override @DB - public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) { + public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) { DataCenterVO zone = _dcDao.findById(zoneId); if (zone == null) { throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId); - } - + } + HostPodVO pod = _podDao.findById(podId); if (pod == null) { throw new InvalidParameterValueException("Could not find pod with ID: " + podId); - } - + } + List dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId); if (dhcps.size() != 0) { throw new InvalidParameterValueException("Already had a DHCP server in Pod: " + podId + " zone: " + zoneId); } - - + + String ipAddress = url; String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress); Map params = new HashMap(); @@ -134,7 +134,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta dns = zone.getDns2(); } params.put("dns", dns); - + ServerResource resource = null; try { if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) { @@ -150,12 +150,12 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta s_logger.debug(e); throw new CloudRuntimeException(e.getMessage()); } - + Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params); if (dhcpServer == null) { throw new CloudRuntimeException("Cannot add external Dhcp server as a host"); } - + Transaction txn = Transaction.currentTxn(); txn.start(); pod.setExternalDhcp(true); @@ -163,11 +163,11 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta txn.commit(); return dhcpServer; } - + @Override public DhcpServerResponse getApiResponse(Host dhcpServer) { DhcpServerResponse response = new DhcpServerResponse(); - response.setId(dhcpServer.getId()); + response.setId(dhcpServer.getUuid()); return response; } @@ -178,7 +178,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry"); return; } - + List servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn()); if (servers.size() != 1) { throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn() @@ -188,7 +188,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta cmd.setNextServer(pxeServer.getPrivateIpAddress()); s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId()); } - + @Override public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException { @@ -198,11 +198,11 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta if (hosts.size() == 0) { throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId); } - + if (hosts.size() > 1) { throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId); } - + HostVO h = hosts.get(0); String dns = nic.getDns1(); if (dns == null) { @@ -240,7 +240,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta if (!(startup[0] instanceof StartupExternalDhcpCommand)) { return null; } - + host.setType(Host.Type.ExternalDhcp); return host; } diff --git a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java index efbccfa2092..0db8cc9289c 100755 --- a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java +++ b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java @@ -57,7 +57,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap @Inject ResourceManager _resourceMgr; @Inject(adapter=PxeServerService.class) protected Adapters _services; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -89,8 +89,8 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap } return _service; } - - + + @Override public Host addPxeServer(PxeServerProfile profile) { return getServiceByType(profile.getType()).addPxeServer(profile); @@ -99,7 +99,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap @Override public PxeServerResponse getApiResponse(Host pxeServer) { PxeServerResponse response = new PxeServerResponse(); - response.setId(pxeServer.getId()); + response.setId(pxeServer.getUuid()); return response; } @@ -112,7 +112,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap public boolean prepareCreateTemplate(PxeServerType type, Long pxeServerId, UserVm vm, String templateUrl) { return getServiceByType(type.getName()).prepareCreateTemplate(pxeServerId, vm, templateUrl); } - + @Override public PxeServerType getPxeServerType(HostVO host) { if (host.getResource().equalsIgnoreCase(PingPxeServerResource.class.getName())) { @@ -134,7 +134,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap if (!(startup[0] instanceof StartupPxeServerCommand)) { return null; } - + host.setType(Host.Type.PxeServer); return host; } diff --git a/server/src/com/cloud/baremetal/PxeServerResponse.java b/server/src/com/cloud/baremetal/PxeServerResponse.java index 26ea865e825..32fcc7fb5b9 100644 --- a/server/src/com/cloud/baremetal/PxeServerResponse.java +++ b/server/src/com/cloud/baremetal/PxeServerResponse.java @@ -16,21 +16,20 @@ // under the License. package com.cloud.baremetal; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class PxeServerResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the PXE server") - private IdentityProxy id = new IdentityProxy("host"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/cluster/CheckPointVO.java b/server/src/com/cloud/cluster/CheckPointVO.java index 27b7f93419e..db4f828721a 100644 --- a/server/src/com/cloud/cluster/CheckPointVO.java +++ b/server/src/com/cloud/cluster/CheckPointVO.java @@ -26,10 +26,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="stack_maid") -public class CheckPointVO { +public class CheckPointVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java b/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java index 4699f15a5ff..e5e12ecb8bf 100644 --- a/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java +++ b/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java @@ -30,10 +30,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.DateUtil; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mshost_peer") -public class ManagementServerHostPeerVO { +public class ManagementServerHostPeerVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/ManagementServerHostVO.java b/server/src/com/cloud/cluster/ManagementServerHostVO.java index ba2498d7352..31642e4d0c5 100644 --- a/server/src/com/cloud/cluster/ManagementServerHostVO.java +++ b/server/src/com/cloud/cluster/ManagementServerHostVO.java @@ -30,10 +30,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mshost") -public class ManagementServerHostVO implements ManagementServerHost{ +public class ManagementServerHostVO implements ManagementServerHost { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java b/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java index 9255c277e90..9c2edde299b 100644 --- a/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java +++ b/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java @@ -26,11 +26,12 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "op_host_transfer") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) -public class HostTransferMapVO { +public class HostTransferMapVO implements InternalIdentity { public enum HostTransferState { TransferRequested, TransferStarted; diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index ea32025ba32..b91fbdd69bf 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -35,15 +35,15 @@ import com.cloud.template.TemplateManager; import com.cloud.vm.UserVmManager; public enum Config { - + // Alert - + AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null), AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null), AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null), AlertSMTPPassword("Secure", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null), - AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), + AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null), CapacityCheckPeriod("Alert", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null), @@ -62,9 +62,9 @@ public enum Config { CPUCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.cpu.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which allocators will disable using the cluster for low cpu available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null), MemoryCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.memory.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which allocators will disable using the cluster for low memory available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null), - + // Storage - + StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null), StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null), MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null), @@ -84,9 +84,9 @@ public enum Config { NetworkLBHaproxyStatsVisbility("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.visibility", "global", "Load Balancer(haproxy) stats visibilty, the value can be one of the following six parameters : global,guest-network,link-local,disabled,all,default", null), NetworkLBHaproxyStatsUri("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.uri","/admin?stats","Load Balancer(haproxy) uri.",null), NetworkLBHaproxyStatsAuth("Secure", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.auth","admin1:AdMiN123","Load Balancer(haproxy) authetication string in the format username:password",null), - NetworkLBHaproxyStatsPort("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.port","8081","Load Balancer(haproxy) stats port number.",null), + NetworkLBHaproxyStatsPort("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.port","8081","Load Balancer(haproxy) stats port number.",null), NetworkRouterRpFilter("Network", ManagementServer.class, Integer.class, "network.disable.rpfilter", "true", "disable rp_filter on Domain Router VM public interfaces.", null), - + GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null), //MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null), NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null), @@ -102,18 +102,18 @@ public enum Config { SecurityGroupWorkerThreads("Network", ManagementServer.class, Integer.class, "network.securitygroups.workers.pool.size", "50", "Number of worker threads processing the security group update work queue", null), SecurityGroupWorkGlobalLockTimeout("Network", ManagementServer.class, Integer.class, "network.securitygroups.work.lock.timeout", "300", "Lock wait timeout (seconds) while updating the security group work queue", null), SecurityGroupWorkPerAgentMaxQueueSize("Network", ManagementServer.class, Integer.class, "network.securitygroups.work.per.agent.queue.size", "100", "The number of outstanding security group work items that can be queued to a host. If exceeded, work items will get dropped to conserve memory. Security Group Sync will take care of ensuring that the host gets updated eventually", null), - + SecurityGroupDefaultAdding("Network", ManagementServer.class, Boolean.class, "network.securitygroups.defaultadding", "true", "If true, the user VM would be added to the default security group by default", null), - + GuestOSNeedGatewayOnNonDefaultNetwork("Network", NetworkManager.class, String.class, "network.dhcp.nondefaultnetwork.setgateway.guestos", "Windows", "The guest OS's name start with this fields would result in DHCP server response gateway information even when the network it's on is not default network. Names are separated by comma.", null), - + //VPN RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null), RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null), - RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), + RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), Site2SiteVpnConnectionPerVpnGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.vpngateway.connection.limit", "4", "The maximum number of VPN connection per VPN gateway", null), Site2SiteVpnSubnetsPerCustomerGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.customergateway.subnets.limit", "10", "The maximum number of subnets per customer gateway", null), - + // Console Proxy ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null), ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null), @@ -125,11 +125,11 @@ public enum Config { ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null), ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null), ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null), - ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), + ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "console proxy service management state", null), - ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), + ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "last console proxy service management state", null), - + // Snapshots SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null), SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null), @@ -137,7 +137,7 @@ public enum Config { SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null), SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null), SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null), - + // Advanced JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null), JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null), @@ -165,8 +165,9 @@ public enum Config { RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VpcVirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null), RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null), RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null), - ExternalNetworkStatsInterval("Advanced", NetworkManager.class, Integer.class, "external.network.stats.interval", "300", "Interval (in seconds) to report external network statistics.", null), + ExternalNetworkStatsInterval("Advanced", NetworkManager.class, Integer.class, "external.network.stats.interval", "300", "Interval (in seconds) to report external network statistics.", null), RouterCheckInterval("Advanced", NetworkManager.class, Integer.class, "router.check.interval", "30", "Interval (in seconds) to report redundant router status.", null), + RouterCheckPoolSize("Advanced", NetworkManager.class, Integer.class, "router.check.poolsize", "10", "Numbers of threads using to check redundant router status.", null), RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null), RouterExtraPublicNics("Advanced", NetworkManager.class, Integer.class, "router.extra.public.nics", "2", "specify extra public nics used for virtual router(up to 5)", "0-5"), StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null), @@ -196,23 +197,23 @@ public enum Config { MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null), SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers, please note 0.0.0.0 is not a valid site", null), SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"), - SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), + SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null), SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null), SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null), SecStorageProxy("Advanced", AgentManager.class, String.class, "secstorage.proxy", null, "http proxy used by ssvm, in http://username:password@proxyserver:port format", null), - + DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"), DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null), CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"), NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null), - NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), + NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null), VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null), VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null), VmDestroyForcestop("Advanced", ManagementServer.class, Boolean.class, "vm.destroy.forcestop", "false", "On destroy, force-stop takes this value ", null), - + ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null), ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null), HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"), @@ -235,7 +236,7 @@ public enum Config { OvmPublicNetwork("Hidden", ManagementServer.class, String.class, "ovm.public.network.device", null, "Specify the public bridge on host for public network", null), OvmPrivateNetwork("Hidden", ManagementServer.class, String.class, "ovm.private.network.device", null, "Specify the private bridge on host for private network", null), OvmGuestNetwork("Hidden", ManagementServer.class, String.class, "ovm.guest.network.device", null, "Specify the private bridge on host for private network", null), - + // XenServer XenPublicNetwork("Hidden", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null), XenStorageNetwork1("Hidden", ManagementServer.class, String.class, "xen.storage.network.device1", null, "Specify when there are storage networks", null), @@ -246,7 +247,7 @@ public enum Config { XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null), XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null), XenGuestNetwork("Hidden", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null), - + // VMware VmwarePrivateNetworkVSwitch("Hidden", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null), VmwarePublicNetworkVSwitch("Hidden", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null), @@ -263,7 +264,7 @@ public enum Config { VmwareRootDiskControllerType("Advanced", ManagementServer.class, String.class, "vmware.root.disk.controller", "ide", "Specify the default disk controller for root volumes, valid values are scsi, ide", null), VmwareSystemVmNicDeviceType("Advanced", ManagementServer.class, String.class, "vmware.systemvm.nic.device.type", "E1000", "Specify the default network device type for system VMs, valid values are E1000, PCNet32, Vmxnet2, Vmxnet3", null), VmwareRecycleHungWorker("Advanced", ManagementServer.class, Boolean.class, "vmware.recycle.hung.wokervm", "false", "Specify whether or not to recycle hung worker VMs", null), - + // KVM KvmPublicNetwork("Hidden", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null), KvmPrivateNetwork("Hidden", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null), @@ -278,7 +279,7 @@ public enum Config { UsageAggregationTimezone("Usage", ManagementServer.class, String.class, "usage.aggregation.timezone", "GMT", "The timezone to use for usage stats aggregation", null), TrafficSentinelIncludeZones("Usage", ManagementServer.class, Integer.class, "traffic.sentinel.include.zones", "EXTERNAL", "Traffic going into specified list of zones is metered. For metering all traffic leave this parameter empty", null), TrafficSentinelExcludeZones("Usage", ManagementServer.class, Integer.class, "traffic.sentinel.exclude.zones", "", "Traffic going into specified list of zones is not metered.", null), - + // Hidden UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null), CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null), @@ -294,12 +295,12 @@ public enum Config { VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"), VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"), VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"), - - + + DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null), - + TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"), - + // Account Default Limits DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null), DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null), @@ -309,10 +310,10 @@ public enum Config { DefaultMaxAccountNetworks("Account Defaults", ManagementServer.class, Long.class, "max.account.networks", "20", "The default maximum number of networks that can be created for an account", null), DefaultMaxAccountVpcs("Account Defaults", ManagementServer.class, Long.class, "max.account.vpcs", "20", "The default maximum number of vpcs that can be created for an account", null), - + ResourceCountCheckInterval("Advanced", ManagementServer.class, Long.class, "resourcecount.check.interval", "0", "Time (in seconds) to wait before retrying resource count check task. Default is 0 which is to never run the task", "Seconds"), DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null), - + //disabling lb as cluster sync does not work with distributed cluster AgentLbEnable("Advanced", ManagementServer.class, Boolean.class, "agent.lb.enabled", "false", "If agent load balancing enabled in cluster setup", null), SubDomainNetworkAccess("Advanced", NetworkManager.class, Boolean.class, "allow.subdomain.network.access", "true", "Allow subdomains to use networks dedicated to their parent domain(s)", null), @@ -322,9 +323,9 @@ public enum Config { ClusterMessageTimeOutSeconds("Advanced", ManagementServer.class, Integer.class, "cluster.message.timeout.seconds", "300", "Time (in seconds) to wait before a inter-management server message post times out.", null), AgentLoadThreshold("Advanced", ManagementServer.class, Float.class, "agent.load.threshold", "0.7", "Percentage (as a value between 0 and 1) of connected agents after which agent load balancing will start happening", null), - + JavaScriptDefaultContentType("Advanced", ManagementServer.class, String.class, "json.content.type", "text/javascript", "Http response content type for .js files (default is text/javascript)", null), - + DefaultMaxProjectUserVms("Project Defaults", ManagementServer.class, Long.class, "max.project.user.vms", "20", "The default maximum number of user VMs that can be deployed for a project", null), DefaultMaxProjectPublicIPs("Project Defaults", ManagementServer.class, Long.class, "max.project.public.ips", "20", "The default maximum number of public IPs that can be consumed by a project", null), DefaultMaxProjectTemplates("Project Defaults", ManagementServer.class, Long.class, "max.project.templates", "20", "The default maximum number of templates that can be deployed for a project", null), @@ -332,11 +333,11 @@ public enum Config { DefaultMaxProjectVolumes("Project Defaults", ManagementServer.class, Long.class, "max.project.volumes", "20", "The default maximum number of volumes that can be created for a project", null), DefaultMaxProjectNetworks("Project Defaults", ManagementServer.class, Long.class, "max.project.networks", "20", "The default maximum number of networks that can be created for a project", null), DefaultMaxProjectVpcs("Project Defaults", ManagementServer.class, Long.class, "max.project.vpcs", "20", "The default maximum number of vpcs that can be created for a project", null), - + ProjectInviteRequired("Project Defaults", ManagementServer.class, Boolean.class, "project.invite.required", "false", "If invitation confirmation is required when add account to project. Default value is false", null), ProjectInvitationExpirationTime("Project Defaults", ManagementServer.class, Long.class, "project.invite.timeout", "86400", "Invitation expiration time (in seconds). Default is 1 day - 86400 seconds", null), AllowUserToCreateProject("Project Defaults", ManagementServer.class, Long.class, "allow.user.create.projects", "true", "If regular user can create a project; true by default", null), - + ProjectEmailSender("Project Defaults", ManagementServer.class, String.class, "project.email.sender", null, "Sender of project invitation email (will be in the From header of the email)", null), ProjectSMTPHost("Project Defaults", ManagementServer.class, String.class, "project.smtp.host", null, "SMTP hostname used for sending out email project invitations", null), ProjectSMTPPassword("Secure", ManagementServer.class, String.class, "project.smtp.password", null, "Password for SMTP authentication (applies only if project.smtp.useAuth is true)", null), @@ -354,11 +355,12 @@ public enum Config { HaTag("Advanced", ManagementServer.class, String.class, "ha.tag", null, "HA tag defining that the host marked with this tag can be used for HA purposes only", null), VpcCleanupInterval("Advanced", ManagementServer.class, Integer.class, "vpc.cleanup.interval", "3600", "The interval (in seconds) between cleanup for Inactive VPCs", null), VpcMaxNetworks("Advanced", ManagementServer.class, Integer.class, "vpc.max.networks", "3", "Maximum number of networks per vpc", null), - + DetailBatchQuerySize("Advanced", ManagementServer.class, Integer.class, "detail.batch.query.size", "2000", "Default entity detail batch query size for listing", null), + ConcurrentSnapshotsThresholdPerHost("Advanced", ManagementServer.class, Long.class, "concurrent.snapshots.threshold.perhost", null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null); - - + + private final String _category; private final Class _componentClass; private final Class _type; @@ -383,7 +385,7 @@ public enum Config { _configs.put("Account Defaults", new ArrayList()); _configs.put("Project Defaults", new ArrayList()); _configs.put("Secure", new ArrayList()); - + // Add values into HashMap for (Config c : Config.values()) { String category = c.getCategory(); @@ -392,7 +394,7 @@ public enum Config { _configs.put(category, currentConfigs); } } - + private Config(String category, Class componentClass, Class type, String name, String defaultValue, String description, String range) { _category = category; _componentClass = componentClass; @@ -402,15 +404,15 @@ public enum Config { _description = description; _range = range; } - + public String getCategory() { return _category; } - + public String key() { return _name; } - + public String getDescription() { return _description; } @@ -426,7 +428,7 @@ public enum Config { public Class getComponentClass() { return _componentClass; } - + public String getComponent() { if (_componentClass == ManagementServer.class) { return "management-server"; @@ -452,16 +454,16 @@ public enum Config { public String getRange() { return _range; } - + @Override public String toString() { return _name; } - + public static List getConfigs(String category) { return _configs.get(category); } - + public static Config getConfig(String name) { List categories = getCategories(); for (String category : categories) { @@ -472,10 +474,10 @@ public enum Config { } } } - + return null; } - + public static List getCategories() { Object[] keys = _configs.keySet().toArray(); List categories = new ArrayList(); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index e851525773c..feef2b23d5b 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -38,32 +38,30 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker; +import org.apache.cloudstack.acl.SecurityChecker; import com.cloud.alert.AlertManager; -import com.cloud.api.ApiConstants.LDAPParams; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -2079,7 +2077,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura Long projectId = cmd.getProjectId(); Long domainId = cmd.getDomainId(); Account vlanOwner = null; - + + // if end ip is not specified, default it to startIp + if (endIP == null && startIP != null) { + endIP = startIP; + } + if (projectId != null) { if (accountName != null) { throw new InvalidParameterValueException("Account and projectId are mutually exclusive"); @@ -2184,6 +2187,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura throw new InvalidParameterValueException("Nework id is required for Direct vlan creation "); } networkId = network.getId(); + zoneId = network.getDataCenterId(); } } else if (network.getGuestType() == null || network.getGuestType() == Network.GuestType.Isolated) { throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType()); @@ -2200,34 +2204,34 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura endIP = startIP; } - if (forVirtualNetwork || zone.getNetworkType() == DataCenter.NetworkType.Basic || zone.isSecurityGroupEnabled()) { - if (vlanGateway == null || vlanNetmask == null || zoneId == null) { - throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks"); - } - } else { - // check if startIp and endIp belong to network Cidr - String networkCidr = network.getCidr(); - String networkGateway = network.getGateway(); - Long networkZoneId = network.getDataCenterId(); - String networkNetmask = NetUtils.getCidrNetmask(networkCidr); - - // Check if ip addresses are in network range - if (!NetUtils.sameSubnet(startIP, networkGateway, networkNetmask)) { - throw new InvalidParameterValueException("Start ip is not in network cidr: " + networkCidr); - } - - if (endIP != null) { - if (!NetUtils.sameSubnet(endIP, networkGateway, networkNetmask)) { - throw new InvalidParameterValueException("End ip is not in network cidr: " + networkCidr); + if ( zone.getNetworkType() == DataCenter.NetworkType.Advanced ) { + if (network.getTrafficType() == TrafficType.Guest) { + if (network.getGuestType() != GuestType.Shared) { + throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + + network.getId() + " is " + network.getGuestType()); } + List vlans = _vlanDao.listVlansByNetworkId(network.getId()); + if ( vlans != null && vlans.size() > 0 ) { + VlanVO vlan = vlans.get(0); + if ( vlanId == null ) { + vlanId = vlan.getVlanTag(); + } else if ( vlan.getVlanTag() != vlanId ) { + throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + + + network.getId() + ", only one vlan is allowed on guest network"); + } + vlanGateway = vlan.getVlanGateway(); + vlanNetmask = vlan.getVlanNetmask(); + } + } else if (network.getTrafficType() == TrafficType.Management) { + throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network"); } - - // set gateway, netmask, zone from network object - vlanGateway = networkGateway; - vlanNetmask = networkNetmask; - zoneId = networkZoneId; } + if (vlanGateway == null || vlanNetmask == null || zoneId == null) { + throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks"); + } + + // if it's an account specific range, associate ip address list to the account boolean associateIpRangeToAccount = false; @@ -3105,8 +3109,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateLoadBalancerServiceCapabilities(Map lbServiceCapabilityMap) { if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { - if (lbServiceCapabilityMap.keySet().size() > 2 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + if (lbServiceCapabilityMap.keySet().size() > 3 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); } for (Capability cap : lbServiceCapabilityMap.keySet()) { @@ -3123,8 +3127,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!enabled && !disabled) { throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticLb.getName()); } + } else if (cap == Capability.InlineMode) { + boolean enabled = value.contains("true"); + boolean disabled = value.contains("false"); + if (!enabled && !disabled) { + throw new InvalidParameterValueException("Unknown specified value for " + Capability.InlineMode.getName()); + } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); } } } @@ -3159,33 +3169,20 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateStaticNatServiceCapablities(Map staticNatServiceCapabilityMap) { if (staticNatServiceCapabilityMap != null && !staticNatServiceCapabilityMap.isEmpty()) { - if (staticNatServiceCapabilityMap.keySet().size() > 2) { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + " capabilitiy can be sepcified for static nat service"); + if (staticNatServiceCapabilityMap.keySet().size() > 1) { + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capability can be specified for static nat service"); } - boolean eipEnabled = false; - boolean eipDisabled = false; - boolean associatePublicIP = true; + for (Capability capability : staticNatServiceCapabilityMap.keySet()) { String value = staticNatServiceCapabilityMap.get(capability); if (capability == Capability.ElasticIp) { - eipEnabled = value.contains("true"); - eipDisabled = value.contains("false"); - if (!eipEnabled && !eipDisabled) { + boolean enabled = value.contains("true"); + boolean disabled = value.contains("false"); + if (!enabled && !disabled) { throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticIp.getName()); } - } else if (capability == Capability.AssociatePublicIP) { - if (value.contains("true")) { - associatePublicIP = true; - } else if (value.contains("false")) { - associatePublicIP = false; - } else { - throw new InvalidParameterValueException("Unknown specified value for " + Capability.AssociatePublicIP.getName()); - } } else { - throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " and " + Capability.AssociatePublicIP.getName() + " capabilitiy can be sepcified for static nat service"); - } - if (eipDisabled && associatePublicIP) { - throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName() + " can only be set when capability " + Capability.ElasticIp.getName() + " is true"); + throw new InvalidParameterValueException("Only " + Capability.ElasticIp.getName() + " capability can be specified for static nat service"); } } } @@ -3239,7 +3236,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean sharedSourceNat = false; boolean redundantRouter = false; boolean elasticIp = false; - boolean associatePublicIp = false; + boolean inline = false; if (serviceCapabilityMap != null && !serviceCapabilityMap.isEmpty()) { Map lbServiceCapabilityMap = serviceCapabilityMap.get(Service.Lb); @@ -3256,6 +3253,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (param != null) { elasticLb = param.contains("true"); } + + String inlineMode = lbServiceCapabilityMap.get(Capability.InlineMode); + if (inlineMode != null) { + _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode); + inline = inlineMode.contains("true"); + } else { + inline = false; + } } Map sourceNatServiceCapabilityMap = serviceCapabilityMap.get(Service.SourceNat); @@ -3280,17 +3285,13 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura String param = staticNatServiceCapabilityMap.get(Capability.ElasticIp); if (param != null) { elasticIp = param.contains("true"); - String associatePublicIP = staticNatServiceCapabilityMap.get(Capability.AssociatePublicIP); - if (associatePublicIP != null) { - associatePublicIp = associatePublicIP.contains("true"); - } } } } NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan, networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb, - sharedSourceNat, redundantRouter, elasticIp, elasticLb, associatePublicIp, specifyIpRanges); + sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges, inline); if (serviceOfferingId != null) { offering.setServiceOfferingId(serviceOfferingId); diff --git a/server/src/com/cloud/configuration/DefaultComponentLibrary.java b/server/src/com/cloud/configuration/DefaultComponentLibrary.java index f57c6919752..e98946b9aa7 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -24,6 +24,21 @@ import java.util.Map; import com.cloud.agent.manager.ClusteredAgentManagerImpl; import com.cloud.alert.AlertManagerImpl; import com.cloud.alert.dao.AlertDaoImpl; +import com.cloud.api.query.QueryManagerImpl; +import com.cloud.api.query.dao.AccountJoinDaoImpl; +import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; +import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; +import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; +import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; +import com.cloud.api.query.dao.ProjectInvitationJoinDaoImpl; +import com.cloud.api.query.dao.ProjectJoinDaoImpl; +import com.cloud.api.query.dao.ResourceTagJoinDaoImpl; +import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; +import com.cloud.api.query.dao.StoragePoolJoinDaoImpl; +import com.cloud.api.query.dao.UserAccountJoinDaoImpl; +import com.cloud.api.query.dao.UserVmJoinDaoImpl; +import com.cloud.api.query.dao.HostJoinDaoImpl; +import com.cloud.api.query.dao.VolumeJoinDaoImpl; import com.cloud.async.AsyncJobExecutorContextImpl; import com.cloud.async.AsyncJobManagerImpl; import com.cloud.async.SyncQueueManagerImpl; @@ -210,6 +225,8 @@ import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; import com.cloud.vm.dao.UserVmDaoImpl; import com.cloud.vm.dao.UserVmDetailsDaoImpl; import com.cloud.vm.dao.VMInstanceDaoImpl; +import com.cloud.event.dao.EventJoinDaoImpl; + public class DefaultComponentLibrary extends ComponentLibraryBase implements ComponentLibrary { @@ -307,6 +324,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); addDao("NicDao", NicDaoImpl.class); addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); + addDao("InstanceGroupJoinDao", InstanceGroupJoinDaoImpl.class); addDao("InstanceGroupVMMapDao", InstanceGroupVMMapDaoImpl.class); addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); addDao("VpnUserDao", VpnUserDaoImpl.class); @@ -359,6 +377,21 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("Site2SiteVpnGatewayDao", Site2SiteVpnGatewayDaoImpl.class); addDao("Site2SiteCustomerGatewayDao", Site2SiteCustomerGatewayDaoImpl.class); addDao("Site2SiteVpnConnnectionDao", Site2SiteVpnConnectionDaoImpl.class); + + addDao("UserVmJoinDao", UserVmJoinDaoImpl.class); + addDao("DomainRouterJoinDao", DomainRouterJoinDaoImpl.class); + addDao("SecurityGroupJoinDao", SecurityGroupJoinDaoImpl.class); + addDao("ResourceTagJoinDao", ResourceTagJoinDaoImpl.class); + addDao("EventJoinDao", EventJoinDaoImpl.class); + addDao("UserAccountJoinDao", UserAccountJoinDaoImpl.class); + addDao("ProjectJoinDao", ProjectJoinDaoImpl.class); + addDao("ProjectAccountJoinDao", ProjectAccountJoinDaoImpl.class); + addDao("ProjectInvitationJoinDao", ProjectInvitationJoinDaoImpl.class); + addDao("HostJoinDao", HostJoinDaoImpl.class); + addDao("VolumeJoinDao", VolumeJoinDaoImpl.class); + addDao("AccountJoinDao", AccountJoinDaoImpl.class); + addDao("AsyncJobJoinDao", AsyncJobJoinDaoImpl.class); + addDao("StoragePoolJoinDao", StoragePoolJoinDaoImpl.class); } @Override @@ -366,6 +399,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com if (_daos.size() == 0) { populateDaos(); } + //FIXME: Incorrect method return definition return _daos; } @@ -421,6 +455,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addManager("NetworkACLManager", NetworkACLManagerImpl.class); addManager("TaggedResourcesManager", TaggedResourceManagerImpl.class); addManager("Site2SiteVpnManager", Site2SiteVpnManagerImpl.class); + addManager("QueryManager", QueryManagerImpl.class); } @Override diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index c8f8bdcbe27..6b2d8ad8e42 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -31,6 +31,8 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.persistence.Table; +import com.cloud.offering.DiskOffering; +import com.cloud.storage.dao.DiskOfferingDao; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -52,7 +54,7 @@ import com.cloud.agent.api.proxy.StartConsoleProxyAgentHttpHandlerCommand; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.commands.DestroyConsoleProxyCmd; import com.cloud.certificate.dao.CertificateDao; import com.cloud.cluster.ClusterManager; @@ -108,7 +110,6 @@ import com.cloud.resource.UnableDeleteHostException; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.servlet.ConsoleProxyServlet; -import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePoolStatus; import com.cloud.storage.StoragePoolVO; @@ -139,7 +140,6 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.events.SubscriptionMgr; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; -import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; @@ -219,6 +219,8 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx @Inject ServiceOfferingDao _offeringDao; @Inject + DiskOfferingDao _diskOfferingDao; + @Inject NetworkOfferingDao _networkOfferingDao; @Inject StoragePoolDao _storagePoolDao; @@ -227,8 +229,6 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx @Inject ResourceManager _resourceMgr; @Inject - IdentityDao _identityDao; - @Inject NetworkDao _networkDao; @Inject RulesManager _rulesMgr; @@ -931,14 +931,12 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx return new ConsoleAccessAuthenticationAnswer(cmd, false); } - vmId = _identityDao.getIdentityId("vm_instance", cmd.getVmId()); - if (vmId == null) { - s_logger.error("Invalid vm id " + cmd.getVmId() + " sent from console access authentication"); - return new ConsoleAccessAuthenticationAnswer(cmd, false); - } - - VMInstanceVO vm = _instanceDao.findById(vmId); + VirtualMachine vm = _instanceDao.findByUuid(cmd.getVmId()); if (vm == null) { + vm = _instanceDao.findById(Long.parseLong(cmd.getVmId())); + } + if (vm == null) { + s_logger.error("Invalid vm id " + cmd.getVmId() + " sent from console access authentication"); return new ConsoleAccessAuthenticationAnswer(cmd, false); } @@ -1528,16 +1526,13 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx //check if there is a default service offering configured String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key()); if (cpvmSrvcOffIdStr != null) { - - Long cpvmSrvcOffId = null; - try { - cpvmSrvcOffId = _identityDao.getIdentityId(DiskOfferingVO.class.getAnnotation(Table.class).name(),cpvmSrvcOffIdStr); - } catch (Exception e) { - String msg = "Can't find system service offering specified by global config, uuid=" + cpvmSrvcOffIdStr + " for console proxy vm"; - s_logger.warn(msg); - } - if(cpvmSrvcOffId != null){ - _serviceOffering = _offeringDao.findById(cpvmSrvcOffId); + DiskOffering diskOffering = _diskOfferingDao.findByUuid(cpvmSrvcOffIdStr); + if (diskOffering == null) + diskOffering = _diskOfferingDao.findById(Long.parseLong(cpvmSrvcOffIdStr)); + if (diskOffering != null) { + _serviceOffering = _offeringDao.findById(diskOffering.getId()); + } else { + s_logger.warn("Can't find system service offering specified by global config, uuid=" + cpvmSrvcOffIdStr + " for console proxy vm"); } } diff --git a/server/src/com/cloud/dao/EntityManagerImpl.java b/server/src/com/cloud/dao/EntityManagerImpl.java index 1430c0834b2..2eee445f933 100644 --- a/server/src/com/cloud/dao/EntityManagerImpl.java +++ b/server/src/com/cloud/dao/EntityManagerImpl.java @@ -45,7 +45,14 @@ public class EntityManagerImpl implements EntityManager, Manager { } @Override - public T findByXid(Class entityType, String xid) { + public T findByUuid(Class entityType, String uuid) { + // Finds and returns a unique VO using uuid, null if entity not found in db + GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); + return dao.findByUuid(uuid); + } + + @Override + public T findByXId(Class entityType, String xid) { return null; } diff --git a/server/src/com/cloud/dc/AccountVlanMapVO.java b/server/src/com/cloud/dc/AccountVlanMapVO.java index f8cb9000332..b1bf919df09 100644 --- a/server/src/com/cloud/dc/AccountVlanMapVO.java +++ b/server/src/com/cloud/dc/AccountVlanMapVO.java @@ -24,15 +24,16 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_vlan_map") -public class AccountVlanMapVO implements OwnedBy { +public class AccountVlanMapVO implements OwnedBy, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") - private Long id; + private long id; @Column(name="account_id") private long accountId; @@ -49,7 +50,7 @@ public class AccountVlanMapVO implements OwnedBy { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/ClusterDetailsVO.java b/server/src/com/cloud/dc/ClusterDetailsVO.java index 972d50ecc0e..11a55258f23 100644 --- a/server/src/com/cloud/dc/ClusterDetailsVO.java +++ b/server/src/com/cloud/dc/ClusterDetailsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="cluster_details") -public class ClusterDetailsVO { +public class ClusterDetailsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/ClusterVO.java b/server/src/com/cloud/dc/ClusterVO.java index c2368016db7..4195b74f87f 100644 --- a/server/src/com/cloud/dc/ClusterVO.java +++ b/server/src/com/cloud/dc/ClusterVO.java @@ -28,63 +28,64 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; import com.cloud.org.Managed.ManagedState; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="cluster") -public class ClusterVO implements Cluster, Identity { +public class ClusterVO implements Cluster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="name") String name; - + @Column(name="guid") String guid; - + @Column(name="data_center_id") long dataCenterId; - + @Column(name="pod_id") long podId; - + @Column(name="hypervisor_type") String hypervisorType; @Column(name="cluster_type") @Enumerated(value=EnumType.STRING) Cluster.ClusterType clusterType; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; - + @Column(name="managed_state") @Enumerated(value=EnumType.STRING) ManagedState managedState; - + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @Column(name="uuid") String uuid; - + public ClusterVO() { clusterType = Cluster.ClusterType.CloudManaged; allocationState = Grouping.AllocationState.Enabled; - + this.uuid = UUID.randomUUID().toString(); } - + public ClusterVO(long dataCenterId, long podId, String name) { this.dataCenterId = dataCenterId; this.podId = podId; @@ -110,23 +111,23 @@ public class ClusterVO implements Cluster, Identity { public long getPodId() { return podId; } - + public Cluster.ClusterType getClusterType() { return clusterType; } - + public void setClusterType(Cluster.ClusterType clusterType) { this.clusterType = clusterType; } - + public AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + public ManagedState getManagedState() { return managedState; } @@ -143,7 +144,7 @@ public class ClusterVO implements Cluster, Identity { public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof ClusterVO)) { @@ -152,7 +153,7 @@ public class ClusterVO implements Cluster, Identity { ClusterVO that = (ClusterVO)obj; return this.id == that.id; } - + public HypervisorType getHypervisorType() { return HypervisorType.getType(hypervisorType); } @@ -160,11 +161,11 @@ public class ClusterVO implements Cluster, Identity { public void setHypervisorType(String hy) { hypervisorType = hy; } - + public String getGuid() { return guid; } - + public void setGuid(String guid) { this.guid = guid; } @@ -176,12 +177,12 @@ public class ClusterVO implements Cluster, Identity { public void setName(String name) { this.name = name; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/dc/DataCenterIpAddressVO.java b/server/src/com/cloud/dc/DataCenterIpAddressVO.java index 4c407ba1d04..d92227fd6f6 100755 --- a/server/src/com/cloud/dc/DataCenterIpAddressVO.java +++ b/server/src/com/cloud/dc/DataCenterIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_ip_address_alloc") -public class DataCenterIpAddressVO { +public class DataCenterIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -75,7 +77,7 @@ public class DataCenterIpAddressVO { this.podId = podId; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java b/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java index feab6d4f578..ffa754954bc 100644 --- a/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java +++ b/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_link_local_ip_address_alloc") -public class DataCenterLinkLocalIpAddressVO { +public class DataCenterLinkLocalIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -64,7 +66,7 @@ public class DataCenterLinkLocalIpAddressVO { this.podId = podId; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 7b5280cc2d3..28fb11f8cc0 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -31,99 +31,100 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.Network.Provider; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="data_center") -public class DataCenterVO implements DataCenter, Identity { - +public class DataCenterVO implements DataCenter { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="name") private String name = null; - + @Column(name="description") private String description = null; - + @Column(name="dns1") private String dns1 = null; - + @Column(name="dns2") private String dns2 = null; - + @Column(name="internal_dns1") private String internalDns1 = null; - + @Column(name="internal_dns2") private String internalDns2 = null; - + @Column(name="router_mac_address", updatable = false, nullable=false) private String routerMacAddress = "02:00:00:00:00:01"; - + @Column(name="guest_network_cidr") private String guestNetworkCidr = null; - + @Column(name="domain_id") private Long domainId = null; @Column(name="domain") private String domain; - + @Column(name="networktype") - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.STRING) NetworkType networkType; - + @Column(name="dns_provider") private String dnsProvider; - + @Column(name="dhcp_provider") private String dhcpProvider; - + @Column(name="gateway_provider") private String gatewayProvider; - + @Column(name="vpn_provider") private String vpnProvider; - + @Column(name="userdata_provider") private String userDataProvider; - + @Column(name="lb_provider") private String loadBalancerProvider; - + @Column(name="firewall_provider") private String firewallProvider; - + @Column(name="mac_address", nullable=false) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) private long macAddress = 1; - + @Column(name="zone_token") - private String zoneToken; - + private String zoneToken; + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call the dao to load it. @Transient Map details; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; @Column(name="uuid") - private String uuid; - + private String uuid; + @Column(name="is_security_group_enabled") boolean securityGroupEnabled; @@ -168,13 +169,13 @@ public class DataCenterVO implements DataCenter, Identity { @Override public String getFirewallProvider() { - return firewallProvider; + return firewallProvider; } public void setFirewallProvider(String firewallProvider) { this.firewallProvider = firewallProvider; } - + public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false); this.id = id; @@ -216,7 +217,7 @@ public class DataCenterVO implements DataCenter, Identity { this.domain = domainSuffix; this.uuid = UUID.randomUUID().toString(); } - + @Override public String getVpnProvider() { return vpnProvider; @@ -234,13 +235,13 @@ public class DataCenterVO implements DataCenter, Identity { public void setUserDataProvider(String userDataProvider) { this.userDataProvider = userDataProvider; } - + @Override public String getGuestNetworkCidr() { return guestNetworkCidr; } - + public void setGuestNetworkCidr(String guestNetworkCidr) { this.guestNetworkCidr = guestNetworkCidr; @@ -254,7 +255,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomainId(Long domainId) { this.domainId = domainId; } - + @Override public String getDescription() { return description; @@ -263,12 +264,12 @@ public class DataCenterVO implements DataCenter, Identity { public String getRouterMacAddress() { return routerMacAddress; } - + @Override public String getDns1() { return dns1; } - + @Override public String getDns2() { return dns2; @@ -291,28 +292,28 @@ public class DataCenterVO implements DataCenter, Identity { public long getId() { return id; } - + @Override public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public void setDns1(String dns1) { this.dns1 = dns1; } - + public void setDns2(String dns2) { this.dns2 = dns2; } - + public void setInternalDns1(String dns3) { this.internalDns1 = dns3; } - + public void setInternalDns2(String dns4) { this.internalDns2 = dns4; } @@ -320,7 +321,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setRouterMacAddress(String routerMacAddress) { this.routerMacAddress = routerMacAddress; } - + @Override public String getDomain() { return domain; @@ -329,7 +330,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomain(String domain) { this.domain = domain; } - + public void setNetworkType(NetworkType zoneNetworkType) { this.networkType = zoneNetworkType; } @@ -338,12 +339,12 @@ public class DataCenterVO implements DataCenter, Identity { public NetworkType getNetworkType() { return networkType; } - - @Override + + @Override public boolean isSecurityGroupEnabled() { return securityGroupEnabled; } - + public void setSecurityGroupEnabled(boolean enabled) { this.securityGroupEnabled = enabled; } @@ -364,34 +365,34 @@ public class DataCenterVO implements DataCenter, Identity { @Override public void setDetails(Map details2) { - details = details2; + details = details2; } - + 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 AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + @Override public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof DataCenterVO)) { @@ -405,20 +406,20 @@ public class DataCenterVO implements DataCenter, Identity { public String getZoneToken() { return zoneToken; } - + public void setZoneToken(String zoneToken) { this.zoneToken = zoneToken; } - + public Date getRemoved() { return removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -430,4 +431,4 @@ public class DataCenterVO implements DataCenter, Identity { public void setMacAddress(long macAddress) { this.macAddress = macAddress; } -} +} diff --git a/server/src/com/cloud/dc/DataCenterVnetVO.java b/server/src/com/cloud/dc/DataCenterVnetVO.java index af6f4788a70..52d7ad2067b 100755 --- a/server/src/com/cloud/dc/DataCenterVnetVO.java +++ b/server/src/com/cloud/dc/DataCenterVnetVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_vnet_alloc") -public class DataCenterVnetVO { +public class DataCenterVnetVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/DcDetailVO.java b/server/src/com/cloud/dc/DcDetailVO.java index 49838637dec..15bfacbb3e1 100644 --- a/server/src/com/cloud/dc/DcDetailVO.java +++ b/server/src/com/cloud/dc/DcDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="data_center_details") -public class DcDetailVO { +public class DcDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/dc/HostPodVO.java b/server/src/com/cloud/dc/HostPodVO.java index 549e27eda3f..e4ba9d0c111 100644 --- a/server/src/com/cloud/dc/HostPodVO.java +++ b/server/src/com/cloud/dc/HostPodVO.java @@ -28,14 +28,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "host_pod_ref") -public class HostPodVO implements Pod, Identity { +public class HostPodVO implements Pod { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) long id; @@ -45,7 +46,7 @@ public class HostPodVO implements Pod, Identity { @Column(name = "data_center_id") private long dataCenterId; - + @Column(name = "gateway") private String gateway; @@ -57,14 +58,14 @@ public class HostPodVO implements Pod, Identity { @Column(name = "description") private String description; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; @Column(name = "external_dhcp") private Boolean externalDhcp; - + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @@ -128,12 +129,12 @@ public class HostPodVO implements Pod, Identity { public void setCidrSize(int cidrSize) { this.cidrSize = cidrSize; } - + @Override public String getGateway() { return gateway; } - + public void setGateway(String gateway) { this.gateway = gateway; } @@ -145,33 +146,33 @@ public class HostPodVO implements Pod, Identity { public void setDescription(String description) { this.description = description; } - + public AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + // Use for comparisons only. public HostPodVO(Long id) { this.id = id; } - + @Override public int hashCode() { return NumbersUtil.hash(id); } - + public boolean getExternalDhcp() { return externalDhcp; } - + public void setExternalDhcp(boolean use) { externalDhcp = use; } - + @Override public boolean equals(Object obj) { if (obj instanceof HostPodVO) { @@ -180,16 +181,16 @@ public class HostPodVO implements Pod, Identity { return false; } } - + public Date getRemoved() { return removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/dc/PodVlanMapVO.java b/server/src/com/cloud/dc/PodVlanMapVO.java index 2e419ba8141..8853fac48ca 100644 --- a/server/src/com/cloud/dc/PodVlanMapVO.java +++ b/server/src/com/cloud/dc/PodVlanMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="pod_vlan_map") -public class PodVlanMapVO { +public class PodVlanMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/PodVlanVO.java b/server/src/com/cloud/dc/PodVlanVO.java index 0d4f1cca27e..5324c8400f3 100755 --- a/server/src/com/cloud/dc/PodVlanVO.java +++ b/server/src/com/cloud/dc/PodVlanVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_pod_vlan_alloc") -public class PodVlanVO { +public class PodVlanVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -67,7 +69,7 @@ public class PodVlanVO { this.takenAt = null; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java index 1f252994ea1..6ad1ecd3c39 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -33,7 +35,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_storage_network_ip_address") @SecondaryTables({@SecondaryTable(name = "dc_storage_network_ip_range", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "range_id", referencedColumnName = "id")})}) -public class StorageNetworkIpAddressVO { +public class StorageNetworkIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -64,7 +66,7 @@ public class StorageNetworkIpAddressVO { protected StorageNetworkIpAddressVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java index bb17e4ab603..e410d22959e 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; diff --git a/server/src/com/cloud/dc/VlanVO.java b/server/src/com/cloud/dc/VlanVO.java index ff57f5e3d6f..fcb46c4971e 100644 --- a/server/src/com/cloud/dc/VlanVO.java +++ b/server/src/com/cloud/dc/VlanVO.java @@ -27,45 +27,46 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vlan") -public class VlanVO implements Vlan, Identity { - +public class VlanVO implements Vlan { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @Column(name="id") Long id; - - @Column(name="vlan_id") + + @Column(name="vlan_id") String vlanTag; - - @Column(name="vlan_gateway") + + @Column(name="vlan_gateway") String vlanGateway; - - @Column(name="vlan_netmask") + + @Column(name="vlan_netmask") String vlanNetmask; - - @Column(name="data_center_id") + + @Column(name="data_center_id") long dataCenterId; - - @Column(name="description") + + @Column(name="description") String ipRange; - + @Column(name="network_id") Long networkId; - + @Column(name="physical_network_id") Long physicalNetworkId; - + @Column(name="vlan_type") - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.STRING) VlanType vlanType; @Column(name="uuid") String uuid; - + public VlanVO(VlanType vlanType, String vlanTag, String vlanGateway, String vlanNetmask, long dataCenterId, String ipRange, Long networkId, Long physicalNetworkId) { this.vlanType = vlanType; this.vlanTag = vlanTag; @@ -77,16 +78,16 @@ public class VlanVO implements Vlan, Identity { this.uuid = UUID.randomUUID().toString(); this.physicalNetworkId = physicalNetworkId; } - + public VlanVO() { this.uuid = UUID.randomUUID().toString(); } - + @Override public long getId() { return id; } - + @Override public String getVlanTag() { return vlanTag; @@ -96,12 +97,12 @@ public class VlanVO implements Vlan, Identity { public String getVlanGateway() { return vlanGateway; } - + @Override public String getVlanNetmask() { return vlanNetmask; } - + @Override public long getDataCenterId() { return dataCenterId; @@ -125,12 +126,12 @@ public class VlanVO implements Vlan, Identity { public void setNetworkId(Long networkId) { this.networkId = networkId; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -142,7 +143,7 @@ public class VlanVO implements Vlan, Identity { public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } - + transient String toString; @Override public String toString() { @@ -152,5 +153,5 @@ public class VlanVO implements Vlan, Identity { } return toString; } - + } diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java index 88b0cbd8965..06e46fb9837 100755 --- a/server/src/com/cloud/deploy/FirstFitPlanner.java +++ b/server/src/com/cloud/deploy/FirstFitPlanner.java @@ -35,7 +35,6 @@ import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; -import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterVO; @@ -73,7 +72,6 @@ import com.cloud.storage.dao.VolumeDao; import com.cloud.user.AccountManager; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.StringUtils; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.vm.DiskProfile; diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index 02d3efe7ac3..bb4ce0cecf7 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -26,16 +26,17 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.apache.cloudstack.api.InternalIdentity; import org.apache.log4j.Logger; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; @Entity @Table(name="domain") -public class DomainVO implements Domain, Identity { +public class DomainVO implements Domain { public static final Logger s_logger = Logger.getLogger(DomainVO.class.getName()); - + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -49,10 +50,10 @@ public class DomainVO implements Domain, Identity { @Column(name="owner") private long accountId; - + @Column(name="path") private String path = null; - + @Column(name="level") private int level; @@ -64,18 +65,18 @@ public class DomainVO implements Domain, Identity { @Column(name="next_child_seq") private long nextChildSeq = 1L; - + @Column(name="state") private Domain.State state; - + @Column(name="network_domain") private String networkDomain; - + @Column(name="uuid") private String uuid; - + public DomainVO() {} - + public DomainVO(long id, String name, long owner, Long parentId, String networkDomain) { this(name, owner, parentId, networkDomain); this.id = id; @@ -102,7 +103,7 @@ public class DomainVO implements Domain, Identity { public Long getParent() { return parent; } - + @Override public void setParent(Long parent) { if(parent == null) { @@ -119,7 +120,7 @@ public class DomainVO implements Domain, Identity { public String getName() { return name; } - + @Override public void setName(String name) { this.name = name; @@ -129,59 +130,59 @@ public class DomainVO implements Domain, Identity { public long getAccountId() { return accountId; } - + @Override public Date getRemoved() { return removed; } - + @Override public String getPath() { return path; } - + @Override public void setPath(String path) { this.path = path; } - + @Override public int getLevel() { - return level; + return level; } - + public void setLevel(int level) { this.level = level; } - + @Override public int getChildCount() { - return childCount; + return childCount; } - + public void setChildCount(int count) { childCount = count; } - + @Override public long getNextChildSeq() { return nextChildSeq; } - + public void setNextChildSeq(long seq) { nextChildSeq = seq; } - - @Override + + @Override public Domain.State getState() { return state; } - + @Override public void setState(Domain.State state) { this.state = state; } - + @Override public String toString() { return new StringBuilder("Domain:").append(id).append(path).toString(); @@ -195,12 +196,12 @@ public class DomainVO implements Domain, Identity { public void setNetworkDomain(String domainSuffix) { this.networkDomain = domainSuffix; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/event/dao/EventJoinDao.java b/server/src/com/cloud/event/dao/EventJoinDao.java new file mode 100644 index 00000000000..cd37d7893df --- /dev/null +++ b/server/src/com/cloud/event/dao/EventJoinDao.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.event.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.EventResponse; + +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.event.Event; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.SearchCriteria; + +public interface EventJoinDao extends GenericDao { + + EventResponse newEventResponse(EventJoinVO uvo); + + EventJoinVO newEventView(Event vr); + + List searchByIds(Long... ids); + + List searchAllEvents(SearchCriteria sc, Filter filter); + + EventJoinVO findCompletedEvent(long startId); +} diff --git a/server/src/com/cloud/event/dao/EventJoinDaoImpl.java b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java new file mode 100644 index 00000000000..764df99557f --- /dev/null +++ b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java @@ -0,0 +1,124 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.event.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.EventJoinVO; + +import org.apache.cloudstack.api.response.EventResponse; +import com.cloud.event.Event; +import com.cloud.event.Event.State; +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={EventJoinDao.class}) +public class EventJoinDaoImpl extends GenericDaoBase implements EventJoinDao { + public static final Logger s_logger = Logger.getLogger(EventJoinDaoImpl.class); + + private SearchBuilder vrSearch; + + private SearchBuilder vrIdSearch; + + private SearchBuilder CompletedEventSearch; + + protected EventJoinDaoImpl() { + + vrSearch = createSearchBuilder(); + vrSearch.and("idIN", vrSearch.entity().getId(), SearchCriteria.Op.IN); + vrSearch.done(); + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + CompletedEventSearch = createSearchBuilder(); + CompletedEventSearch.and("state",CompletedEventSearch.entity().getState(),SearchCriteria.Op.EQ); + CompletedEventSearch.and("startId", CompletedEventSearch.entity().getStartId(), SearchCriteria.Op.EQ); + CompletedEventSearch.done(); + + + this._count = "select count(distinct id) from event_view WHERE "; + } + + + + @Override + public List searchAllEvents(SearchCriteria sc, Filter filter) { + return listIncludingRemovedBy(sc, filter); + } + + + + @Override + public EventJoinVO findCompletedEvent(long startId) { + SearchCriteria sc = CompletedEventSearch.create(); + sc.setParameters("state", State.Completed); + sc.setParameters("startId", startId); + return findOneIncludingRemovedBy(sc); + } + + + + @Override + public EventResponse newEventResponse(EventJoinVO event) { + EventResponse responseEvent = new EventResponse(); + responseEvent.setCreated(event.getCreateDate()); + responseEvent.setDescription(event.getDescription()); + responseEvent.setEventType(event.getType()); + responseEvent.setId(event.getUuid()); + responseEvent.setLevel(event.getLevel()); + responseEvent.setParentId(event.getStartUuid()); + responseEvent.setState(event.getState()); + responseEvent.setUsername(event.getUserName()); + + ApiResponseHelper.populateOwner(responseEvent, event); + responseEvent.setObjectName("event"); + return responseEvent; + } + + + + @Override + public List searchByIds(Long... ids) { + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + return searchIncludingRemoved(sc, null, null, false); + } + + + @Override + public EventJoinVO newEventView(Event vr) { + + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", vr.getId()); + List vms = searchIncludingRemoved(sc, null, null, false); + assert vms != null && vms.size() == 1 : "No event found for event id " + vr.getId(); + return vms.get(0); + + } + +} diff --git a/server/src/com/cloud/ha/HaWorkVO.java b/server/src/com/cloud/ha/HaWorkVO.java index d5f41e0f76a..adfa3ec4e27 100644 --- a/server/src/com/cloud/ha/HaWorkVO.java +++ b/server/src/com/cloud/ha/HaWorkVO.java @@ -34,10 +34,11 @@ import com.cloud.ha.HighAvailabilityManager.WorkType; import com.cloud.utils.db.GenericDao; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="op_ha_work") -public class HaWorkVO { +public class HaWorkVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -87,7 +88,7 @@ public class HaWorkVO { protected HaWorkVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/host/dao/HostDaoImpl.java b/server/src/com/cloud/host/dao/HostDaoImpl.java index ab1e77eb7f4..0881675dda7 100755 --- a/server/src/com/cloud/host/dao/HostDaoImpl.java +++ b/server/src/com/cloud/host/dao/HostDaoImpl.java @@ -63,7 +63,7 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = { HostDao.class }) @DB(txn = false) @TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1) -public class HostDaoImpl extends GenericDaoBase implements HostDao { +public class HostDaoImpl extends GenericDaoBase implements HostDao { //FIXME: , ExternalIdDao { private static final Logger s_logger = Logger.getLogger(HostDaoImpl.class); private static final Logger status_logger = Logger.getLogger(Status.class); private static final Logger state_logger = Logger.getLogger(ResourceState.class); diff --git a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java index 242852fc681..2efe6d35098 100644 --- a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java +++ b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java @@ -62,6 +62,7 @@ public abstract class HypervisorGuruBase extends AdapterBase implements Hypervis to.setIsolationuri(profile.getIsolationUri()); to.setNetworkRateMbps(profile.getNetworkRate()); to.setName(profile.getName()); + to.setSecurityGroupEnabled(profile.isSecurityGroupEnabled()); // Workaround to make sure the TO has the UUID we need for Niciri integration NicVO nicVO = _nicDao.findById(profile.getId()); diff --git a/server/src/com/cloud/keystore/KeystoreVO.java b/server/src/com/cloud/keystore/KeystoreVO.java index a7be602fe45..f590607e3a1 100644 --- a/server/src/com/cloud/keystore/KeystoreVO.java +++ b/server/src/com/cloud/keystore/KeystoreVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.keystore; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="keystore") -public class KeystoreVO { +public class KeystoreVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -49,7 +51,7 @@ public class KeystoreVO { public KeystoreVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/maint/AgentUpgradeVO.java b/server/src/com/cloud/maint/AgentUpgradeVO.java index b784ead7825..b36f5b7dd6c 100644 --- a/server/src/com/cloud/maint/AgentUpgradeVO.java +++ b/server/src/com/cloud/maint/AgentUpgradeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.maint; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name="op_host_upgrade") -public class AgentUpgradeVO { +public class AgentUpgradeVO implements InternalIdentity { @Id @Column(name="host_id") private long id; diff --git a/server/src/com/cloud/migration/DiskOffering20VO.java b/server/src/com/cloud/migration/DiskOffering20VO.java index 8c261715e39..e50328d7cd7 100644 --- a/server/src/com/cloud/migration/DiskOffering20VO.java +++ b/server/src/com/cloud/migration/DiskOffering20VO.java @@ -26,10 +26,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="disk_offering") -public class DiskOffering20VO { +public class DiskOffering20VO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -64,7 +65,7 @@ public class DiskOffering20VO { this.mirrored = mirrored; } - public Long getId() { + public long getId() { return id; } public void setId(Long id) { diff --git a/server/src/com/cloud/migration/DiskOffering21VO.java b/server/src/com/cloud/migration/DiskOffering21VO.java index f428c519e87..593f7ba61ff 100644 --- a/server/src/com/cloud/migration/DiskOffering21VO.java +++ b/server/src/com/cloud/migration/DiskOffering21VO.java @@ -32,12 +32,13 @@ import javax.persistence.Table; import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="disk_offering_21") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class DiskOffering21VO { +public class DiskOffering21VO implements InternalIdentity { public enum Type { Disk, Service diff --git a/server/src/com/cloud/migration/ServiceOffering20VO.java b/server/src/com/cloud/migration/ServiceOffering20VO.java index 065c9246964..bed29ecf3b9 100644 --- a/server/src/com/cloud/migration/ServiceOffering20VO.java +++ b/server/src/com/cloud/migration/ServiceOffering20VO.java @@ -30,10 +30,11 @@ import javax.persistence.Table; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="service_offering") -public class ServiceOffering20VO { +public class ServiceOffering20VO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -108,7 +109,7 @@ public class ServiceOffering20VO { this.offerHA = offerHA; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/migration/ServiceOffering21VO.java b/server/src/com/cloud/migration/ServiceOffering21VO.java index adfac1aad61..fdec30e3b8a 100644 --- a/server/src/com/cloud/migration/ServiceOffering21VO.java +++ b/server/src/com/cloud/migration/ServiceOffering21VO.java @@ -32,25 +32,25 @@ import com.cloud.offering.ServiceOffering; public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffering { @Column(name="cpu") private int cpu; - + @Column(name="speed") private int speed; - + @Column(name="ram_size") private int ramSize; - + @Column(name="nw_rate") private Integer rateMbps; - + @Column(name="mc_rate") private Integer multicastRateMbps; - + @Column(name="ha_enabled") private boolean offerHA; - + @Column(name="host_tag") - private String hostTag; - + private String hostTag; + protected ServiceOffering21VO() { super(); } @@ -64,19 +64,19 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe this.multicastRateMbps = multicastRateMbps; this.offerHA = offerHA; } - + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags); this.hostTag = hostTag; } - + @Override public boolean getOfferHA() { return offerHA; } - @Override + @Override public boolean getLimitCpuUse() { return false; } @@ -84,7 +84,7 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setOfferHA(boolean offerHA) { this.offerHA = offerHA; } - + @Override @Transient public String[] getTagsArray() { @@ -92,15 +92,15 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe if (tags == null || tags.length() == 0) { return new String[0]; } - + return tags.split(","); } - + @Override public int getCpu() { return cpu; } - + public void setCpu(int cpu) { this.cpu = cpu; } @@ -112,17 +112,17 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setRamSize(int ramSize) { this.ramSize = ramSize; } - + @Override public int getSpeed() { return speed; } - + @Override public int getRamSize() { return ramSize; } - + public void setRateMbps(Integer rateMbps) { this.rateMbps = rateMbps; } @@ -135,7 +135,7 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setMulticastRateMbps(Integer multicastRateMbps) { this.multicastRateMbps = multicastRateMbps; } - + @Override public Integer getMulticastRateMbps() { return multicastRateMbps; @@ -147,8 +147,8 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setHostTag(String hostTag) { this.hostTag = hostTag; - } - + } + public String getHostTag() { return hostTag; } @@ -156,10 +156,18 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe @Override public boolean getDefaultUse() { return false; - } - + } + @Override public String getSystemVmType() { return null; - } + } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + + } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManager.java b/server/src/com/cloud/network/ExternalFirewallDeviceManager.java index f6a39d96cea..f758ca1d341 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceManager.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceManager.java @@ -22,6 +22,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.PortForwardingRule; import com.cloud.resource.ServerResource; import com.cloud.utils.component.Manager; @@ -94,4 +95,12 @@ public interface ExternalFirewallDeviceManager extends Manager { */ public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; + /** + * applies port forwarding rules + * @param network guest network if + * @param rules load balancer rules + * @return true if successfully applied rules + * @throws ResourceUnavailableException + */ + public boolean applyPortForwardingRules(Network network, List rules) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java index 6b05e25d15f..582e86b30ec 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -30,17 +30,18 @@ import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.StartupExternalLoadBalancerCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; +import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; +import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -49,7 +50,6 @@ import com.cloud.dc.Vlan; import com.cloud.dc.VlanVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; -import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -59,12 +59,10 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Service; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.ExternalFirewallDeviceDao; +import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.InlineLoadBalancerNicMapDao; import com.cloud.network.dao.LoadBalancerDao; @@ -76,17 +74,17 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNatRule; +import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.dao.AccountDao; @@ -133,6 +131,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject VpnUserDao _vpnUsersDao; @Inject HostDetailsDao _hostDetailDao; + @Inject FirewallRulesDao _fwRulesDao; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalFirewallDeviceManagerImpl.class); private long _defaultFwCapacity; @@ -166,10 +165,10 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), ntwkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null ) { - throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + + throw new CloudRuntimeException("Network Service Provider: " + ntwkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device" ); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + + throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is not added or in shutdown state in the physical network: " + physicalNetworkId + "to add this device" ); } @@ -214,7 +213,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl capacity = _defaultFwCapacity; } - ExternalFirewallDeviceVO fwDevice = new ExternalFirewallDeviceVO(externalFirewall.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(), + ExternalFirewallDeviceVO fwDevice = new ExternalFirewallDeviceVO(externalFirewall.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(), deviceName, capacity, dedicatedUse); _externalFirewallDeviceDao.persist(fwDevice); @@ -236,14 +235,26 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl throw new InvalidParameterValueException("Could not find an external firewall with ID: " + hostId); } + DetailVO fwHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.FIREWALL_DEVICE_ID); + long fwDeviceId = Long.parseLong(fwHostDetails.getValue()); + + // check if any networks are using this balancer device + List networks = _networkExternalFirewallDao.listByFirewallDeviceId(fwDeviceId); + if ((networks != null) && !networks.isEmpty()) { + throw new CloudRuntimeException("Delete can not be done as there are networks using the firewall device "); + } + try { - if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) { - return true; - } else { - return false; - } - } catch (AgentUnavailableException e) { - s_logger.debug(e); + // put the host in maintenance state in order for it to be deleted + externalFirewall.setResourceState(ResourceState.Maintenance); + _hostDao.update(hostId, externalFirewall); + _resourceMgr.deleteHost(hostId, false, false); + + // delete the external load balancer entry + _externalFirewallDeviceDao.remove(fwDeviceId); + return true; + } catch (Exception e) { + s_logger.debug("Failed to delete external firewall device due to " + e.getMessage()); return false; } } @@ -265,7 +276,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), fwNetworkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { - return null; + return null; } List fwDevices = _externalFirewallDeviceDao.listByPhysicalNetworkAndProvider(physicalNetworkId, ntwkSvcProvider.getProviderName()); @@ -274,7 +285,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } return firewallHosts; } - + public ExternalFirewallDeviceVO getExternalFirewallForNetwork(Network network) { NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); if (fwDeviceForNetwork != null) { @@ -296,7 +307,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl long physicalNetworkId = network.getPhysicalNetworkId(); List fwDevices = _externalFirewallDeviceDao.listByPhysicalNetwork(physicalNetworkId); - // loop through the firewall device in the physical network and pick the first-fit + // loop through the firewall device in the physical network and pick the first-fit for (ExternalFirewallDeviceVO fwDevice: fwDevices) { // max number of guest networks that can be mapped to this device long fullCapacity = fwDevice.getCapacity(); @@ -305,7 +316,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } // get the list of guest networks that are mapped to this load balancer - List mappedNetworks = _networkExternalFirewallDao.listByFirewallDeviceId(fwDevice.getId()); + List mappedNetworks = _networkExternalFirewallDao.listByFirewallDeviceId(fwDevice.getId()); long usedCapacity = (mappedNetworks == null) ? 0 : mappedNetworks.size(); if ((fullCapacity - usedCapacity) > 0) { @@ -316,6 +327,32 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl " to implement the network", DataCenter.class, network.getDataCenterId()); } + @DB + protected boolean freeFirewallForNetwork(Network network) { + Transaction txn = Transaction.currentTxn(); + GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap"); + try { + if (deviceMapLock.lock(120)) { + try { + NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); + if (fwDeviceForNetwork != null) { + _networkExternalFirewallDao.remove(fwDeviceForNetwork.getId()); + } + } catch (Exception exception) { + txn.rollback(); + s_logger.error("Failed to release firewall device for the network" + network.getId() + " due to " + exception.getMessage()); + return false; + } finally { + deviceMapLock.unlock(); + } + } + } finally { + deviceMapLock.releaseRef(); + } + txn.commit(); + return true; + } + public String getExternalNetworkResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @@ -323,7 +360,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall) { Map fwDetails = _hostDetailDao.findDetails(externalFirewall.getId()); ExternalFirewallResponse response = new ExternalFirewallResponse(); - response.setId(externalFirewall.getId()); + response.setId(externalFirewall.getUuid()); response.setIpAddress(externalFirewall.getPrivateIpAddress()); response.setUsername(fwDetails.get("username")); response.setPublicInterface(fwDetails.get("publicInterface")); @@ -352,7 +389,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl try { if (deviceMapLock.lock(120)) { try { - ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network); + ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network); long externalFirewallId = device.getId(); NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId); @@ -377,10 +414,10 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId()); - - NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); - + IPAddressVO sourceNatIp = null; if (!sharedSourceNat) { // Get the source NAT IP address for this account @@ -388,7 +425,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl zoneId, true); if (sourceNatIps.size() != 1) { - String errorMsg = "External firewall was unable to find the source NAT IP address for account " + String errorMsg = "External firewall was unable to find the source NAT IP address for account " + account.getAccountName(); s_logger.error(errorMsg); return true; @@ -422,31 +459,50 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalFirewall.getId(), cmd); + List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId()); + if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : "answer was null"; String msg = "External firewall was unable to " + action + " the guest network on the external firewall in zone " + zone.getName() + " due to " + answerDetails; s_logger.error(msg); + if (!add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { + // If we failed the implementation as well, then just return, no complain + s_logger.error("Skip the shutdown of guest network on SRX because it seems we didn't implement it as well"); + return true; + } throw new ResourceUnavailableException(msg, DataCenter.class, zoneId); } - List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId()); if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { // Insert a new NIC for this guest network to reserve the gateway address savePlaceholderNic(network, network.getGateway()); } - + // Delete any mappings used for inline external load balancers in this network List nicsInNetwork = _nicDao.listByNetworkId(network.getId()); for (NicVO nic : nicsInNetwork) { InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId()); - + if (mapping != null) { _nicDao.expunge(mapping.getNicId()); _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); } } + // on network shutdown, delete placeHolder nics used for the firewall device + if (!add) { + List guestIps = _nicDao.listByNetworkId(network.getId()); + for (NicVO guestIp : guestIps) { + // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy + if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getIp4Address().equals(network.getGateway())) { + _nicDao.remove(guestIp.getId()); + } + } + + freeFirewallForNetwork(network); + } + String action = add ? "implemented" : "shut down"; s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); @@ -456,6 +512,37 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Override public boolean applyFirewallRules(Network network, List rules) throws ResourceUnavailableException { // Find the external firewall in this zone + long zoneId = network.getDataCenterId(); + DataCenterVO zone = _dcDao.findById(zoneId); + ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); + // During destroy, device reference may already been clean up, then we just return true + if (fwDeviceVO == null) { + return true; + } + HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); + + assert(externalFirewall != null); + + if (network.getState() == Network.State.Allocated) { + s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); + return true; + } + + List rulesTO = new ArrayList(); + + for (FirewallRule rule : rules) { + IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); + FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr()); + rulesTO.add(ruleTO); + } + + //Firewall rules configured for staticNAT/PF + sendFirewallRules(rulesTO, zone, externalFirewall.getId()); + + return true; + } + + public boolean applyStaticNatRules(Network network, List rules) throws ResourceUnavailableException { long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); @@ -469,32 +556,34 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } List staticNatRules = new ArrayList(); - List portForwardingRules = new ArrayList(); - - for (FirewallRule rule : rules) { + + for (StaticNat rule : rules) { IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); - if (rule.getPurpose() == Purpose.StaticNat) { - StaticNatRule staticNatRule = (StaticNatRule) rule; - StaticNatRuleTO ruleTO = new StaticNatRuleTO(staticNatRule, vlan.getVlanTag(), sourceIp.getAddress().addr(), staticNatRule.getDestIpAddress()); - staticNatRules.add(ruleTO); - } else if (rule.getPurpose() == Purpose.PortForwarding) { - PortForwardingRuleTO ruleTO = new PortForwardingRuleTO((PortForwardingRule) rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); - portForwardingRules.add(ruleTO); - } + StaticNatRuleTO ruleTO = new StaticNatRuleTO(0,vlan.getVlanTag(), sourceIp.getAddress().addr(), -1, -1, rule.getDestIpAddress(), -1, -1, "any", rule.isForRevoke(), false); + staticNatRules.add(ruleTO); } - - // Apply static nat rules - applyStaticNatRules(staticNatRules, zone, externalFirewall.getId()); - - // apply port forwarding rules - applyPortForwardingRules(portForwardingRules, zone, externalFirewall.getId()); - + + sendStaticNatRules(staticNatRules, zone, externalFirewall.getId()); + return true; } + + protected void sendFirewallRules(List firewallRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + if (!firewallRules.isEmpty()) { + SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(firewallRules); + Answer answer = _agentMgr.easySend(externalFirewallId, cmd); + if (answer == null || !answer.getResult()) { + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + String msg = "External firewall was unable to apply static nat rules to the SRX appliance in zone " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); + } + } + } - protected void applyStaticNatRules(List staticNatRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + protected void sendStaticNatRules(List staticNatRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { if (!staticNatRules.isEmpty()) { SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(staticNatRules, null); Answer answer = _agentMgr.easySend(externalFirewallId, cmd); @@ -507,7 +596,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } } - protected void applyPortForwardingRules(List portForwardingRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + protected void sendPortForwardingRules(List portForwardingRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { if (!portForwardingRules.isEmpty()) { SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(portForwardingRules); Answer answer = _agentMgr.easySend(externalFirewallId, cmd); @@ -531,26 +620,26 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if (externalFirewall == null) { return false; } - + // Create/delete VPN IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId()); - + // Mask the IP range with the network's VLAN tag String[] ipRange = vpn.getIpRange().split("-"); DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag); int cidrSize = getGloballyConfiguredCidrSize(); - + for (int i = 0; i < 2; i++) { ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize))); } - + String maskedIpRange = ipRange[0] + "-" + ipRange[1]; - + RemoteAccessVpnCfgCommand createVpnCmd = new RemoteAccessVpnCfgCommand(create, ip.getAddress().addr(), vpn.getLocalIp(), maskedIpRange, vpn.getIpsecPresharedKey()); createVpnCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); - createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); + createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; @@ -558,12 +647,12 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); } - + // Add/delete users List vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); return manageRemoteAccessVpnUsers(network, vpn, vpnUsers); - } - + } + public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List vpnUsers) throws ResourceUnavailableException { ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); @@ -571,7 +660,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl if (externalFirewall == null) { return false; } - + List addUsers = new ArrayList(); List removeUsers = new ArrayList(); for (VpnUser user : vpnUsers) { @@ -582,11 +671,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl removeUsers.add(user); } } - + VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers); addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId())); - addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); - + addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr()); + Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd); if (answer == null || !answer.getResult()) { String details = (answer != null) ? answer.getDetails() : "details unavailable"; @@ -595,7 +684,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl s_logger.error(msg); throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); } - + return true; } @@ -612,7 +701,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl int lowestVlanTag = Integer.valueOf(vlanRange[0]); return vlanTag - lowestVlanTag; } - + private NicVO savePlaceholderNic(Network network, String ipAddress) { NicVO nic = new NicVO(null, null, network.getId(), null); nic.setIp4Address(ipAddress); @@ -620,7 +709,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl nic.setState(State.Reserved); return _nicDao.persist(nic); } - + public int getGloballyConfiguredCidrSize() { try { String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key()); @@ -648,7 +737,38 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub - return null; + if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) { + return null; + } + return new DeleteHostAnswer(true); + } + + @Override + public boolean applyPortForwardingRules(Network network, List rules) throws ResourceUnavailableException { + // Find the external firewall in this zone + long zoneId = network.getDataCenterId(); + DataCenterVO zone = _dcDao.findById(zoneId); + ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); + HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); + + assert(externalFirewall != null); + + if (network.getState() == Network.State.Allocated) { + s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); + return true; + } + + List pfRules = new ArrayList(); + + for (PortForwardingRule rule : rules) { + IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); + Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); + + PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); + pfRules.add(ruleTO); + } + + sendPortForwardingRules(pfRules, zone, externalFirewall.getId()); + return true; } } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceVO.java b/server/src/com/cloud/network/ExternalFirewallDeviceVO.java index 9b587776979..83be8c40b3d 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceVO.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceVO.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; @@ -33,7 +36,7 @@ import javax.persistence.Table; @Entity @Table(name="external_firewall_devices") -public class ExternalFirewallDeviceVO { +public class ExternalFirewallDeviceVO implements InternalIdentity, Identity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java index 97c63064c32..718f130d764 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -36,11 +36,9 @@ import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -48,7 +46,6 @@ import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.Pod; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; @@ -63,7 +60,8 @@ import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceAllocationState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; @@ -79,15 +77,17 @@ import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; +import com.cloud.network.element.IpDeployer; +import com.cloud.network.element.NetworkElement; +import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.resource.CreateLoadBalancerApplianceAnswer; import com.cloud.network.resource.DestroyLoadBalancerApplianceAnswer; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.StaticNatRuleImpl; +import com.cloud.network.rules.StaticNat; +import com.cloud.network.rules.StaticNatImpl; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -96,7 +96,7 @@ import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.dao.AccountDao; @@ -241,7 +241,6 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase if (host != null) { boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; - boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false; long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; @@ -249,7 +248,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase txn.start(); ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(), - deviceName, capacity, dedicatedUse, inline); + deviceName, capacity, dedicatedUse); _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); @@ -341,7 +340,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); - response.setId(externalLoadBalancer.getId()); + response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); @@ -691,30 +690,6 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return false; } - HostVO getFirewallProviderForNetwork(Network network) { - HostVO fwHost = null; - - // get the firewall provider (could be either virtual router or external firewall device) for the network - String fwProvider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Firewall); - - if (fwProvider.equalsIgnoreCase("VirtualRouter")) { - // FIXME: use network service provider container framework support to implement on virtual router - } else { - NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); - assert (fwDeviceForNetwork != null) : "Why firewall provider is not ready for the network to apply static nat rules?"; - long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId(); - ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId); - fwHost = _hostDao.findById(fwDevice.getHostId()); - } - - return fwHost; - } - - private boolean externalLoadBalancerIsInline(HostVO externalLoadBalancer) { - DetailVO detail = _hostDetailDao.findDetail(externalLoadBalancer.getId(), "inline"); - return (detail != null && detail.getValue().equals("true")); - } - private NicVO savePlaceholderNic(Network network, String ipAddress) { NicVO nic = new NicVO(null, null, network.getId(), null); nic.setIp4Address(ipAddress); @@ -735,31 +710,115 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return null; } - private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, HostVO firewallHost, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { - List staticNatRules = new ArrayList(); + private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { + List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); - VlanVO vlan = _vlanDao.findById(ipVO.getVlanId()); - FirewallRuleVO fwRule = new FirewallRuleVO(null, ipVO.getId(), -1, -1, "any", network.getId(), network.getAccountId(), network.getDomainId(), Purpose.StaticNat, null, null, null, null, null); - FirewallRule.State state = !revoked ? FirewallRule.State.Add : FirewallRule.State.Revoke; - fwRule.setState(state); - StaticNatRule rule = new StaticNatRuleImpl(fwRule, privateIp); - StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, vlan.getVlanTag(), publicIp, privateIp); - staticNatRules.add(ruleTO); - - applyStaticNatRules(staticNatRules, network, firewallHost.getId()); + StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), + network.getId(), ipVO.getId(), privateIp, revoked); + staticNats.add(staticNat); + StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); + element.applyStaticNats(network, staticNats); } - protected void applyStaticNatRules(List staticNatRules, Network network, long firewallHostId) throws ResourceUnavailableException { - if (!staticNatRules.isEmpty()) { - SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(staticNatRules, null); - Answer answer = _agentMgr.easySend(firewallHostId, cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "firewall provider for the network was unable to apply static nat rules due to: " + details + "."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, Network.class, network.getId()); + private enum MappingState { + Create, + Remove, + Unchanged, + }; + + private class MappingNic { + private NicVO nic; + private MappingState state; + + public NicVO getNic() { + return nic; + } + public void setNic(NicVO nic) { + this.nic = nic; + } + public MappingState getState() { + return state; + } + public void setState(MappingState state) { + this.state = state; + } + }; + + private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { + String srcIp = _networkMgr.getIp(sourceIpId).getAddress().addr(); + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); + NicVO loadBalancingIpNic = null; + MappingNic nic = new MappingNic(); + nic.setState(MappingState.Unchanged); + if (!revoked) { + if (mapping == null) { + // Acquire a new guest IP address and save it as the load balancing IP address + String loadBalancingIpAddress = existedGuestIp; + + if (loadBalancingIpAddress == null) { + loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); + } + + if (loadBalancingIpAddress == null) { + String msg = "Ran out of guest IP addresses."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + } + + // If a NIC doesn't exist for the load balancing IP address, create one + loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); + if (loadBalancingIpNic == null) { + loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); + } + + // Save a mapping between the source IP address and the load balancing IP address NIC + mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); + _inlineLoadBalancerNicMapDao.persist(mapping); + + // On the firewall provider for the network, create a static NAT rule between the source IP + // address and the load balancing IP address + try { + applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + } catch (ResourceUnavailableException ex) { + // Rollback db operation + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + _nicDao.expunge(loadBalancingIpNic.getId()); + throw ex; + } + + s_logger.debug("Created static nat rule for inline load balancer"); + nic.setState(MappingState.Create); + } else { + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + } + } else { + if (mapping != null) { + // Find the NIC that the mapping refers to + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + + int count = _networkMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); + if (count == 0) { + // On the firewall provider for the network, delete the static NAT rule between the source IP + // address and the load balancing IP address + applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + + // Delete the mapping between the source IP address and the load balancing IP address + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + + // Delete the NIC + _nicDao.expunge(loadBalancingIpNic.getId()); + + s_logger.debug("Revoked static nat rule for inline load balancer"); + nic.setState(MappingState.Remove); + } + } else { + s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); + return null; } } + + nic.setNic(loadBalancingIpNic); + return nic; } @Override @@ -788,7 +847,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); - boolean externalLoadBalancerIsInline = externalLoadBalancerIsInline(externalLoadBalancer); + boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); @@ -796,6 +855,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase } List loadBalancersToApply = new ArrayList(); + List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); @@ -806,62 +866,13 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase String srcIp = _networkModel.getIp(rule.getSourceIpAddressId()).getAddress().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); - List sourceCidrs = rule.getSourceCidrList(); if (externalLoadBalancerIsInline) { - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); - NicVO loadBalancingIpNic = null; - HostVO firewallProviderHost = null; - - if (externalLoadBalancerIsInline) { - firewallProviderHost = getFirewallProviderForNetwork(network); - } - - if (!revoked) { - if (mapping == null) { - // Acquire a new guest IP address and save it as the load balancing IP address - String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); - - if (loadBalancingIpAddress == null) { - String msg = "Ran out of guest IP addresses."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - - // If a NIC doesn't exist for the load balancing IP address, create one - loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); - if (loadBalancingIpNic == null) { - loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); - } - - // Save a mapping between the source IP address and the load balancing IP address NIC - mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); - _inlineLoadBalancerNicMapDao.persist(mapping); - - // On the firewall provider for the network, create a static NAT rule between the source IP -// address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - } else { - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - } - } else { - if (mapping != null) { - // Find the NIC that the mapping refers to - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - - // On the firewall provider for the network, delete the static NAT rule between the source IP -// address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - - // Delete the mapping between the source IP address and the load balancing IP address - _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); - - // Delete the NIC - _nicDao.expunge(loadBalancingIpNic.getId()); - } else { - s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); - continue; - } + MappingNic nic = getLoadBalancingIpNic(zone, network, rule.getSourceIpAddressId(), revoked, null); + mappingStates.add(nic.getState()); + NicVO loadBalancingIpNic = nic.getNic(); + if (loadBalancingIpNic == null) { + continue; } // Change the source IP address for the load balancing rule to be the load balancing IP address @@ -869,27 +880,50 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase } if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { - LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, destinations, rule.getStickinessPolicies()); - if(rule.isAutoScaleConfig()) { + boolean inline = _networkMgr.isNetworkInlineMode(network); + LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies()); + if (rule.isAutoScaleConfig()) { loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); } loadBalancersToApply.add(loadBalancer); } } - if (loadBalancersToApply.size() > 0) { - int numLoadBalancersForCommand = loadBalancersToApply.size(); - LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); - LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); - long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); - cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); - Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + try { + if (loadBalancersToApply.size() > 0) { + int numLoadBalancersForCommand = loadBalancersToApply.size(); + LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); + LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null); + long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost()); + cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); + Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd); + if (answer == null || !answer.getResult()) { + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + String msg = "Unable to apply load balancer rules to the external load balancer appliance in zone " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + } } + } catch (Exception ex) { + if (externalLoadBalancerIsInline) { + s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); + String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); + // Rollback static NAT operation in current session + for (int i = 0; i < loadBalancingRules.size(); i++) { + LoadBalancingRule rule = loadBalancingRules.get(i); + MappingState state = mappingStates.get(i); + boolean revoke; + if (state == MappingState.Create) { + revoke = true; + } else if (state == MappingState.Remove) { + revoke = false; + } else { + continue; + } + getLoadBalancingIpNic(zone, network, rule.getSourceIpAddressId(), revoke, existedGuestIp); + } + } + throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); } return true; @@ -907,11 +941,17 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase HostVO externalLoadBalancer = null; if (add) { - ExternalLoadBalancerDeviceVO lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); + ExternalLoadBalancerDeviceVO lbDeviceVO = null; + // on restart network, device could have been allocated already, skip allocation if a device is assigned + lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { - String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); - s_logger.error(msg); - throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); + // allocate a load balancer device for the network + lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); + if (lbDeviceVO == null) { + String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); + s_logger.error(msg); + throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); + } } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); @@ -935,6 +975,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase Integer networkRate = _networkModel.getNetworkRate(guestConfig.getId(), null); if (add) { + // on restart network, network could have already been implemented. If already implemented then return + NicVO selfipNic = getPlaceholderNic(guestConfig); + if (selfipNic != null) { + return true; + } + // Acquire a self-ip address from the guest network IP address range selfIp = _networkMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { @@ -953,7 +999,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase selfIp = selfipNic.getIp4Address(); } - IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, String.valueOf(guestVlanTag), selfIp, guestVlanNetmask, null, networkRate, false); + // It's a hack, using isOneToOneNat field for indicate if it's inline or not + boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); + IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, String.valueOf(guestVlanTag), selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); @@ -961,8 +1009,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; - String answerDetails = (answer != null) ? answer.getDetails() : "answer was null"; - String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + " due to " + answerDetails; + String answerDetails = (answer != null) ? answer.getDetails() : null; + answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; + String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } @@ -1034,4 +1083,25 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return new DeleteHostAnswer(true); } + protected IpDeployer getIpDeployerForInlineMode(Network network) { + //We won't deploy IP, instead the firewall in front of us would do it + List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); + //Only support one provider now + if (providers == null) { + s_logger.error("Cannot find firewall provider for network " + network.getId()); + return null; + } + if (providers.size() != 1) { + s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); + return null; + } + + NetworkElement element = _networkMgr.getElementImplementingProvider(providers.get(0).getName()); + if (!(element instanceof IpDeployer)) { + s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); + return null; + } + s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); + return (IpDeployer)element; + } } diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java index 190067b653b..d77352a9614 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java @@ -16,6 +16,10 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; + import java.util.UUID; import javax.persistence.Column; @@ -33,7 +37,7 @@ import javax.persistence.Table; @Entity @Table(name="external_load_balancer_devices") -public class ExternalLoadBalancerDeviceVO { +public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -66,9 +70,6 @@ public class ExternalLoadBalancerDeviceVO { @Column(name="is_managed") private boolean isManagedDevice; - @Column(name="is_inline") - private boolean isInlineMode; - @Column(name="is_dedicated") private boolean isDedicatedDevice; @@ -92,7 +93,7 @@ public class ExternalLoadBalancerDeviceVO { } public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, - long capacity, boolean dedicated, boolean inline) { + long capacity, boolean dedicated) { this.physicalNetworkId = physicalNetworkId; this.providerName = provider_name; this.deviceName = device_name; @@ -101,7 +102,6 @@ public class ExternalLoadBalancerDeviceVO { this.allocationState = LBDeviceAllocationState.Free; this.capacity = capacity; this.isDedicatedDevice = dedicated; - this.isInlineMode = inline; this.isManagedDevice = false; this.state = LBDeviceState.Enabled; this.uuid = UUID.randomUUID().toString(); @@ -112,8 +112,8 @@ public class ExternalLoadBalancerDeviceVO { } public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, - long capacity, boolean dedicated, boolean inline, boolean managed, long parentHostId) { - this(hostId, physicalNetworkId, provider_name, device_name, capacity, dedicated, inline); + long capacity, boolean dedicated, boolean managed, long parentHostId) { + this(hostId, physicalNetworkId, provider_name, device_name, capacity, dedicated); this.isManagedDevice = managed; this.parentHostId = parentHostId; } @@ -182,14 +182,6 @@ public class ExternalLoadBalancerDeviceVO { this.isManagedDevice = managed; } - public boolean getIsInLineMode () { - return isInlineMode; - } - - public void setIsInlineMode(boolean inline) { - this.isInlineMode = inline; - } - public boolean getIsDedicatedDevice() { return isDedicatedDevice; } diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index aae77368d6c..751777cc5ff 100755 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -26,27 +26,29 @@ import java.util.concurrent.ScheduledExecutorService; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.network.AddNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.ListNetworkDeviceCmd; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; -import com.cloud.api.ApiConstants; -import com.cloud.api.IdentityService; -import com.cloud.api.PlugService; -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; +import com.cloud.api.ApiDBUtils; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.IdentityService; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkDeviceCmd; import com.cloud.baremetal.ExternalDhcpManager; import com.cloud.baremetal.PxeServerManager; import com.cloud.baremetal.PxeServerProfile; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenter; +import com.cloud.dc.Pod; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; import com.cloud.host.Host; import com.cloud.host.HostVO; -import com.cloud.host.Host.Type; import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.dao.ExternalFirewallDeviceDao; import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; import com.cloud.network.dao.IPAddressDao; @@ -60,9 +62,8 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.resource.ServerResource; import com.cloud.server.ManagementServer; -import com.cloud.server.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; import com.cloud.server.api.response.NwDeviceDhcpResponse; import com.cloud.server.api.response.PxePingResponse; import com.cloud.user.AccountManager; @@ -106,17 +107,17 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa ScheduledExecutorService _executor; int _externalNetworkStatsInterval; - private final static IdentityService _identityService = (IdentityService)ComponentLocator.getLocator(ManagementServer.Name).getManager(IdentityService.class); - + private final static IdentityService _identityService = (IdentityService)ComponentLocator.getLocator(ManagementServer.Name).getManager(IdentityService.class); + private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkDeviceManagerImpl.class); protected String _name; - + @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; return true; } - + @Override public boolean start() { return true; @@ -131,14 +132,14 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa public String getName() { return _name; } - + @Override public Host addNetworkDevice(AddNetworkDeviceCmd cmd) { Map paramList = cmd.getParamList(); if (paramList == null) { throw new CloudRuntimeException("Parameter list is null"); } - + Collection paramsCollection = paramList.values(); HashMap params = (HashMap) (paramsCollection.toArray())[0]; if (cmd.getDeviceType().equalsIgnoreCase(NetworkDevice.ExternalDhcp.getName())) { @@ -190,8 +191,16 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa String pxeType = host.getDetail("type"); if (pxeType.equalsIgnoreCase(PxeServerType.PING.getName())) { PxePingResponse r = new PxePingResponse(); - r.setZoneId(host.getDataCenterId()); - r.setPodId(host.getPodId()); + DataCenter zone = ApiDBUtils.findZoneById(host.getDataCenterId()); + if (zone != null) { + r.setZoneId(zone.getUuid()); + } + if (host.getPodId() != null) { + Pod pod = ApiDBUtils.findPodById(host.getPodId()); + if (pod != null) { + r.setPodId(pod.getUuid()); + } + } r.setUrl(host.getPrivateIpAddress()); r.setType(pxeType); r.setStorageServerIp(host.getDetail("storageServer")); @@ -204,8 +213,8 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } else { throw new CloudRuntimeException("Unsupported network device type:" + host.getType()); } - - response.setId(device.getId()); + + response.setId(device.getUuid()); return response; } @@ -222,18 +231,18 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa // List devs = _hostDao.listBy(type, zoneId); // res.addAll(devs); // } - + // return res; return null; } - + @Override public List listNetworkDevice(ListNetworkDeviceCmd cmd) { Map paramList = cmd.getParamList(); if (paramList == null) { throw new CloudRuntimeException("Parameter list is null"); } - + List res; Collection paramsCollection = paramList.values(); HashMap params = (HashMap) (paramsCollection.toArray())[0]; @@ -248,7 +257,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } else if (cmd.getDeviceType() == null){ Long zoneId = Long.parseLong((String) params.get(ApiConstants.ZONE_ID)); Long podId = Long.parseLong((String)params.get(ApiConstants.POD_ID)); - Long physicalNetworkId = (params.get(ApiConstants.PHYSICAL_NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.PHYSICAL_NETWORK_ID)):null; + Long physicalNetworkId = (params.get(ApiConstants.PHYSICAL_NETWORK_ID)==null)?Long.parseLong((String)params.get(ApiConstants.PHYSICAL_NETWORK_ID)):null; List res1 = listNetworkDevice(zoneId, physicalNetworkId, podId, Host.Type.PxeServer); List res2 = listNetworkDevice(zoneId, physicalNetworkId, podId, Host.Type.ExternalDhcp); List res3 = listNetworkDevice(zoneId, physicalNetworkId, podId, Host.Type.ExternalLoadBalancer); @@ -262,7 +271,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa } else { throw new CloudRuntimeException("Unknown network device type:" + cmd.getDeviceType()); } - + return res; } diff --git a/server/src/com/cloud/network/FirewallRulesCidrsVO.java b/server/src/com/cloud/network/FirewallRulesCidrsVO.java index a123aeeb840..0048dce8dab 100644 --- a/server/src/com/cloud/network/FirewallRulesCidrsVO.java +++ b/server/src/com/cloud/network/FirewallRulesCidrsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("firewall_rules_cidrs")) -public class FirewallRulesCidrsVO { +public class FirewallRulesCidrsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -44,7 +46,7 @@ public class FirewallRulesCidrsVO { this.sourceCidrList = sourceCidrList; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/network/IPAddressVO.java b/server/src/com/cloud/network/IPAddressVO.java index 9be624e6554..c17d68f0787 100644 --- a/server/src/com/cloud/network/IPAddressVO.java +++ b/server/src/com/cloud/network/IPAddressVO.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -31,8 +31,9 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.InternalIdentity; /** * A bean representing a public IP Address @@ -40,12 +41,12 @@ import com.cloud.utils.net.Ip; */ @Entity @Table(name=("user_ip_address")) -public class IPAddressVO implements IpAddress, Identity { +public class IPAddressVO implements IpAddress { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="account_id") private Long allocatedToAccountId = null; @@ -59,59 +60,59 @@ public class IPAddressVO implements IpAddress, Identity { @Column(name="data_center_id", updatable=false) private long dataCenterId; - + @Column(name="source_nat") private boolean sourceNat; @Column(name="allocated") @Temporal(value=TemporalType.TIMESTAMP) private Date allocatedTime; - + @Column(name="vlan_db_id") private long vlanId; @Column(name="one_to_one_nat") private boolean oneToOneNat; - + @Column(name="vm_id") private Long associatedWithVmId; - + @Column(name="state") private State state; - + @Column(name="mac_address") private long macAddress; - + @Column(name="source_network_id") private Long sourceNetworkId; - + @Column(name="network_id") private Long associatedWithNetworkId; - + @Column(name="uuid") private String uuid; - + @Column(name="physical_network_id") private Long physicalNetworkId; - + @Column(name="is_system") private boolean system; - + @Column(name="account_id") @Transient private Long accountId = null; - + @Transient @Column(name="domain_id") private Long domainId = null; - + @Column(name="vpc_id") private Long vpcId; - + protected IPAddressVO() { this.uuid = UUID.randomUUID().toString(); } - + @Override public boolean readyToUse() { return state == State.Allocated; @@ -129,36 +130,36 @@ public class IPAddressVO implements IpAddress, Identity { this.macAddress = macAddress; this.uuid = UUID.randomUUID().toString(); } - + public long getMacAddress() { return macAddress; } - + @Override public long getDataCenterId() { - return dataCenterId; + return dataCenterId; } @Override public Ip getAddress() { return address; } - + @Override public Long getAllocatedToAccountId() { return allocatedToAccountId; } - + @Override public Long getAllocatedInDomainId() { return allocatedInDomainId; } - + @Override public Long getAssociatedWithNetworkId() { return associatedWithNetworkId; } - + public void setAssociatedWithNetworkId(Long networkId) { this.associatedWithNetworkId = networkId; } @@ -171,7 +172,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setAssociatedWithVmId(Long associatedWithVmId) { this.associatedWithVmId = associatedWithVmId; } - + @Override public Date getAllocatedTime() { return allocatedTime; @@ -188,7 +189,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setSourceNat(boolean sourceNat) { this.sourceNat = sourceNat; } - + @Override public boolean isSourceNat() { return sourceNat; @@ -197,12 +198,12 @@ public class IPAddressVO implements IpAddress, Identity { public void setAllocatedTime(Date allocated) { this.allocatedTime = allocated; } - + @Override public long getVlanId() { return this.vlanId; } - + public void setVlanId(long vlanDbId) { this.vlanId = vlanDbId; } @@ -215,31 +216,31 @@ public class IPAddressVO implements IpAddress, Identity { public void setOneToOneNat(boolean oneToOneNat) { this.oneToOneNat = oneToOneNat; } - + @Override public long getDomainId() { return allocatedInDomainId == null ? -1 : allocatedInDomainId; } - + @Override public long getAccountId() { return allocatedToAccountId == null ? -1 : allocatedToAccountId; } - + @Override public State getState() { return state; } - + public void setState(State state) { this.state = state; } - + @Override public String toString() { return new StringBuilder("Ip[").append(address).append("-").append(dataCenterId).append("]").toString(); } - + @Override public long getId() { return id; @@ -252,12 +253,12 @@ public class IPAddressVO implements IpAddress, Identity { public void setSourceNetworkId(Long sourceNetworkId) { this.sourceNetworkId = sourceNetworkId; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -269,7 +270,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } - + @Override public boolean getSystem() { return system; @@ -288,4 +289,4 @@ public class IPAddressVO implements IpAddress, Identity { public void setVpcId(Long vpcId) { this.vpcId = vpcId; } -} +} diff --git a/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java b/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java index ade6dae9bb6..297aa2d26e4 100644 --- a/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java +++ b/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,15 +27,12 @@ import javax.persistence.Table; @Entity @Table(name=("inline_load_balancer_nic_map")) -public class InlineLoadBalancerNicMapVO { +public class InlineLoadBalancerNicMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - @Column(name="load_balancer_id") - private long loadBalancerId; - @Column(name="public_ip_address") private String publicIpAddress; @@ -42,8 +41,7 @@ public class InlineLoadBalancerNicMapVO { public InlineLoadBalancerNicMapVO() { } - public InlineLoadBalancerNicMapVO(long loadBalancerId, String publicIpAddress, long nicId) { - this.loadBalancerId = loadBalancerId; + public InlineLoadBalancerNicMapVO(String publicIpAddress, long nicId) { this.publicIpAddress = publicIpAddress; this.nicId = nicId; } @@ -52,10 +50,6 @@ public class InlineLoadBalancerNicMapVO { return id; } - public long getLoadBalancerId() { - return loadBalancerId; - } - public String getPublicIpAddress() { return publicIpAddress; } diff --git a/server/src/com/cloud/network/LBStickinessPolicyVO.java b/server/src/com/cloud/network/LBStickinessPolicyVO.java index 30590cdfbfa..9a629ce017c 100644 --- a/server/src/com/cloud/network/LBStickinessPolicyVO.java +++ b/server/src/com/cloud/network/LBStickinessPolicyVO.java @@ -32,6 +32,7 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.cloud.network.rules.StickinessPolicy; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("load_balancer_stickiness_policies")) diff --git a/server/src/com/cloud/network/LoadBalancerVMMapVO.java b/server/src/com/cloud/network/LoadBalancerVMMapVO.java index e64085d027a..3cc66dc9011 100644 --- a/server/src/com/cloud/network/LoadBalancerVMMapVO.java +++ b/server/src/com/cloud/network/LoadBalancerVMMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("load_balancer_vm_map")) -public class LoadBalancerVMMapVO { +public class LoadBalancerVMMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/NetworkAccountVO.java b/server/src/com/cloud/network/NetworkAccountVO.java index b04da8d1c84..b51e78cce4c 100644 --- a/server/src/com/cloud/network/NetworkAccountVO.java +++ b/server/src/com/cloud/network/NetworkAccountVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_network_ref") -public class NetworkAccountVO implements OwnedBy { +public class NetworkAccountVO implements OwnedBy, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; @@ -49,7 +50,12 @@ public class NetworkAccountVO implements OwnedBy { this.accountId = accountId; this.owner = owner; } - + + @Override + public long getId() { + return id; + } + @Override public long getAccountId() { return accountId; diff --git a/server/src/com/cloud/network/NetworkDomainVO.java b/server/src/com/cloud/network/NetworkDomainVO.java index bf32d1a8539..9b79887f7a7 100644 --- a/server/src/com/cloud/network/NetworkDomainVO.java +++ b/server/src/com/cloud/network/NetworkDomainVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.domain.PartOf; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="domain_network_ref") -public class NetworkDomainVO implements PartOf { +public class NetworkDomainVO implements PartOf, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; @@ -49,7 +50,12 @@ public class NetworkDomainVO implements PartOf { this.domainId = domainId; this.subdomainAccess = subdomainAccess; } - + + @Override + public long getId() { + return id; + } + @Override public long getDomainId() { return domainId; diff --git a/server/src/com/cloud/network/NetworkExternalFirewallVO.java b/server/src/com/cloud/network/NetworkExternalFirewallVO.java index 37441174f29..800e737137d 100644 --- a/server/src/com/cloud/network/NetworkExternalFirewallVO.java +++ b/server/src/com/cloud/network/NetworkExternalFirewallVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkExternalFirewallVO contains information on the networks that are using external firewall @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name="network_external_firewall_device_map") -public class NetworkExternalFirewallVO { +public class NetworkExternalFirewallVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java b/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java index f3ff1c06f49..17f9ffd2fee 100644 --- a/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java +++ b/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkExternalLoadBalancerVO contains mapping of a network and the external load balancer device id assigned to the network @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name="network_external_lb_device_map") -public class NetworkExternalLoadBalancerVO { +public class NetworkExternalLoadBalancerVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index d4a9b5c64c9..546f1bf613c 100755 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -19,7 +19,7 @@ package com.cloud.network; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan.VlanType; import com.cloud.deploy.DataCenterDeployment; @@ -32,7 +32,10 @@ import com.cloud.exception.InsufficientVirtualNetworkCapcityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.LoadBalancingServiceProvider; +import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; @@ -308,7 +311,7 @@ public interface NetworkManager { NetworkOfferingVO findById) throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException; - IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, + IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerId, DataCenter zone) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException; @@ -316,4 +319,12 @@ public interface NetworkManager { Long physicalNetworkId); + List getProvidersForServiceInNetwork(Network network, Service service); + + StaticNatServiceProvider getStaticNatProviderForNetwork(Network network); + boolean isNetworkInlineMode(Network network); + + int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state); + + LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index eb20207dca6..bb60dcfcdc8 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -35,10 +35,10 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; @@ -51,6 +51,7 @@ import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.to.NicTO; import com.cloud.alert.AlertManager; +import com.cloud.api.ApiDBUtils; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource.ResourceType; @@ -113,6 +114,7 @@ import com.cloud.network.dao.PhysicalNetworkTrafficTypeDao; import com.cloud.network.dao.PhysicalNetworkTrafficTypeVO; import com.cloud.network.element.DhcpServiceProvider; import com.cloud.network.element.IpDeployer; +import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.element.UserDataServiceProvider; @@ -293,7 +295,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } @DB - public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, + public PublicIp fetchNewPublicIp(long dcId, Long podId, Long vlanDbId, Account owner, VlanType vlanUse, Long guestNetworkId, boolean sourceNat, boolean assign, String requestedIp, boolean isSystem, Long vpcId) throws InsufficientAddressCapacityException { StringBuilder errorMessage = new StringBuilder("Unable to get ip adress in "); @@ -339,13 +341,13 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", Pod.class, podId); // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. - ex.addProxyObject("Pod", podId, "podId"); + ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid()); throw ex; } s_logger.warn(errorMessage.toString()); InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", DataCenter.class, dcId); - ex.addProxyObject("data_center", dcId, "dcId"); + ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid()); throw ex; } @@ -403,9 +405,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { VlanVO vlan = _vlanDao.findById(addr.getVlanId()); String guestType = vlan.getVlanType().toString(); - - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), - addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, + + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_ASSIGN, owner.getId(), + addr.getDataCenterId(), addr.getId(), addr.getAddress().toString(), addr.isSourceNat(), guestType, addr.getSystem()); _usageEventDao.persist(usageEvent); // don't increment resource count for direct ip addresses @@ -417,9 +419,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { txn.commit(); } - + @Override - public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) + public PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException { assert (guestNetwork.getTrafficType() != null) : "You're asking for a source nat but your network " + "can't participate in source nat. What do you have to say for yourself?"; @@ -429,28 +431,28 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { PublicIp ipToReturn = null; if (sourceNatIp != null) { - ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), + ipToReturn = new PublicIp(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(sourceNatIp.getMacAddress())); } else { ipToReturn = assignDedicateIpAddress(owner, guestNetwork.getId(), null, dcId, true); } - + return ipToReturn; } - + @Override public PublicIp assignVpnGatewayIpAddress(long dcId, Account owner, long vpcId) throws InsufficientAddressCapacityException, ConcurrentOperationException { return assignDedicateIpAddress(owner, null, vpcId, dcId, false); } - + @DB @Override - public PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) + public PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) throws ConcurrentOperationException, InsufficientAddressCapacityException { long ownerId = owner.getId(); - + // Check that the maximum number of public IPs for the given accountId will not be exceeded try { _resourceLimitMgr.checkResourceLimit(owner, ResourceType.public_ip); @@ -474,7 +476,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (s_logger.isDebugEnabled()) { s_logger.debug("lock account " + ownerId + " is acquired"); } - + // If account has Account specific ip ranges, try to allocate ip from there Long vlanId = null; List maps = _accountVlanMapDao.listAccountVlanMapsByAccount(ownerId); @@ -483,7 +485,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } - ip = fetchNewPublicIp(dcId, null, vlanId, owner, VlanType.VirtualNetwork, guestNtwkId, + ip = fetchNewPublicIp(dcId, null, vlanId, owner, VlanType.VirtualNetwork, guestNtwkId, isSourceNat, false, null, false, vpcId); IPAddressVO publicIp = ip.ip(); @@ -515,7 +517,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { List publicIps = new ArrayList(); if (userIps != null && !userIps.isEmpty()) { for (IPAddressVO userIp : userIps) { - PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), + PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress())); publicIps.add(publicIp); } @@ -532,7 +534,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { // system if (cleanupIpResources(addr.getId(), Account.ACCOUNT_ID_SYSTEM, _accountMgr.getSystemAccount())) { s_logger.debug("Unassiging ip address " + addr); - _ipAddressDao.unassignIpAddress(addr.getId()); + _ipAddressDao.unassignIpAddress(addr.getId()); } else { success = false; s_logger.warn("Failed to release resources for ip address id=" + addr.getId()); @@ -604,17 +606,18 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { long callerUserId = UserContext.current().getCallerUserId(); // check permissions _accountMgr.checkAccess(caller, null, false, ipOwner); - + DataCenter zone = _configMgr.getZone(zoneId); - return allocateIp(ipOwner, isSystem, caller, zone); + return allocateIp(ipOwner, isSystem, caller, callerUserId, zone); } @DB - public IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, DataCenter zone) + @Override + public IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerUserId, DataCenter zone) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException { - + VlanType vlanType = VlanType.VirtualNetwork; boolean assign = false; @@ -632,7 +635,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { Account accountToLock = null; try { if (s_logger.isDebugEnabled()) { - s_logger.debug("Associate IP address called by the user " + caller.getId()); + s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId()); } accountToLock = _accountDao.acquireInLockTable(ipOwner.getId()); if (accountToLock == null) { @@ -650,14 +653,14 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { txn.start(); - ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, + ip = fetchNewPublicIp(zone.getId(), null, null, ipOwner, vlanType, null, false, assign, null, isSystem, null); if (ip == null) { InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); - ex.addProxyObject("data_center", zone.getId(), "zoneId"); + ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid()); throw ex; } UserContext.current().setEventDetails("Ip Id: " + ip.getId()); @@ -696,48 +699,33 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { assert (sourceNatIp != null) : "How do we get a bunch of ip addresses but none of them are source nat? " + "account=" + ownerId + "; networkId=" + networkId; - } - + } + return sourceNatIp; } @DB @Override - public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) - throws ResourceAllocationException, ResourceUnavailableException, + public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure) + throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException { Account caller = UserContext.current().getCaller(); Account owner = null; IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId); if (ipToAssoc != null) { - Network network = _networksDao.findById(networkId); - if (network == null) { - throw new InvalidParameterValueException("Invalid network id is given"); - } - - DataCenter zone = _configMgr.getZone(network.getDataCenterId()); - if (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced) { - if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) { - _accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.UseNetwork, false, network); - } else { - throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if" + - "network service Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network"); - } - } else { - _accountMgr.checkAccess(caller, null, true, ipToAssoc); - } + _accountMgr.checkAccess(caller, null, true, ipToAssoc); owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId()); } else { s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + if (ipToAssoc.getAssociatedWithNetworkId() != null) { s_logger.debug("IP " + ipToAssoc + " is already assocaited with network id" + networkId); return ipToAssoc; } - + Network network = _networksDao.findById(networkId); if (network != null) { _accountMgr.checkAccess(owner, AccessType.UseNetwork, false, network); @@ -745,7 +733,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.debug("Unable to find ip address by id: " + ipId); return null; } - + DataCenter zone = _configMgr.getZone(network.getDataCenterId()); // allow associating IP addresses to guest network only @@ -753,25 +741,21 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest); } - // Check that network belongs to IP owner - skip this check - // - if zone is basic zone as there is just one guest network, - // - if shared network in Advanced zone - // - and it belongs to the system - if (network.getAccountId() != owner.getId()) { - if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Shared)) { - throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); - } + // Check that network belongs to IP owner - skip this check for Basic zone as there is just one guest network, + // and it belongs to the system + if (zone.getNetworkType() != NetworkType.Basic && network.getAccountId() != owner.getId()) { + throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP"); } - // In Advance zone only allow to do IP assoc - // - for Isolated networks with source nat service enabled - // - for shared networks with source nat service enabled - if (zone.getNetworkType() == NetworkType.Advanced && (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) { + // In Advance zone only allow to do IP assoc for Isolated networks with source nat service enabled + if (zone.getNetworkType() == NetworkType.Advanced && + !(network.getGuestType() == GuestType.Isolated && _networkModel.areServicesSupportedInNetwork(network.getId(), + Service.SourceNat))) { throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled"); } - + NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); boolean sharedSourceNat = offering.getSharedSourceNat(); boolean isSourceNat = false; @@ -782,15 +766,15 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } } } - + s_logger.debug("Associating ip " + ipToAssoc + " to network " + network); - + IPAddressVO ip = _ipAddressDao.findById(ipId); //update ip address with networkId ip.setAssociatedWithNetworkId(networkId); ip.setSourceNat(isSourceNat); _ipAddressDao.update(ipId, ip); - + boolean success = false; try { success = applyIpAssociations(network, false); @@ -818,7 +802,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } } } - + @Override @DB @@ -901,7 +885,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { sgProviders.add(Provider.SecurityGroupProvider); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders); - Map> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = + Map> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap>(); defaultProviders.clear(); defaultProviders.add(Network.Provider.VirtualRouter); @@ -915,9 +899,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders); - - - Map> defaultVPCOffProviders = + + + Map> defaultVPCOffProviders = new HashMap>(); defaultProviders.clear(); defaultProviders.add(Network.Provider.VirtualRouter); @@ -973,7 +957,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks, "Offering for Isolated VPC networks with Source Nat service enabled", TrafficType.Guest, @@ -982,7 +966,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB) == null) { //remove LB service defaultVPCOffProviders.remove(Service.Lb); @@ -995,14 +979,14 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOffering) == null) { - offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOffering, + offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOffering, "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, true, Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated, false, null, true, null, true); offering.setState(NetworkOffering.State.Enabled); _networkOfferingDao.update(offering.getId(), offering); } - + Map> netscalerServiceProviders = new HashMap>(); Set vrProvider = new HashSet(); vrProvider.add(Provider.VirtualRouter); @@ -1016,7 +1000,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { netscalerServiceProviders.put(Service.SecurityGroup, sgProvider); netscalerServiceProviders.put(Service.StaticNat, nsProvider); netscalerServiceProviders.put(Service.Lb, nsProvider); - + Map> serviceCapabilityMap = new HashMap>(); Map elb = new HashMap(); elb.put(Capability.ElasticLb, "true"); @@ -1024,7 +1008,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { eip.put(Capability.ElasticIp, "true"); serviceCapabilityMap.put(Service.Lb, elb); serviceCapabilityMap.put(Service.StaticNat, eip); - + if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedEIPandELBNetworkOffering) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, null, true, Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true); @@ -1099,7 +1083,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { public List setupNetwork(Account owner, NetworkOffering offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, ACLType aclType, Boolean subdomainAccess, Long vpcId) throws ConcurrentOperationException { - + Account locked = _accountDao.acquireInLockTable(owner.getId()); if (locked == null) { throw new ConcurrentOperationException("Unable to acquire lock on " + owner); @@ -1107,7 +1091,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { try { if (predefined == null - || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && + || (offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && !(predefined.getBroadcastDomainType() == BroadcastDomainType.Vlan || predefined.getBroadcastDomainType() == BroadcastDomainType.Lswitch))) { List configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId()); if (configs.size() > 0) { @@ -1118,7 +1102,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (errorIfAlreadySetup) { InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); + ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); throw ex; } else { return configs; @@ -1135,7 +1119,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (errorIfAlreadySetup) { InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)"); ex.addProxyObject(offering, offering.getId(), "offeringId"); - ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); + ex.addProxyObject(configs.get(0), configs.get(0).getId(), "networkConfigId"); throw ex; } else { return configs; @@ -1171,7 +1155,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { txn.start(); NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), - related, name, displayText, predefined.getNetworkDomain(), offering.getGuestType(), + related, name, displayText, predefined.getNetworkDomain(), offering.getGuestType(), plan.getDataCenterId(), plan.getPhysicalNetworkId(), aclType, offering.getSpecifyIpRanges(), vpcId); networks.add(_networksDao.persist(vo, vo.getGuestType() == Network.GuestType.Isolated, finalizeServicesAndProvidersForNetwork(offering, plan.getPhysicalNetworkId()))); @@ -1201,7 +1185,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @Override @DB - public void allocate(VirtualMachineProfile vm, List> networks) + public void allocate(VirtualMachineProfile vm, List> networks) throws InsufficientCapacityException, ConcurrentOperationException { Transaction txn = Transaction.currentTxn(); txn.start(); @@ -1217,26 +1201,26 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { for (Pair network : networks) { NetworkVO config = network.first(); NicProfile requested = network.second(); - + Boolean isDefaultNic = false; if (vm != null && (requested != null && requested.isDefaultNic())) { isDefaultNic = true; } - + while (deviceIds[deviceId] && deviceId < deviceIds.length) { deviceId++; } - - Pair vmNicPair = allocateNic(requested, config, isDefaultNic, + + Pair vmNicPair = allocateNic(requested, config, isDefaultNic, deviceId, vm); - + NicProfile vmNic = vmNicPair.first(); if (vmNic == null) { continue; } - + deviceId = vmNicPair.second(); - + int devId = vmNic.getDeviceId(); if (devId > deviceIds.length) { throw new IllegalArgumentException("Device id for nic is too large: " + vmNic); @@ -1246,18 +1230,18 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } deviceIds[devId] = true; - + if (vmNic.isDefaultNic()) { if (defaultNic != null) { - throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " + + throw new IllegalArgumentException("You cannot specify two nics as default nics: nic 1 = " + defaultNic + "; nic 2 = " + vmNic); } defaultNic = vmNic; } - + nics.add(vmNic); vm.addNic(vmNic); - + } if (nics.size() != networks.size()) { @@ -1271,14 +1255,14 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { txn.commit(); } - - + + @DB @Override - public Pair allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, + public Pair allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, int deviceId, VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException{ - + NetworkVO ntwkVO = _networksDao.findById(network.getId()); s_logger.debug("Allocating nic for vm " + vm.getVirtualMachine() + " in network " + network + " with requested profile " + requested); NetworkGuru guru = _networkGurus.get(ntwkVO.getGuruName()); @@ -1311,9 +1295,9 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network)); - + return new Pair(vmNic, Integer.valueOf(deviceId)); - } + } protected Integer applyProfileToNic(NicVO vo, NicProfile profile, Integer deviceId) { if (profile.getDeviceId() != null) { @@ -1399,7 +1383,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { Integer networkRate = _networkModel.getNetworkRate(config.getId(), null); to.setNetworkRateMbps(networkRate); - + to.setUuid(config.getUuid()); return to; @@ -1417,10 +1401,10 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (network == null) { // see NetworkVO.java ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); - ex.addProxyObject("networks", networkId, "networkId"); + ex.addProxyObject(ApiDBUtils.findNetworkById(networkId).getUuid()); throw ex; } - + if (s_logger.isDebugEnabled()) { s_logger.debug("Lock is acquired for network id " + networkId + " as a part of network implement"); } @@ -1428,21 +1412,12 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { try { NetworkGuru guru = _networkGurus.get(network.getGuruName()); Network.State state = network.getState(); - if (state == Network.State.Implemented || state == Network.State.Implementing) { + if (state == Network.State.Implemented || state == Network.State.Setup || state == Network.State.Implementing) { s_logger.debug("Network id=" + networkId + " is already implemented"); implemented.set(guru, network); return implemented; } - if (state == Network.State.Setup) { - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); - if (!isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) || (zone.getNetworkType() == NetworkType.Basic)) { - s_logger.debug("Network id=" + networkId + " is already implemented"); - implemented.set(guru, network); - return implemented; - } - } - if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + guru.getName() + " to implement " + network); } @@ -1478,7 +1453,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { shutdownNetwork(networkId, context, false); } - + _networksDao.releaseFromLockTable(networkId); if (s_logger.isDebugEnabled()) { s_logger.debug("Lock is released for network id " + networkId + " as a part of network implement"); @@ -1496,16 +1471,15 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { NetworkVO network, NetworkOfferingVO offering) throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException { - // Associate a source NAT IP (if one isn't already associated with the network) if this is a - // 1) 'Isolated' or 'Shared' guest virtual network in the advance zone - // 2) network has sourceNat service - // 3) network offering does not support a shared source NAT rule + // If this is a 1) guest virtual network 2) network has sourceNat service 3) network offering does not support a + // Shared source NAT rule, + // associate a source NAT IP (if one isn't already associated with the network) boolean sharedSourceNat = offering.getSharedSourceNat(); DataCenter zone = _dcDao.findById(network.getDataCenterId()); - if (!sharedSourceNat && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) - && (network.getGuestType() == Network.GuestType.Isolated || - (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) { + if (network.getGuestType() == Network.GuestType.Isolated + && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) + && !sharedSourceNat) { List ips = null; if (network.getVpcId() != null) { @@ -1533,7 +1507,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { // because the serializer would look up the NetworkVO class's table and retrieve the // network id instead of the physical network id. // So just throw this exception as is. We may need to TBD by changing the serializer. - throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + + throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId()); } @@ -1544,7 +1518,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (!element.implement(network, offering, dest, context)) { CloudRuntimeException ex = new CloudRuntimeException("Failed to implement provider " + element.getProvider().getName() + " for network with specified id"); ex.addProxyObject(network, network.getId(), "networkId"); - throw ex; + throw ex; } } } @@ -1555,12 +1529,12 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); // see DataCenterVO.java ResourceUnavailableException ex = new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); - ex.addProxyObject("data_center", network.getDataCenterId(), "dataCenterId"); + ex.addProxyObject(ApiDBUtils.findZoneById(network.getDataCenterId()).getUuid()); throw ex; } } - protected void prepareElement(NetworkElement element, NetworkVO network, + protected void prepareElement(NetworkElement element, NetworkVO network, NicProfile profile, VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException { @@ -1595,7 +1569,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (nic.getVmType() == VirtualMachine.Type.User || (nic.getVmType() == VirtualMachine.Type.DomainRouter && _networksDao.findById(networkId).getTrafficType() == TrafficType.Guest)) { _networksDao.setCheckForGc(networkId); } - + txn.commit(); } @@ -1620,7 +1594,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { for (NicVO nic : nics) { Pair implemented = implementNetwork(nic.getNetworkId(), dest, context); - + NetworkVO network = implemented.second(); NicProfile profile = prepareNic(vmProfile, dest, context, nic.getId(), network); vmProfile.addNic(profile); @@ -1628,15 +1602,15 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } @Override - public NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination + public NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination dest, ReservationContext context, long nicId, NetworkVO network) - throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, + throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { Integer networkRate = _networkModel.getNetworkRate(network.getId(), vmProfile.getId()); NetworkGuru guru = _networkGurus.get(network.getGuruName()); NicVO nic = _nicDao.findById(nicId); - + NicProfile profile = null; if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { nic.setState(Nic.State.Reserving); @@ -1649,7 +1623,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { URI isolationUri = nic.getIsolationUri(); - profile = new NicProfile(nic, network, broadcastUri, isolationUri, + profile = new NicProfile(nic, network, broadcastUri, isolationUri, networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network)); guru.reserve(profile, network, vmProfile, dest, context); @@ -1717,27 +1691,27 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @Override @DB - public void releaseNic(VirtualMachineProfile vmProfile, Nic nic) + public void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { NicVO nicVO = _nicDao.findById(nic.getId()); releaseNic(vmProfile, nicVO); } @DB - protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nicVO) + protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nicVO) throws ConcurrentOperationException, ResourceUnavailableException { //lock the nic Transaction txn = Transaction.currentTxn(); txn.start(); - + NicVO nic = _nicDao.lockRow(nicVO.getId(), true); if (nic == null) { throw new ConcurrentOperationException("Unable to acquire lock on nic " + nic); } - + Nic.State originalState = nic.getState(); NetworkVO network = _networksDao.findById(nicVO.getNetworkId()); - + if (originalState == Nic.State.Reserved || originalState == Nic.State.Reserving) { if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { NetworkGuru guru = _networkGurus.get(network.getGuruName()); @@ -1756,17 +1730,17 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } //commit the transaction before proceeding releasing nic profile on the network elements txn.commit(); - + // Perform release on network elements for (NetworkElement element : _networkElements) { if (s_logger.isDebugEnabled()) { s_logger.debug("Asking " + element.getName() + " to release " + nic); } - //NOTE: Context appear to never be used in release method + //NOTE: Context appear to never be used in release method //implementations. Consider removing it from interface Element element.release(network, profile, vmProfile, null); } - + } else { nic.setState(Nic.State.Allocated); updateNic(nic, network.getId(), -1); @@ -1786,7 +1760,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { removeNic(vm, nic); } } - + @Override public void removeNic(VirtualMachineProfile vm, Nic nic) { removeNic(vm, _nicDao.findById(nic.getId())); @@ -1818,7 +1792,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @DB public Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, Long domainId, - PhysicalNetwork pNtwk, long zoneId, ACLType aclType, Boolean subdomainAccess, Long vpcId) + PhysicalNetwork pNtwk, long zoneId, ACLType aclType, Boolean subdomainAccess, Long vpcId) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); @@ -1858,7 +1832,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (aclType == null || aclType != ACLType.Domain) { throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); } - + // Only one guest network is supported in Basic zone List guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { @@ -1905,7 +1879,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { "service disabled are allowed in security group enabled zone"); } } - + //don't allow eip/elb networks in Advance zone if (ntwkOff.getElasticIp() || ntwkOff.getElasticLb()) { throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic); @@ -1930,15 +1904,14 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId); } } else { - //don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or - //shared network with same Vlan ID in the zone - if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0 || - _networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Shared) > 0) { - throw new InvalidParameterValueException("There is a isolated/shared network with vlan id: " + vlanId + " already exists " + "in zone " + zoneId); + //don't allow to create Shared network with Vlan that already exists in the zone for Isolated networks + if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) { + throw new InvalidParameterValueException("Isolated network with vlan " + vlanId + " already exists " + + "in zone " + zoneId); } } } - + // If networkDomain is not specified, take it from the global configuration if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { Map dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities @@ -2032,7 +2005,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { - if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && + if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { Network defaultGuestNetwork = networks.get(0); for (Network nw : networks) { @@ -2046,7 +2019,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { network = networks.get(0); } } - + if (updateResourceCount) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network); } @@ -2062,7 +2035,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { @DB public boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements) { boolean result = false; - + NetworkVO network = _networksDao.lockRow(networkId, true); if (network == null) { s_logger.debug("Unable to find network with id: " + networkId); @@ -2090,13 +2063,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { applyProfileToNetwork(network, profile); - DataCenterVO zone = _dcDao.findById(network.getDataCenterId()); - if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId()) && (zone.getNetworkType() == NetworkType.Advanced)) { - network.setState(Network.State.Setup); - } else { - network.setState(Network.State.Allocated); - } - + network.setState(Network.State.Allocated); network.setRestartRequired(false); _networksDao.update(network.getId(), network); _networksDao.clearCheckForGc(networkId); @@ -2187,11 +2154,11 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { return false; } } - + //In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network DataCenter zone = _configMgr.getZone(network.getDataCenterId()); if (zone.getNetworkType() == NetworkType.Basic) { - List systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), + List systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm); if (systemVms != null && !systemVms.isEmpty()) { s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged"); @@ -2266,7 +2233,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { network.setState(Network.State.Destroy); _networksDao.update(network.getId(), network); _networksDao.remove(network.getId()); - + NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, network.getAclType()); if (updateResourceCount) { @@ -2285,7 +2252,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } protected boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) { - + //cleanup Public vlans List publicVlans = _vlanDao.listVlansByNetworkId(networkId); boolean result = true; @@ -2294,8 +2261,8 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.warn("Failed to delete vlan " + vlan.getId() + ");"); result = false; } - } - + } + //cleanup private vlans int privateIpAllocCount = _privateIpDao.countAllocatedByNetworkId(networkId); if (privateIpAllocCount > 0) { @@ -2417,7 +2384,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { NetworkVO network = _networksDao.findById(networkId); if (network == null) { InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id doesn't exist"); - ex.addProxyObject(network, networkId, "networkId"); + ex.addProxyObject(network, networkId, "networkId"); throw ex; } @@ -2528,13 +2495,13 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } } } - + //apply network ACLs if (!_networkACLMgr.applyNetworkACLs(networkId, caller)) { s_logger.warn("Failed to reapply network ACLs as a part of of network id=" + networkId + " restart"); success = false; } - + return success; } @@ -2551,7 +2518,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { ResourceUnavailableException, ResourceAllocationException { Account owner = _accountMgr.getActiveAccountById(accountId); boolean createNetwork = false; - + if (guestNetwork != null && guestNetwork.getTrafficType() != TrafficType.Guest) { throw new InvalidParameterValueException("Network " + guestNetwork + " is not of a type " + TrafficType.Guest); } @@ -2575,7 +2542,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (createNetwork) { List requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false); if (requiredOfferings.size() < 1) { - throw new CloudRuntimeException("Unable to find network offering with availability=" + + throw new CloudRuntimeException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as part of createVlanIpRange"); } if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) { @@ -2586,11 +2553,11 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { if (physicalNetwork == null) { throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } - - s_logger.debug("Creating network for account " + owner + " from the network offering id=" + + + s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process"); guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network" - , owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, + , owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zoneId, ACLType.Account, null, null); if (guestNetwork == null) { @@ -2599,8 +2566,8 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { "service enabled as a part of createVlanIpRange, for the account " + accountId + "in zone " + zoneId); } } else { - throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() - + " is not in " + NetworkOffering.State.Enabled); + throw new CloudRuntimeException("Required network offering id=" + requiredOfferings.get(0).getId() + + " is not in " + NetworkOffering.State.Enabled); } } @@ -2748,7 +2715,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { String guestType = vlan.getVlanType().toString(); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_IP_RELEASE, - ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), + ip.getAllocatedToAccountId(), ip.getDataCenterId(), addrId, ip.getAddress().addr(), ip.isSourceNat(), guestType, ip.getSystem()); _usageEventDao.persist(usageEvent); } @@ -2826,23 +2793,15 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { applyIpAssociations(network, false, continueOnError, publicIps); // get provider - String staticNatProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.StaticNat); - - for (NetworkElement ne : _networkElements) { - try { - if (!(ne instanceof StaticNatServiceProvider && ne.getName().equalsIgnoreCase(staticNatProvider))) { - continue; - } - - boolean handled = ((StaticNatServiceProvider) ne).applyStaticNats(network, staticNats); - s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); - } catch (ResourceUnavailableException e) { - if (!continueOnError) { - throw e; - } - s_logger.warn("Problems with " + ne.getName() + " but pushing on", e); - success = false; + StaticNatServiceProvider element = getStaticNatProviderForNetwork(network); + try { + success = element.applyStaticNats(network, staticNats); + } catch (ResourceUnavailableException e) { + if (!continueOnError) { + throw e; } + s_logger.warn("Problems with " + element.getName() + " but pushing on", e); + success = false; } // For revoked static nat IP, set the vm_id to null, indicate it should be revoked @@ -2861,7 +2820,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { } } } - + // if all the rules configured on public IP are revoked then, dis-associate IP with network service provider applyIpAssociations(network, true, continueOnError, publicIps); @@ -2933,7 +2892,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { // shouldn't even come here as network is being cleaned up after all network elements are shutdown s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex); } - + //revoke all network ACLs for network try { if (_networkACLMgr.revokeAllNetworkACLsForNetwork(networkId, callerUserId, caller)) { @@ -3075,7 +3034,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.warn("Failed to cleanup firewall rules as a part of shutdownNetworkRules due to ", ex); success = false; } - + //revoke all Network ACLs for the network w/o applying them in the DB List networkACLs = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.NetworkACL); if (s_logger.isDebugEnabled()) { @@ -3097,7 +3056,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex); success = false; } - + //release all static nats for the network if (!_rulesMgr.applyStaticNatForNetwork(networkId, false, caller, true)) { s_logger.warn("Failed to disable static nats as part of shutdownNetworkRules for network id " + networkId); @@ -3369,7 +3328,7 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { boolean dnsProvided = _networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dns, provider ); boolean dhcpProvided =_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, provider); - + boolean setupDns = dnsProvided || dhcpProvided; return setupDns; } @@ -3450,10 +3409,76 @@ public class NetworkManagerImpl implements NetworkManager, Manager, Listener { return profiles; } + @Override public int getNetworkLockTimeout() { return _networkLockTimeout; } + private Map> getServiceProvidersMap(long networkId) { + Map> map = new HashMap>(); + List nsms = _ntwkSrvcDao.getServicesInNetwork(networkId); + for (NetworkServiceMapVO nsm : nsms) { + Set providers = map.get(Service.getService(nsm.getService())); + if (providers == null) { + providers = new HashSet(); + } + providers.add(Provider.getProvider(nsm.getProvider())); + map.put(Service.getService(nsm.getService()), providers); + } + return map; + } + + @Override + public List getProvidersForServiceInNetwork(Network network, Service service) { + Map> service2ProviderMap = getServiceProvidersMap(network.getId()); + if (service2ProviderMap.get(service) != null) { + List providers = new ArrayList(service2ProviderMap.get(service)); + return providers; + } + return null; + } + protected NetworkElement getElementForServiceInNetwork(Network network, Service service) { + List providers = getProvidersForServiceInNetwork(network, service); + //Only support one provider now + if (providers == null) { + s_logger.error("Cannot find " + service.getName() + " provider for network " + network.getId()); + return null; + } + if (providers.size() != 1) { + s_logger.error("Found " + providers.size() + " " + service.getName() + " providers for network!" + network.getId()); + return null; + } + NetworkElement element = _networkModel.getElementImplementingProvider(providers.get(0).getName()); + s_logger.info("Let " + element.getName() + " handle " + service.getName() + " in network " + network.getId()); + return element; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + NetworkElement element = getElementForServiceInNetwork(network, Service.StaticNat); + assert element instanceof StaticNatServiceProvider; + return (StaticNatServiceProvider)element; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + NetworkElement element = getElementForServiceInNetwork(network, Service.Lb); + assert element instanceof LoadBalancingServiceProvider; + return ( LoadBalancingServiceProvider)element; + } + public boolean isNetworkInlineMode(Network network) { + NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + return offering.isInline(); + } + + @Override + public int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state) { + List rules = _firewallDao.listByIpAndPurposeWithState(addressId, purpose, state); + if (rules == null) { + return 0; + } + return rules.size(); + } } diff --git a/server/src/com/cloud/network/NetworkRuleConfigVO.java b/server/src/com/cloud/network/NetworkRuleConfigVO.java index 5a92f4f4d63..bbfae43b222 100644 --- a/server/src/com/cloud/network/NetworkRuleConfigVO.java +++ b/server/src/com/cloud/network/NetworkRuleConfigVO.java @@ -27,10 +27,11 @@ import javax.persistence.Table; import com.cloud.async.AsyncInstanceCreateStatus; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("network_rule_config")) -public class NetworkRuleConfigVO { +public class NetworkRuleConfigVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -62,7 +63,7 @@ public class NetworkRuleConfigVO { this.protocol = protocol; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/network/NetworkServiceMapVO.java b/server/src/com/cloud/network/NetworkServiceMapVO.java index 6cd9ba6c565..592522d614d 100644 --- a/server/src/com/cloud/network/NetworkServiceMapVO.java +++ b/server/src/com/cloud/network/NetworkServiceMapVO.java @@ -28,10 +28,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="ntwk_service_map") -public class NetworkServiceMapVO { +public class NetworkServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/NetworkUsageManager.java b/server/src/com/cloud/network/NetworkUsageManager.java index 10264b8ba42..3d4577b8199 100644 --- a/server/src/com/cloud/network/NetworkUsageManager.java +++ b/server/src/com/cloud/network/NetworkUsageManager.java @@ -23,7 +23,7 @@ import com.cloud.api.commands.DeleteTrafficMonitorCmd; import com.cloud.api.commands.ListTrafficMonitorsCmd; import com.cloud.host.Host; import com.cloud.host.HostVO; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.utils.component.Manager; public interface NetworkUsageManager extends Manager { diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index 42c72ad04bc..2485a8c966d 100755 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -67,7 +67,7 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.usage.UsageIPAddressVO; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -211,7 +211,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta public TrafficMonitorResponse getApiResponse(Host trafficMonitor) { Map tmDetails = _detailsDao.findDetails(trafficMonitor.getId()); TrafficMonitorResponse response = new TrafficMonitorResponse(); - response.setId(trafficMonitor.getId()); + response.setId(trafficMonitor.getUuid()); response.setIpAddress(trafficMonitor.getPrivateIpAddress()); response.setNumRetries(tmDetails.get("numRetries")); response.setTimeout(tmDetails.get("timeout")); @@ -229,7 +229,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ); AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER); AllocatedIpSearch.done(); - + _networkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400); _TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key()); _TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key()); @@ -327,8 +327,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta // This coule be made configurable rightNow.add(Calendar.HOUR_OF_DAY, -2); - Date now = rightNow.getTime(); - + Date now = rightNow.getTime(); + if(lastCollection.after(now)){ s_logger.debug("Current time is less than 2 hours after last collection time : " + lastCollection.toString() + ". Skipping direct network usage collection"); return false; @@ -380,7 +380,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta } List collectedStats = new ArrayList(); - + //Get usage for Ips which were assigned for the entire duration if(fullDurationIpUsage.size() > 0){ DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now, _TSinclZones, _TSexclZones); @@ -520,7 +520,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta protected DirectNetworkStatsListener() { } - + } @@ -536,7 +536,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta if (!(startup[0] instanceof StartupTrafficMonitorCommand)) { return null; } - + host.setType(Host.Type.TrafficMonitor); return host; } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 39dd66e77b0..14b643b29b7 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -29,8 +29,7 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; @@ -44,7 +43,7 @@ import com.cloud.utils.net.NetUtils; */ @Entity @Table(name="networks") -public class NetworkVO implements Network, Identity { +public class NetworkVO implements Network { @Id @TableGenerator(name="networks_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="networks_seq", allocationSize=1) @Column(name="id") @@ -79,13 +78,13 @@ public class NetworkVO implements Network, Identity { @Column(name="network_offering_id") long networkOfferingId; - + @Column(name="vpc_id") Long vpcId; @Column(name="physical_network_id") Long physicalNetworkId; - + @Column(name="data_center_id") long dataCenterId; @@ -132,24 +131,24 @@ public class NetworkVO implements Network, Identity { @Column(name="reservation_id") String reservationId; - + @Column(name="uuid") String uuid; - + @Column(name="guest_type") @Enumerated(value=EnumType.STRING) Network.GuestType guestType; - + @Column(name="acl_type") @Enumerated(value=EnumType.STRING) ControlledEntity.ACLType aclType; @Column(name="restart_required") boolean restartRequired = false; - + @Column(name="specify_ip_ranges") boolean specifyIpRanges = false; - + public NetworkVO() { this.uuid = UUID.randomUUID().toString(); } @@ -181,8 +180,8 @@ public class NetworkVO implements Network, Identity { this.uuid = UUID.randomUUID().toString(); } - public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, - long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, + public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, + long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, Long physicalNetworkId, ACLType aclType, boolean specifyIpRanges, Long vpcId) { this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, networkDomain, guestType, dcId, physicalNetworkId, aclType, specifyIpRanges, vpcId); @@ -215,8 +214,8 @@ public class NetworkVO implements Network, Identity { * @param vpcId TODO * @param dataCenterId */ - public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, - long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, + public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, + long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, Long physicalNetworkId, ACLType aclType, boolean specifyIpRanges, Long vpcId) { this(trafficType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); this.domainId = domainId; @@ -368,7 +367,7 @@ public class NetworkVO implements Network, Identity { public Long getPhysicalNetworkId() { return physicalNetworkId; } - + @Override public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; @@ -428,7 +427,7 @@ public class NetworkVO implements Network, Identity { public void setCreated(Date created) { this.created = created; } - + @Override public Network.GuestType getGuestType() { return guestType; @@ -465,7 +464,7 @@ public class NetworkVO implements Network, Identity { public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -482,7 +481,7 @@ public class NetworkVO implements Network, Identity { public boolean isRestartRequired() { return restartRequired; } - + @Override public boolean getSpecifyIpRanges() { return specifyIpRanges; diff --git a/server/src/com/cloud/network/PhysicalNetworkVO.java b/server/src/com/cloud/network/PhysicalNetworkVO.java index 84371fb0be5..9bf8601c503 100644 --- a/server/src/com/cloud/network/PhysicalNetworkVO.java +++ b/server/src/com/cloud/network/PhysicalNetworkVO.java @@ -35,6 +35,7 @@ import javax.persistence.TableGenerator; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkConfigurationVO contains information about a specific physical network. diff --git a/server/src/com/cloud/network/PortProfileVO.java b/server/src/com/cloud/network/PortProfileVO.java index c9b2a3f2830..8a7b9d88fe4 100644 --- a/server/src/com/cloud/network/PortProfileVO.java +++ b/server/src/com/cloud/network/PortProfileVO.java @@ -27,6 +27,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.InternalIdentity; /** * PortProfileVO contains information on portprofiles that are created on a Cisco Nexus 1000v VSM associated @@ -35,7 +36,7 @@ import com.cloud.exception.InvalidParameterValueException; @Entity @Table(name="port_profile") -public class PortProfileVO { +public class PortProfileVO implements InternalIdentity { // We need to know what properties a VSM has. Put them here. diff --git a/server/src/com/cloud/network/RouterNetworkVO.java b/server/src/com/cloud/network/RouterNetworkVO.java index 0ff3a4461da..ee58521e2a2 100644 --- a/server/src/com/cloud/network/RouterNetworkVO.java +++ b/server/src/com/cloud/network/RouterNetworkVO.java @@ -26,11 +26,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.network.Network.GuestType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="router_network_ref") -public class RouterNetworkVO{ +public class RouterNetworkVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; diff --git a/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java b/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java index b51e83cea87..c327b1e33e5 100644 --- a/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java +++ b/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_customer_gateway")) diff --git a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java index 4424f218911..99f807f06b2 100644 --- a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java +++ b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java @@ -29,10 +29,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_vpn_connection")) -public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection { +public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java b/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java index 29d174b5afc..ada50c40869 100644 --- a/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java +++ b/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_vpn_gateway")) diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 598ade6342c..f46081c9de0 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -25,12 +25,12 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.ListStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import com.cloud.dc.HostPodVO; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.StorageNetworkIpAddressVO; @@ -38,12 +38,9 @@ import com.cloud.dc.StorageNetworkIpRangeVO; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.StorageNetworkIpAddressDao; import com.cloud.dc.dao.StorageNetworkIpRangeDao; -import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.HostVO; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.Pair; import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria2; @@ -55,7 +52,6 @@ import com.cloud.utils.net.NetUtils; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.SecondaryStorageVmDao; -import com.cloud.vm.dao.VMInstanceDao; @Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService { @@ -308,7 +304,7 @@ public class StorageNetworkManagerImpl implements StorageNetworkManager, Storage } @Override - public List listIpRange(listStorageNetworkIpRangeCmd cmd) { + public List listIpRange(ListStorageNetworkIpRangeCmd cmd) { Long rangeId = cmd.getRangeId(); Long podId = cmd.getPodId(); Long zoneId = cmd.getZoneId(); diff --git a/server/src/com/cloud/network/addr/PublicIp.java b/server/src/com/cloud/network/addr/PublicIp.java index e1f77be6ca7..8ad716fd631 100644 --- a/server/src/com/cloud/network/addr/PublicIp.java +++ b/server/src/com/cloud/network/addr/PublicIp.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -36,52 +36,52 @@ public class PublicIp implements PublicIpAddress { _vlan = vlan; this.macAddress = NetUtils.long2Mac(macAddress); } - + @Override public Ip getAddress() { return _addr.getAddress(); } - + @Override public String getNetmask() { return _vlan.getVlanNetmask(); } - + @Override public String getGateway() { return _vlan.getVlanGateway(); } - + @Override public String getVlanTag() { return _vlan.getVlanTag(); } - + @Override public long getDataCenterId() { return _addr.getDataCenterId(); } - + @Override public boolean readyToUse() { return _addr.getAllocatedTime() != null && _addr.getState() == State.Allocated; } - + @Override public boolean isSourceNat() { return _addr.isSourceNat(); } - + @Override public boolean isOneToOneNat() { return _addr.isOneToOneNat(); } - + @Override public Long getAssociatedWithVmId() { return _addr.getAssociatedWithVmId(); } - + @Override public Date getAllocatedTime() { return _addr.getAllocatedTime(); @@ -106,25 +106,25 @@ public class PublicIp implements PublicIpAddress { public State getState() { return _addr.getState(); } - + public IPAddressVO ip() { return _addr; } - + public VlanVO vlan() { return _vlan; } - + @Override public String getMacAddress() { return macAddress; } - + @Override public Long getAssociatedWithNetworkId() { return _addr.getAssociatedWithNetworkId(); } - + @Override public Long getNetworkId() { return _vlan.getNetworkId(); @@ -149,12 +149,18 @@ public class PublicIp implements PublicIpAddress { public VlanType getVlanType() { return _vlan.getVlanType(); } - + @Override public long getId() { return _addr.getId(); } - + + + @Override + public String getUuid() { + return _addr.getUuid(); + } + @Override public String toString() { return _addr.getAddress().toString(); @@ -179,7 +185,7 @@ public class PublicIp implements PublicIpAddress { public Long getAllocatedInDomainId() { return _addr.getAllocatedInDomainId(); } - + @Override public boolean getSystem() { return _addr.getSystem(); diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java index e739aec82ed..4c49914f11c 100644 --- a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java +++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java @@ -25,27 +25,23 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd; +import org.apache.cloudstack.api.command.user.autoscale.*; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDispatcher; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.commands.CreateAutoScalePolicyCmd; -import com.cloud.api.commands.CreateAutoScaleVmGroupCmd; -import com.cloud.api.commands.CreateAutoScaleVmProfileCmd; -import com.cloud.api.commands.CreateConditionCmd; -import com.cloud.api.commands.CreateCounterCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.ListAutoScalePoliciesCmd; -import com.cloud.api.commands.ListAutoScaleVmGroupsCmd; -import com.cloud.api.commands.ListAutoScaleVmProfilesCmd; -import com.cloud.api.commands.ListConditionsCmd; -import com.cloud.api.commands.ListCountersCmd; -import com.cloud.api.commands.UpdateAutoScalePolicyCmd; -import com.cloud.api.commands.UpdateAutoScaleVmGroupCmd; -import com.cloud.api.commands.UpdateAutoScaleVmProfileCmd; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmGroupCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateConditionCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmGroupsCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListConditionsCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; @@ -81,7 +77,6 @@ import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; @@ -354,7 +349,7 @@ public class AutoScaleManagerImpl implements AutoScaleManager, AutoScaleSe * For ex. if projectId is given as a string instead of an long value, this * will be throwing an error. */ - ApiDispatcher.setupParameters(new DeployVMCmd(), deployParams); + ApiDispatcher.processParameters(new DeployVMCmd(), deployParams); if (autoscaleUserId == null) { autoscaleUserId = UserContext.current().getCallerUserId(); @@ -566,8 +561,8 @@ public class AutoScaleManagerImpl implements AutoScaleManager, AutoScaleSe Account caller = UserContext.current().getCaller(); Account owner = _accountDao.findActiveAccount(accountName, domainId); if (owner == null) { - List idList = new ArrayList(); - idList.add(new IdentityProxy("domain", domainId, "domainId")); + List idList = new ArrayList(); + idList.add(ApiDBUtils.findDomainById(domainId).getUuid()); throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId"); } _accountMgr.checkAccess(caller, null, false, owner); diff --git a/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java index b387b9340f1..7d87b27507c 100644 --- a/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java +++ b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java @@ -1,21 +1,23 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("autoscale_policy_condition_map")) -public class AutoScalePolicyConditionMapVO { +public class AutoScalePolicyConditionMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/as/AutoScalePolicyVO.java b/server/src/com/cloud/network/as/AutoScalePolicyVO.java index e23e34d1aa5..f8fbcb483f5 100644 --- a/server/src/com/cloud/network/as/AutoScalePolicyVO.java +++ b/server/src/com/cloud/network/as/AutoScalePolicyVO.java @@ -1,19 +1,19 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; import java.util.Date; @@ -29,11 +29,12 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "autoscale_policies") @Inheritance(strategy = InheritanceType.JOINED) -public class AutoScalePolicyVO implements AutoScalePolicy { +public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java index 9ea6cab30d7..7e1c38af108 100644 --- a/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java +++ b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java @@ -1,21 +1,23 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("autoscale_vmgroup_policy_map")) -public class AutoScaleVmGroupPolicyMapVO { +public class AutoScaleVmGroupPolicyMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java index ab3ee1a059a..d1d85f9e293 100644 --- a/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java +++ b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java @@ -1,19 +1,19 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; import java.util.Date; @@ -29,11 +29,12 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "autoscale_vmgroups") @Inheritance(strategy = InheritanceType.JOINED) -public class AutoScaleVmGroupVO implements AutoScaleVmGroup { +public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java index ea2fc767850..011be2b41ca 100644 --- a/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java +++ b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java @@ -1,19 +1,19 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. package com.cloud.network.as; import java.util.ArrayList; @@ -33,15 +33,16 @@ import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "autoscale_vmprofiles") @Inheritance(strategy = InheritanceType.JOINED) -public class AutoScaleVmProfileVO implements AutoScaleVmProfile, Identity { +public class AutoScaleVmProfileVO implements AutoScaleVmProfile, Identity, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/as/ConditionVO.java b/server/src/com/cloud/network/as/ConditionVO.java index 45b61d859da..bbae72f2312 100644 --- a/server/src/com/cloud/network/as/ConditionVO.java +++ b/server/src/com/cloud/network/as/ConditionVO.java @@ -29,12 +29,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "conditions") -public class ConditionVO implements Condition, Identity { +public class ConditionVO implements Condition, Identity, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/as/CounterVO.java b/server/src/com/cloud/network/as/CounterVO.java index fd7bf3651f9..b7b03f716b0 100644 --- a/server/src/com/cloud/network/as/CounterVO.java +++ b/server/src/com/cloud/network/as/CounterVO.java @@ -29,12 +29,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "counter") -public class CounterVO implements Counter, Identity { +public class CounterVO implements Counter, Identity, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/dao/FirewallRulesDao.java b/server/src/com/cloud/network/dao/FirewallRulesDao.java index 2a4c200f116..cc184c84fce 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDao.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java @@ -56,6 +56,6 @@ public interface FirewallRulesDao extends GenericDao { long countRulesByIpId(long sourceIpId); List listByNetworkPurposeTrafficTypeAndNotRevoked(long networkId, FirewallRule.Purpose purpose, FirewallRule.TrafficType trafficType); - - + + List listByIpAndPurposeWithState(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state); } diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java index a2478d8d497..2fff15aff8d 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -309,4 +309,19 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i return result; } + @Override + public List listByIpAndPurposeWithState(Long ipId, Purpose purpose, State state) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("ipId", ipId); + + if (state != null) { + sc.setParameters("state", state); + } + + if (purpose != null) { + sc.setParameters("purpose", purpose); + } + + return listBy(sc); + } } diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index 4079955c2e9..1fefb75a360 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -110,4 +110,5 @@ public interface NetworkDao extends GenericDao { List listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem); + List listRedundantNetworks(); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 8228393f93f..29e2f818d55 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -23,7 +23,7 @@ import java.util.Random; import javax.ejb.Local; import javax.persistence.TableGenerator; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; @@ -103,6 +103,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("vpcId", AllFieldsSearch.entity().getVpcId(), Op.EQ); SearchBuilder join1 = _ntwkOffDao.createSearchBuilder(); join1.and("isSystem", join1.entity().isSystemOnly(), Op.EQ); + join1.and("isRedundant", join1.entity().getRedundantRouter(), Op.EQ); AllFieldsSearch.join("offerings", join1, AllFieldsSearch.entity().getNetworkOfferingId(), join1.entity().getId(), JoinBuilder.JoinType.INNER); AllFieldsSearch.done(); @@ -574,4 +575,12 @@ public class NetworkDaoImpl extends GenericDaoBase implements N List networks = search(sc, null); return networks; } + + @Override + public List listRedundantNetworks() { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setJoinParameters("offerings", "isRedundant", true); + + return listBy(sc, null); + } } diff --git a/server/src/com/cloud/network/dao/NetworkOpVO.java b/server/src/com/cloud/network/dao/NetworkOpVO.java index 5beb55cb13d..8d417278188 100644 --- a/server/src/com/cloud/network/dao/NetworkOpVO.java +++ b/server/src/com/cloud/network/dao/NetworkOpVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -23,7 +25,7 @@ import javax.persistence.Table; @Entity @Table(name="op_networks") -public class NetworkOpVO { +public class NetworkOpVO implements InternalIdentity { @Id @Column(name="id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java index d98f86e96be..59967045dbe 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -28,7 +30,7 @@ import javax.persistence.Table; */ @Entity @Table(name = "physical_network_isolation_methods") -public class PhysicalNetworkIsolationMethodVO { +public class PhysicalNetworkIsolationMethodVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java index 12b08af9327..370e4982156 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java @@ -33,10 +33,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Service; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "physical_network_service_providers") -public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceProvider { +public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceProvider, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java index bca1a45ba12..787c049d3c0 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -28,7 +30,7 @@ import javax.persistence.Table; */ @Entity @Table(name = "physical_network_tags") -public class PhysicalNetworkTagVO { +public class PhysicalNetworkTagVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java index 0561ae86fb9..4c32d0a949b 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java @@ -29,6 +29,7 @@ import javax.persistence.Table; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkTrafficType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "physical_network_traffic_types") diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 124d029be44..2b54ae0fe36 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -24,10 +24,12 @@ import java.util.Set; import javax.ejb.Local; +import com.cloud.utils.PropertiesUtil; +import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.CreateVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.ConfigureVirtualRouterElementCmd; -import com.cloud.api.commands.ListVirtualRouterElementsCmd; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -681,8 +683,12 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public String getPropertiesFile() { - return "virtualrouter_commands.properties"; + public List> getCommands() { + List> cmdList = new ArrayList>(); + cmdList.add(CreateVirtualRouterElementCmd.class); + cmdList.add(ConfigureVirtualRouterElementCmd.class); + cmdList.add(ListVirtualRouterElementsCmd.class); + return cmdList; } @Override diff --git a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java index c491fd2004e..ff2b6210504 100644 --- a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java +++ b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java @@ -30,6 +30,7 @@ import javax.persistence.Table; import com.cloud.network.VirtualRouterProvider; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("virtual_router_providers")) diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index 60c5bf30d42..7bab1bad7a5 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -26,9 +26,9 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.ListFirewallRulesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.dao.DomainDao; @@ -75,7 +75,6 @@ import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; import com.cloud.user.UserContext; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java index 47f1b18fdcb..c9b3f9336b8 100644 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java @@ -18,7 +18,7 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.lb.LoadBalancingRule.LbDestination; diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index 662a2dafdb6..0fefb2de67f 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -30,15 +30,13 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.loadbalancer.*; import org.apache.log4j.Logger; -import com.cloud.api.commands.CreateLBStickinessPolicyCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.ListLBStickinessPoliciesCmd; -import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; -import com.cloud.api.commands.ListLoadBalancerRulesCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; -import com.cloud.api.response.ServiceResponse; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleInstancesCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRulesCmd; +import org.apache.cloudstack.api.response.ServiceResponse; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; @@ -600,8 +598,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa private boolean isRollBackAllowedForProvider(LoadBalancerVO loadBalancer) { Network network = _networkDao.findById(loadBalancer.getNetworkId()); - Provider provider = Network.Provider.Netscaler; - return _ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), Service.Lb, provider); + List provider = _networkMgr.getProvidersForServiceInNetwork(network, Service.Lb); + if (provider == null || provider.size() == 0) { + return false; + } + if (provider.get(0) == Provider.Netscaler || provider.get(0) == Provider.F5BigIp) { + return true; + } + return false; } @Override @DB @@ -1077,6 +1081,12 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), lb.getDefaultPortStart(), lb.getAlgorithm(), network.getId(), ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId()); + // verify rule is supported by Lb provider of the network + LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList(), new ArrayList()); + if (!_networkMgr.validateRule(loadBalancing)) { + throw new InvalidParameterValueException("LB service provider cannot support this rule"); + } + newRule = _lbDao.persist(newRule); if (openFirewall) { diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 2a2a625f9f8..e1c78e1a4e7 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -27,15 +27,21 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Queue; import java.util.Set; import java.util.TimeZone; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -80,7 +86,6 @@ import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; -import com.cloud.api.commands.UpgradeRouterCmd; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.ManagementServerNode; import com.cloud.cluster.dao.ManagementServerHostDao; @@ -339,6 +344,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian int _routerStatsInterval = 300; int _routerCheckInterval = 30; + int _rvrStatusUpdatePoolSize = 10; protected ServiceOfferingVO _offering; private String _dnsBasicZoneUpdates = "all"; private Set _guestOSNeedGatewayOnNonDefaultNetwork = new HashSet(); @@ -353,8 +359,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian ScheduledExecutorService _executor; ScheduledExecutorService _checkExecutor; ScheduledExecutorService _networkStatsUpdateExecutor; + ExecutorService _rvrStatusUpdateExecutor; Account _systemAcct; + + BlockingQueue _vrUpdateQueue = null; @Override public boolean sendSshKeysToHost(Long hostId, String pubKey, String prvKey) { @@ -582,7 +591,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RouterMonitor")); _checkExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RouterStatusMonitor")); _networkStatsUpdateExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NetworkStatsUpdater")); - + final ComponentLocator locator = ComponentLocator.getCurrentLocator(); final Map configs = _configDao.getConfiguration("AgentManager", params); @@ -609,7 +618,18 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian value = configs.get("router.check.interval"); _routerCheckInterval = NumbersUtil.parseInt(value, 30); - + + value = configs.get("router.check.poolsize"); + _rvrStatusUpdatePoolSize = NumbersUtil.parseInt(value, 10); + + /* + * We assume that one thread can handle 20 requests in 1 minute in normal situation, so here we give the queue size up to 50 minutes. + * It's mostly for buffer, since each time CheckRouterTask running, it would add all the redundant networks in the queue immediately + */ + _vrUpdateQueue = new LinkedBlockingQueue(_rvrStatusUpdatePoolSize * 1000); + + _rvrStatusUpdateExecutor = Executors.newFixedThreadPool(_rvrStatusUpdatePoolSize, new NamedThreadFactory("RedundantRouterStatusMonitor")); + _instance = configs.get("instance.name"); if (_instance == null) { _instance = "DEFAULT"; @@ -707,6 +727,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (_routerCheckInterval > 0) { _checkExecutor.scheduleAtFixedRate(new CheckRouterTask(), _routerCheckInterval, _routerCheckInterval, TimeUnit.SECONDS); + for (int i = 0; i < _rvrStatusUpdatePoolSize; i++) { + _rvrStatusUpdateExecutor.execute(new RvRStatusUpdateTask()); + } } else { s_logger.debug("router.check.interval - " + _routerCheckInterval+ " so not scheduling the redundant router checking thread"); } @@ -803,26 +826,29 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian String privateIP = router.getPrivateIpAddress(); if (privateIP != null) { + boolean forVpc = router.getVpcId() != null; List routerNics = _nicDao.listByVmId(router.getId()); for (Nic routerNic : routerNics) { Network network = _networkModel.getNetwork(routerNic.getNetworkId()); - if (network.getTrafficType() == TrafficType.Public) { - boolean forVpc = router.getVpcId() != null; + //Send network usage command for public nic in VPC VR + //Send network usage command for isolated guest nic of non VPC VR + if ((forVpc && network.getTrafficType() == TrafficType.Public) || (!forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated)) { final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), forVpc, routerNic.getIp4Address()); - UserStatisticsVO previousStats = _statsDao.findBy(router.getAccountId(), - router.getDataCenterIdToDeployIn(), network.getId(), null, router.getId(), router.getType().toString()); + String routerType = router.getType().toString(); + UserStatisticsVO previousStats = _statsDao.findBy(router.getAccountId(), + router.getDataCenterIdToDeployIn(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType); NetworkUsageAnswer answer = null; try { answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd); } catch (Exception e) { - s_logger.warn("Error while collecting network stats from router: "+router.getInstanceName()+" from host: "+router.getHostId(), e); + s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId(), e); continue; } if (answer != null) { if (!answer.getResult()) { - s_logger.warn("Error while collecting network stats from router: "+router.getInstanceName()+" from host: "+router.getHostId() + "; details: " + answer.getDetails()); + s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails()); continue; } Transaction txn = Transaction.open(Transaction.CLOUD_DB); @@ -832,27 +858,27 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian continue; } txn.start(); - UserStatisticsVO stats = _statsDao.lock(router.getAccountId(), - router.getDataCenterIdToDeployIn(), network.getId(), routerNic.getIp4Address(), router.getId(), router.getType().toString()); + UserStatisticsVO stats = _statsDao.lock(router.getAccountId(), + router.getDataCenterIdToDeployIn(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType); if (stats == null) { s_logger.warn("unable to find stats for account: " + router.getAccountId()); continue; } - if(previousStats != null - && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived()) - || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))){ + if (previousStats != null + && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived()) + || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))) { s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " + - "Ignoring current answer. Router: "+answer.getRouterName()+" Rcvd: " + - answer.getBytesReceived()+ "Sent: " +answer.getBytesSent()); + "Ignoring current answer. Router: " + answer.getRouterName() + " Rcvd: " + + answer.getBytesReceived() + "Sent: " + answer.getBytesSent()); continue; } if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Received # of bytes that's less than the last one. " + - "Assuming something went wrong and persisting it. Router: " + - answer.getRouterName()+" Reported: " + answer.getBytesReceived() + "Assuming something went wrong and persisting it. Router: " + + answer.getRouterName() + " Reported: " + answer.getBytesReceived() + " Stored: " + stats.getCurrentBytesReceived()); } stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived()); @@ -861,8 +887,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (stats.getCurrentBytesSent() > answer.getBytesSent()) { if (s_logger.isDebugEnabled()) { s_logger.debug("Received # of bytes that's less than the last one. " + - "Assuming something went wrong and persisting it. Router: " + - answer.getRouterName()+" Reported: " + answer.getBytesSent() + "Assuming something went wrong and persisting it. Router: " + + answer.getRouterName() + " Reported: " + answer.getBytesSent() + " Stored: " + stats.getCurrentBytesSent()); } stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent()); @@ -1042,14 +1068,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (host == null || host.getStatus() != Status.Up) { router.setRedundantState(RedundantState.UNKNOWN); updated = true; - } else if (host.getManagementServerId() != ManagementServerNode.getManagementServerId()) { - /* Only cover hosts managed by this management server */ - continue; } else if (privateIP != null) { final CheckRouterCommand command = new CheckRouterCommand(); command.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId())); command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); - command.setWait(60); + command.setWait(30); final Answer origAnswer = _agentMgr.easySend(router.getHostId(), command); CheckRouterAnswer answer = null; if (origAnswer instanceof CheckRouterAnswer) { @@ -1131,11 +1154,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian return priority; } - protected class CheckRouterTask implements Runnable { + protected class RvRStatusUpdateTask implements Runnable { - public CheckRouterTask() { + public RvRStatusUpdateTask() { } - + /* * In order to make fail-over works well at any time, we have to ensure: * 1. Backup router's priority = Master's priority - DELTA + 1 @@ -1198,9 +1221,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian String title = "More than one redundant virtual router is in MASTER state! Router " + router.getHostName() + " and router " + dupRouter.getHostName(); String context = "Virtual router (name: " + router.getHostName() + ", id: " + router.getId() + " and router (name: " + dupRouter.getHostName() + ", id: " + router.getId() + ") are both in MASTER state! If the problem persist, restart both of routers. "; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterIdToDeployIn(), router.getPodIdToDeployIn(), title, context); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER, dupRouter.getDataCenterIdToDeployIn(), dupRouter.getPodIdToDeployIn(), title, context); + s_logger.warn(context); } else { networkRouterMaps.put(routerGuestNtwkId, router); } @@ -1209,19 +1232,61 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } } + @Override + public void run() { + while (true) { + try { + Long networkId = _vrUpdateQueue.take(); + List routers = _routerDao.listByNetworkAndRole(networkId, Role.VIRTUAL_ROUTER); + + if (routers.size() != 2) { + continue; + } + /* + * We update the router pair which the lower id router owned by this mgmt server, in order + * to prevent duplicate update of router status from cluster mgmt servers + */ + DomainRouterVO router = routers.get(0); + if (routers.get(1).getId() < router.getId()) { + router = routers.get(1); + } + HostVO host = _hostDao.findById(router.getHostId()); + if (host == null || host.getManagementServerId() == null || + host.getManagementServerId() != ManagementServerNode.getManagementServerId()) { + continue; + } + updateRoutersRedundantState(routers); + checkDuplicateMaster(routers); + checkSanity(routers); + } catch (Exception ex) { + s_logger.error("Fail to complete the RvRStatusUpdateTask! ", ex); + } + } + } + + } + + protected class CheckRouterTask implements Runnable { + + public CheckRouterTask() { + } + @Override public void run() { try { final List routers = _routerDao.listIsolatedByHostId(null); - s_logger.debug("Found " + routers.size() + " routers. "); + s_logger.debug("Found " + routers.size() + " routers to update status. "); - updateRoutersRedundantState(routers); updateSite2SiteVpnConnectionState(routers); - /* FIXME assumed the a pair of redundant routers managed by same mgmt server, - * then the update above can get the latest status */ - checkDuplicateMaster(routers); - checkSanity(routers); + final List networks = _networkDao.listRedundantNetworks(); + s_logger.debug("Found " + networks.size() + " networks to update RvR status. "); + for (NetworkVO network : networks) { + if (!_vrUpdateQueue.offer(network.getId(), 500, TimeUnit.MILLISECONDS)) { + s_logger.warn("Cannot insert into virtual router update queue! Adjustment of router.check.interval and router.check.poolsize maybe needed."); + break; + } + } } catch (Exception ex) { s_logger.error("Fail to complete the CheckRouterTask! ", ex); } @@ -1409,31 +1474,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian offeringId = _offering.getId(); } + PublicIp sourceNatIp = null; + if (publicNetwork) { + sourceNatIp = _networkMgr.assignSourceNatIpAddressToGuestNetwork(owner, guestNetwork); + } + // 3) deploy virtual router(s) int count = routerCount - routers.size(); DeploymentPlan plan = planAndRouters.first(); for (int i = 0; i < count; i++) { - PublicIp sourceNatIp = null; - if (publicNetwork) { - int failCount = 0; - // Generate different MAC for VR - while (sourceNatIp == null) { - sourceNatIp = _networkMgr.assignSourceNatIpAddressToGuestNetwork(owner, guestNetwork); - NicVO nic = _nicDao.findByMacAddress(sourceNatIp.getMacAddress()); - // We got duplicate MAC here, so regenerate the mac - if (nic != null) { - s_logger.debug("Failed to find a different mac for redundant router. Try again. The current mac is " + sourceNatIp.getMacAddress()); - sourceNatIp = null; - failCount ++; - } - //Prevent infinite loop - if (failCount > 3) { - s_logger.error("Failed to find a different mac for redundant router! Abort operation!"); - throw new InsufficientAddressCapacityException("Failed to find a different mac for redundant router", null, offeringId); - } - } - } - List> networks = createRouterNetworks(owner, isRedundant, plan, guestNetwork, new Pair(publicNetwork, sourceNatIp)); //don't start the router as we are holding the network lock that needs to be released at the end of router allocation @@ -1655,6 +1704,13 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } NetworkOffering publicOffering = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemPublicNetwork).get(0); List publicNetworks = _networkMgr.setupNetwork(_systemAcct, publicOffering, plan, null, null, false); + String publicIp = defaultNic.getIp4Address(); + // We want to use the identical MAC address for RvR on public interface if possible + NicVO peerNic = _nicDao.findByIp4AddressAndNetworkId(publicIp, publicNetworks.get(0).getId()); + if (peerNic != null) { + s_logger.info("Use same MAC as previous RvR, the MAC is " + peerNic.getMacAddress()); + defaultNic.setMacAddress(peerNic.getMacAddress()); + } networks.add(new Pair(publicNetworks.get(0), defaultNic)); } @@ -2836,6 +2892,8 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()]; int i = 0; + // We don't support VR to be inline currently + boolean inline = false; for (LoadBalancingRule rule : rules) { boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); @@ -2846,7 +2904,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); List stickinessPolicies = rule.getStickinessPolicies(); - LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, destinations, stickinessPolicies); + LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, stickinessPolicies); lbs[i++] = lb; } String routerPublicIp = null; diff --git a/server/src/com/cloud/network/rules/FirewallRuleVO.java b/server/src/com/cloud/network/rules/FirewallRuleVO.java index c2539310d6e..63ace5baa6e 100644 --- a/server/src/com/cloud/network/rules/FirewallRuleVO.java +++ b/server/src/com/cloud/network/rules/FirewallRuleVO.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -34,79 +34,80 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="firewall_rules") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) -public class FirewallRuleVO implements Identity, FirewallRule { +public class FirewallRuleVO implements FirewallRule { protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); - + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @GeneratedValue(strategy=GenerationType.AUTO) @Column(name=GenericDao.XID_COLUMN) String xId; @Column(name="domain_id", updatable=false) long domainId; - + @Column(name="account_id", updatable=false) long accountId; - + @Column(name="ip_address_id", updatable=false) Long sourceIpAddressId; - + @Column(name="start_port", updatable=false) Integer sourcePortStart; @Column(name="end_port", updatable=false) Integer sourcePortEnd; - + @Column(name="protocol", updatable=false) String protocol = NetUtils.TCP_PROTO; - + @Enumerated(value=EnumType.STRING) @Column(name="purpose") Purpose purpose; - + @Enumerated(value=EnumType.STRING) @Column(name="state") State state; - + @Column(name=GenericDao.CREATED_COLUMN) Date created; - + @Column(name="network_id") long networkId; - + @Column(name="icmp_code") Integer icmpCode; - + @Column(name="icmp_type") Integer icmpType; - + @Column(name="related") Long related; - + @Column(name="type") @Enumerated(value=EnumType.STRING) FirewallRuleType type; - + @Column(name="traffic_type") @Enumerated(value=EnumType.STRING) TrafficType trafficType; - - + + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call firewallrules dao to load it. @@ -124,7 +125,7 @@ public class FirewallRuleVO implements Identity, FirewallRule { public List getSourceCidrList() { if (sourceCidrs == null && (purpose == Purpose.Firewall || purpose == Purpose.NetworkACL)) { return _firewallRulesCidrsDao.getSourceCidrs(id); - } + } return sourceCidrs; } @@ -167,7 +168,7 @@ public class FirewallRuleVO implements Identity, FirewallRule { public String getProtocol() { return protocol; } - + public void setState(State state) { this.state = state; } @@ -176,17 +177,17 @@ public class FirewallRuleVO implements Identity, FirewallRule { public Purpose getPurpose() { return purpose; } - + @Override public State getState() { return state; } - + @Override public long getNetworkId() { return networkId; } - + @Override public FirewallRuleType getType() { return type; @@ -194,12 +195,12 @@ public class FirewallRuleVO implements Identity, FirewallRule { public Date getCreated() { return created; } - + protected FirewallRuleVO() { this.uuid = UUID.randomUUID().toString(); } - - public FirewallRuleVO(String xId, Long ipAddressId, Integer portStart, Integer portEnd, String protocol, + + public FirewallRuleVO(String xId, Long ipAddressId, Integer portStart, Integer portEnd, String protocol, long networkId, long accountId, long domainId, Purpose purpose, List sourceCidrs, Integer icmpCode, Integer icmpType, Long related, TrafficType trafficType) { this.xId = xId; @@ -208,11 +209,11 @@ public class FirewallRuleVO implements Identity, FirewallRule { } this.accountId = accountId; this.domainId = domainId; - + if (ipAddressId == null) { assert (purpose == Purpose.NetworkACL) : "ipAddressId can be null for " + Purpose.NetworkACL + " only"; } - + this.sourceIpAddressId = ipAddressId; this.sourcePortStart = portStart; this.sourcePortEnd = portEnd; @@ -223,28 +224,28 @@ public class FirewallRuleVO implements Identity, FirewallRule { this.icmpCode = icmpCode; this.icmpType = icmpType; this.sourceCidrs = sourceCidrs; - + if (related != null) { assert (purpose == Purpose.Firewall) : "related field can be set for rule of purpose " + Purpose.Firewall + " only"; } - + this.related = related; this.uuid = UUID.randomUUID().toString(); this.type = FirewallRuleType.User; this.trafficType = trafficType; } - - - public FirewallRuleVO(String xId, long ipAddressId, int port, String protocol, long networkId, long accountId, + + + public FirewallRuleVO(String xId, long ipAddressId, int port, String protocol, long networkId, long accountId, long domainId, Purpose purpose, List sourceCidrs, Integer icmpCode, Integer icmpType, Long related) { this(xId, ipAddressId, port, port, protocol, networkId, accountId, domainId, purpose, sourceCidrs, icmpCode, icmpType, related, null); } - + @Override public String toString() { return new StringBuilder("Rule[").append(id).append("-").append(purpose).append("-").append(state).append("]").toString(); } - + @Override public Integer getIcmpCode() { return icmpCode; @@ -259,16 +260,16 @@ public class FirewallRuleVO implements Identity, FirewallRule { public Long getRelated() { return related; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public void setType(FirewallRuleType type) { this.type = type; } diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index 1548afeb420..fc12660638f 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -16,7 +16,6 @@ // under the License. package com.cloud.network.rules; -import com.cloud.api.commands.ListPortForwardingRulesCmd; import com.cloud.configuration.ConfigurationManager; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; @@ -65,6 +64,7 @@ import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; +import org.apache.cloudstack.api.command.user.firewall.ListPortForwardingRulesCmd; import org.apache.log4j.Logger; import javax.ejb.Local; @@ -1176,12 +1176,11 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { Network guestNetwork = _networkModel.getNetwork(ipAddress.getAssociatedWithNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) { - if (offering.getAssociatePublicIP()) { - getSystemIpAndEnableStaticNatForVm(_vmDao.findById(vmId), true); - return true; - } + getSystemIpAndEnableStaticNatForVm(_vmDao.findById(vmId), true); + return true; + } else { + return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); } - return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); } @Override @@ -1367,11 +1366,6 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { Network guestNetwork = _networkModel.getNetwork(nic.getNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) { - boolean isSystemVM = (vm.getType() == Type.ConsoleProxy || vm.getType() == Type.SecondaryStorageVm); - // for user VM's associate public IP only if offering is marked to associate a public IP by default on start of VM - if (!isSystemVM && !offering.getAssociatePublicIP()) { - continue; - } // check if there is already static nat enabled if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) { s_logger.debug("Vm " + vm + " already has ip associated with it in guest network " + guestNetwork); @@ -1386,6 +1380,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { s_logger.debug("Allocated system ip " + ip + ", now enabling static nat on it for vm " + vm); + boolean isSystemVM = (vm.getType() == Type.ConsoleProxy || vm.getType() == Type.SecondaryStorageVm); try { success = enableStaticNat(ip.getId(), vm.getId(), guestNetwork.getId(), isSystemVM); } catch (NetworkRuleConflictException ex) { diff --git a/server/src/com/cloud/network/rules/StaticNatRuleImpl.java b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java index 4ae7ab2adab..6103689a31b 100644 --- a/server/src/com/cloud/network/rules/StaticNatRuleImpl.java +++ b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -19,9 +19,10 @@ package com.cloud.network.rules; import java.util.List; -public class StaticNatRuleImpl implements StaticNatRule{ +public class StaticNatRuleImpl implements StaticNatRule { long id; String xid; + String uuid; String protocol; int portStart; int portEnd; @@ -32,9 +33,10 @@ public class StaticNatRuleImpl implements StaticNatRule{ long sourceIpAddressId; String destIpAddress; - public StaticNatRuleImpl(FirewallRuleVO rule, String dstIp) { + public StaticNatRuleImpl(FirewallRuleVO rule, String dstIp) { this.id = rule.getId(); this.xid = rule.getXid(); + this.uuid = rule.getUuid(); this.protocol = rule.getProtocol(); this.portStart = rule.getSourcePortStart(); this.portEnd = rule.getSourcePortEnd(); @@ -55,7 +57,7 @@ public class StaticNatRuleImpl implements StaticNatRule{ public Integer getSourcePortEnd() { return portEnd; } - + @Override public Purpose getPurpose() { return Purpose.StaticNat; @@ -65,17 +67,17 @@ public class StaticNatRuleImpl implements StaticNatRule{ public State getState() { return state; } - + @Override public long getAccountId() { return accountId; } - + @Override public long getDomainId() { return domainId; } - + @Override public long getNetworkId() { return networkId; @@ -105,12 +107,18 @@ public class StaticNatRuleImpl implements StaticNatRule{ public String getXid() { return xid; } - + + + @Override + public String getUuid() { + return uuid; + } + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -130,7 +138,7 @@ public class StaticNatRuleImpl implements StaticNatRule{ public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index 1d7d0fdb0e8..b564e3d5759 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -36,6 +36,7 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.securitygroup.*; import org.apache.commons.codec.digest.DigestUtils; import org.apache.log4j.Logger; @@ -44,13 +45,10 @@ import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd; -import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; -import com.cloud.api.commands.CreateSecurityGroupCmd; -import com.cloud.api.commands.DeleteSecurityGroupCmd; -import com.cloud.api.commands.ListSecurityGroupsCmd; -import com.cloud.api.commands.RevokeSecurityGroupEgressCmd; -import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.vo.SecurityGroupJoinVO; + +import org.apache.cloudstack.api.command.user.securitygroup.RevokeSecurityGroupEgressCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.dao.DomainDao; @@ -78,8 +76,6 @@ import com.cloud.network.security.dao.VmRulesetLogDao; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.ProjectManager; import com.cloud.server.ManagementServer; -import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -97,10 +93,10 @@ import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.net.NetUtils; @@ -125,6 +121,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG @Inject SecurityGroupDao _securityGroupDao; @Inject + SecurityGroupJoinDao _securityGroupJoinDao; + @Inject SecurityGroupRuleDao _securityGroupRuleDao; @Inject SecurityGroupVMMapDao _securityGroupVMMapDao; @@ -164,7 +162,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG UsageEventDao _usageEventDao; @Inject ResourceTagDao _resourceTagDao; - + ScheduledExecutorService _executorPool; ScheduledExecutorService _cleanupExecutor; @@ -402,7 +400,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG if (s_logger.isTraceEnabled()) { s_logger.trace("Security Group Mgr: scheduling ruleset updates for " + affectedVms.size() + " vms"); } - boolean locked = _workLock.lock(_globalWorkLockTimeout); + boolean locked = _workLock.lock(_globalWorkLockTimeout); if (!locked) { s_logger.warn("Security Group Mgr: failed to acquire global work lock"); return; @@ -581,11 +579,11 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG Map groupList = cmd.getUserSecurityGroupList(); return authorizeSecurityGroupRule(securityGroupId,protocol,startPort,endPort,icmpType,icmpCode,cidrList,groupList,SecurityRuleType.IngressRule); } - + private List authorizeSecurityGroupRule(Long securityGroupId,String protocol,Integer startPort,Integer endPort,Integer icmpType,Integer icmpCode,List cidrList,Map groupList,SecurityRuleType ruleType) { Integer startPortOrType = null; Integer endPortOrCode = null; - + // Validate parameters SecurityGroup securityGroup = _securityGroupDao.findById(securityGroupId); if (securityGroup == null) { @@ -753,7 +751,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG } } } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_REVOKE_EGRESS, eventDescription = "Revoking Egress Rule ", async = true) @@ -761,7 +759,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG Long id = cmd.getId(); return revokeSecurityGroupRule(id, SecurityRuleType.EgressRule); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_REVOKE_INGRESS, eventDescription = "Revoking Ingress Rule ", async = true) @@ -770,11 +768,11 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG Long id = cmd.getId(); return revokeSecurityGroupRule(id, SecurityRuleType.IngressRule); } - + private boolean revokeSecurityGroupRule(Long id, SecurityRuleType type) { // input validation Account caller = UserContext.current().getCaller(); - + SecurityGroupRuleVO rule = _securityGroupRuleDao.findById(id); if (rule == null) { s_logger.debug("Unable to find security rule with id " + id); @@ -786,7 +784,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG s_logger.debug("Mismatch in rule type for security rule with id " + id ); throw new InvalidParameterValueException("Mismatch in rule type for security rule with id " + id); } - + // Check permissions SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId()); _accountMgr.checkAccess(caller, null, true, securityGroup); @@ -867,13 +865,13 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId(); - s_logger.info("SecurityGroupManager: num worker threads=" + _numWorkerThreads + + s_logger.info("SecurityGroupManager: num worker threads=" + _numWorkerThreads + ", time between cleanups=" + _timeBetweenCleanups + " global lock timeout=" + _globalWorkLockTimeout); createThreadPools(); return true; } - + protected void createThreadPools() { _executorPool = Executors.newScheduledThreadPool(_numWorkerThreads, new NamedThreadFactory("NWGRP")); _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("NWGRP-Cleanup")); @@ -970,7 +968,7 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG s_logger.debug("Unable to send ingress rules updates for vm: " + userVmId + "(agentid=" + agentId + ")"); _workDao.updateStep(work.getInstanceId(), seqnum, Step.Done); } - + } } } finally { @@ -1094,101 +1092,24 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG return true; } - @Override - public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { - Account caller = UserContext.current().getCaller(); - Long instanceId = cmd.getVirtualMachineId(); - String securityGroup = cmd.getSecurityGroupName(); - Long id = cmd.getId(); - Object keyword = cmd.getKeyword(); - List permittedAccounts = new ArrayList(); - Map tags = cmd.getTags(); - if (instanceId != null) { - UserVmVO userVM = _userVMDao.findById(instanceId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); - } - _accountMgr.checkAccess(caller, null, true, userVM); - return listSecurityGroupRulesByVM(instanceId.longValue()); + + private Pair, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) { + Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize); + Pair, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf); + Integer count = sgVmMappingPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return new Pair, Integer>(new ArrayList(), count); } - - List securityRulesList = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(SecurityGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _securityGroupDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); + List sgVmMappings = sgVmMappingPair.first(); + Long[] sgIds = new Long[sgVmMappings.size()]; + int i = 0; + for (SecurityGroupVMMapVO sgVm : sgVmMappings) { + sgIds[i++] = sgVm.getSecurityGroupId(); } - - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (id != null) { - sc.setParameters("id", id); - } - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.SecurityGroup.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - if (securityGroup != null) { - sc.setParameters("name", securityGroup); - } - - if (keyword != null) { - SearchCriteria ssc = _securityGroupRulesDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - List securityGroups = _securityGroupDao.search(sc, searchFilter); - for (SecurityGroupVO group : securityGroups) { - securityRulesList.addAll(_securityGroupRulesDao.listSecurityRulesByGroupId(group.getId())); - } - - return securityRulesList; - } - - private List listSecurityGroupRulesByVM(long vmId) { - List results = new ArrayList(); - List networkGroupMappings = _securityGroupVMMapDao.listByInstanceId(vmId); - if (networkGroupMappings != null) { - for (SecurityGroupVMMapVO networkGroupMapping : networkGroupMappings) { - SecurityGroupVO group = _securityGroupDao.findById(networkGroupMapping.getSecurityGroupId()); - List rules = _securityGroupRulesDao.listSecurityGroupRules(group.getAccountId(), networkGroupMapping.getGroupName()); - if (rules != null) { - results.addAll(rules); - } - } - } - return results; + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); } @Override diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java index cc842df7d64..cbeae4f1483 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java @@ -19,12 +19,15 @@ package com.cloud.network.security.dao; import java.util.List; import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; import com.cloud.vm.VirtualMachine.State; public interface SecurityGroupVMMapDao extends GenericDao { List listByIpAndInstanceId(String ipAddress, long instanceId); List listByInstanceId(long instanceId); + Pair, Integer> listByInstanceId(long instanceId, Filter filter); List listByIp(String ipAddress); List listBySecurityGroup(long securityGroupId); List listBySecurityGroup(long securityGroupId, State ... vmStates); diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java index db6c0029447..95dd7f3aca2 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java @@ -24,6 +24,8 @@ import com.cloud.dc.VlanVO; import com.cloud.dc.Vlan.VlanType; import com.cloud.network.IPAddressVO; import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; @@ -114,6 +116,13 @@ public class SecurityGroupVMMapDaoImpl extends GenericDaoBase, Integer> listByInstanceId(long instanceId, Filter filter) { + SearchCriteria sc = ListByVmId.create(); + sc.setParameters("instanceId", instanceId); + return this.searchAndCount(sc, filter); + } + @Override public int deleteVM(long instanceId) { SearchCriteria sc = ListByVmId.create(); diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java index 36cb8d50952..5e5b4baff80 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java @@ -23,10 +23,10 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.ListNetworkACLsCmd; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -51,7 +51,6 @@ import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.UserContext; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; diff --git a/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java b/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java index 4ad1fb6f525..2595a6a0fa4 100644 --- a/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java +++ b/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java @@ -17,7 +17,7 @@ package com.cloud.network.vpc; -public class PrivateGatewayProfile implements PrivateGateway{ +public class PrivateGatewayProfile implements PrivateGateway { VpcGateway vpcGateway; long physicalNetworkId; diff --git a/server/src/com/cloud/network/vpc/PrivateIpVO.java b/server/src/com/cloud/network/vpc/PrivateIpVO.java index f20150da660..e6616ae3899 100644 --- a/server/src/com/cloud/network/vpc/PrivateIpVO.java +++ b/server/src/com/cloud/network/vpc/PrivateIpVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.vpc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -30,7 +32,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="private_ip_address") -public class PrivateIpVO{ +public class PrivateIpVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/StaticRouteVO.java b/server/src/com/cloud/network/vpc/StaticRouteVO.java index 8f6dd03bb79..eb4c61b7860 100644 --- a/server/src/com/cloud/network/vpc/StaticRouteVO.java +++ b/server/src/com/cloud/network/vpc/StaticRouteVO.java @@ -28,47 +28,48 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="static_routes") -public class StaticRouteVO implements Identity, StaticRoute{ +public class StaticRouteVO implements StaticRoute { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="uuid") String uuid; - + @Column(name="vpc_gateway_id", updatable=false) long vpcGatewayId; - + @Column(name="cidr") private String cidr; - + @Enumerated(value=EnumType.STRING) @Column(name="state") State state; - + @Column(name="vpc_id") private Long vpcId; - + @Column(name = "account_id") long accountId; @Column(name = "domain_id") long domainId; - + @Column(name=GenericDao.CREATED_COLUMN) Date created; - + protected StaticRouteVO(){ this.uuid = UUID.randomUUID().toString(); } - + /** * @param vpcGatewayId * @param cidr @@ -86,7 +87,7 @@ public class StaticRouteVO implements Identity, StaticRoute{ this.domainId = domainId; this.uuid = UUID.randomUUID().toString(); } - + @Override public long getVpcGatewayId() { return vpcGatewayId; @@ -130,7 +131,7 @@ public class StaticRouteVO implements Identity, StaticRoute{ public void setState(State state) { this.state = state; } - + @Override public String toString() { StringBuilder buf = new StringBuilder("StaticRoute["); diff --git a/server/src/com/cloud/network/vpc/VpcGatewayVO.java b/server/src/com/cloud/network/vpc/VpcGatewayVO.java index 43a99104834..718e4df82df 100644 --- a/server/src/com/cloud/network/vpc/VpcGatewayVO.java +++ b/server/src/com/cloud/network/vpc/VpcGatewayVO.java @@ -29,11 +29,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_gateways") -public class VpcGatewayVO implements VpcGateway{ +public class VpcGatewayVO implements VpcGateway { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/VpcManager.java b/server/src/com/cloud/network/vpc/VpcManager.java index 9d7aaa8152b..8d49aa1615c 100644 --- a/server/src/com/cloud/network/vpc/VpcManager.java +++ b/server/src/com/cloud/network/vpc/VpcManager.java @@ -18,7 +18,7 @@ package com.cloud.network.vpc; import java.util.List; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index e95c54f5df6..fa6bd30f980 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -30,11 +30,11 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource.ResourceType; @@ -989,7 +989,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ } else { if (_ntwkModel.areServicesSupportedInNetwork(network.getId(), Service.Lb)) { throw new InvalidParameterValueException("LB service is already supported " + - "by network " + network + " in VPC " + vpc); + "by network " + network + " in VPC " + vpc); } } } @@ -1076,7 +1076,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ //5) network domain should be the same as VPC's if (!networkDomain.equalsIgnoreCase(vpc.getNetworkDomain())) { throw new InvalidParameterValueException("Network domain of the new network should match network" + - " domain of vpc " + vpc); + " domain of vpc " + vpc); } //6) gateway should never be equal to the cidr subnet diff --git a/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java b/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java index 3615703ca4a..9dbb32f37d9 100644 --- a/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java +++ b/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java @@ -28,11 +28,12 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_offering_service_map") -public class VpcOfferingServiceMapVO { +public class VpcOfferingServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/vpc/VpcOfferingVO.java b/server/src/com/cloud/network/vpc/VpcOfferingVO.java index 7458a66ffbe..dce7a81e4d0 100644 --- a/server/src/com/cloud/network/vpc/VpcOfferingVO.java +++ b/server/src/com/cloud/network/vpc/VpcOfferingVO.java @@ -29,11 +29,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_offerings") -public class VpcOfferingVO implements VpcOffering{ +public class VpcOfferingVO implements VpcOffering { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/VpcVO.java b/server/src/com/cloud/network/vpc/VpcVO.java index 4691b0508a9..634df052850 100644 --- a/server/src/com/cloud/network/vpc/VpcVO.java +++ b/server/src/com/cloud/network/vpc/VpcVO.java @@ -26,12 +26,13 @@ import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc") -public class VpcVO implements Vpc, Identity { +public class VpcVO implements Vpc { @Id @Column(name="id") long id; diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index e0f114d0909..81721ea4992 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -24,10 +24,10 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.ListRemoteAccessVpnsCmd; -import com.cloud.api.commands.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.DomainVO; diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index 8c1ebe502fc..44baf99b0c0 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -25,17 +25,17 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnCustomerGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ResetVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.event.ActionEvent; diff --git a/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java index b21581419d0..f249405e7b6 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java @@ -28,10 +28,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="ntwk_offering_service_map") -public class NetworkOfferingServiceMapVO { +public class NetworkOfferingServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 2570b70f630..efaca764020 100755 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -16,7 +16,6 @@ // under the License. package com.cloud.offerings; -import com.cloud.api.Identity; import com.cloud.network.Network; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; @@ -28,7 +27,7 @@ import java.util.UUID; @Entity @Table(name = "network_offerings") -public class NetworkOfferingVO implements NetworkOffering, Identity { +public class NetworkOfferingVO implements NetworkOffering { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -114,8 +113,8 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { @Column(name = "elastic_lb_service") boolean elasticLb; - @Column(name = "eip_associate_public_ip") - boolean eipAssociatePublicIp; + @Column(name = "inline") + boolean inline; @Override public String getDisplayText() { @@ -277,20 +276,20 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { this.redundantRouter = false; this.elasticIp = false; this.elasticLb = false; - this.eipAssociatePublicIp = true; + this.inline = false; this.specifyIpRanges = specifyIpRanges; } public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault, Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb, - boolean associatePublicIP, boolean specifyIpRanges) { + boolean specifyIpRanges, boolean inline) { this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges); this.dedicatedLB = dedicatedLb; this.sharedSourceNat = sharedSourceNat; this.redundantRouter = redundantRouter; this.elasticIp = elasticIp; this.elasticLb = elasticLb; - this.eipAssociatePublicIp = associatePublicIP; + this.inline = inline; } public NetworkOfferingVO() { @@ -298,7 +297,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { /** * Network Offering for all system vms. - * + * * @param name * @param trafficType * @param specifyIpRanges @@ -308,9 +307,9 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges); this.state = State.Enabled; } - + public NetworkOfferingVO(String name, Network.GuestType guestType) { - this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional, + this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional, null, Network.GuestType.Isolated, true, false); this.state = State.Enabled; } @@ -352,11 +351,6 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { return elasticIp; } - @Override - public boolean getAssociatePublicIP() { - return eipAssociatePublicIp; - } - @Override public boolean getElasticLb() { return elasticLb; @@ -367,4 +361,8 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { return specifyIpRanges; } + @Override + public boolean isInline() { + return inline; + } } diff --git a/server/src/com/cloud/projects/ProjectAccountVO.java b/server/src/com/cloud/projects/ProjectAccountVO.java index c3d7d735e73..8c4f1ba5e04 100644 --- a/server/src/com/cloud/projects/ProjectAccountVO.java +++ b/server/src/com/cloud/projects/ProjectAccountVO.java @@ -28,11 +28,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="project_account") @SuppressWarnings("unused") -public class ProjectAccountVO implements ProjectAccount{ +public class ProjectAccountVO implements ProjectAccount, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/projects/ProjectInvitationVO.java b/server/src/com/cloud/projects/ProjectInvitationVO.java index 7dc8f7daf54..78f05c792e6 100644 --- a/server/src/com/cloud/projects/ProjectInvitationVO.java +++ b/server/src/com/cloud/projects/ProjectInvitationVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "project_invitations") -public class ProjectInvitationVO implements ProjectInvitation, Identity { +public class ProjectInvitationVO implements ProjectInvitation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/projects/ProjectManager.java b/server/src/com/cloud/projects/ProjectManager.java index a243d2d3891..f5681464615 100644 --- a/server/src/com/cloud/projects/ProjectManager.java +++ b/server/src/com/cloud/projects/ProjectManager.java @@ -35,4 +35,6 @@ public interface ProjectManager extends ProjectService { boolean deleteProject(Account caller, long callerUserId, ProjectVO project); + long getInvitationTimeout(); + } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index c922ddb2c12..15d36750ee4 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -17,7 +17,6 @@ package com.cloud.projects; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; @@ -40,12 +39,14 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; -import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; @@ -54,14 +55,11 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.Project.State; import com.cloud.projects.ProjectAccount.Role; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.projects.dao.ProjectInvitationDao; -import com.cloud.server.ResourceTag.TaggedResourceType; -import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -73,17 +71,10 @@ import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; -import com.cloud.utils.db.JoinBuilder; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.sun.mail.smtp.SMTPMessage; @@ -95,47 +86,53 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public static final Logger s_logger = Logger.getLogger(ProjectManagerImpl.class); private String _name; private EmailInvite _emailInvite; - + @Inject private DomainDao _domainDao; @Inject private ProjectDao _projectDao; @Inject + private ProjectJoinDao _projectJoinDao; + @Inject AccountManager _accountMgr; @Inject DomainManager _domainMgr; @Inject - ConfigurationManager _configMgr; + ConfigurationManager _configMgr; @Inject ResourceLimitService _resourceLimitMgr; @Inject private ProjectAccountDao _projectAccountDao; @Inject + private ProjectAccountJoinDao _projectAccountJoinDao; + @Inject private AccountDao _accountDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectInvitationDao _projectInvitationDao; @Inject + private ProjectInvitationJoinDao _projectInvitationJoinDao; + @Inject protected ResourceTagDao _resourceTagDao; - + protected boolean _invitationRequired = false; protected long _invitationTimeOut = 86400000; protected boolean _allowUserToCreateProject = true; protected ScheduledExecutorService _executor; protected int _projectCleanupExpInvInterval = 60; //Interval defining how often project invitation cleanup thread is running - - + + @Override public boolean configure(final String name, final Map params) throws ConfigurationException { _name = name; - + Map configs = _configDao.getConfiguration(params); _invitationRequired = Boolean.valueOf(configs.get(Config.ProjectInviteRequired.key())); _invitationTimeOut = Long.valueOf(configs.get(Config.ProjectInvitationExpirationTime.key()))*1000; _allowUserToCreateProject = Boolean.valueOf(configs.get(Config.AllowUserToCreateProject.key())); - - + + // set up the email system for project invitations String smtpHost = configs.get("project.smtp.host"); @@ -153,13 +150,13 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _emailInvite = new EmailInvite(smtpHost, smtpPort, useAuth, smtpUsername, smtpPassword, emailSender, smtpDebug); _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Project-ExpireInvitations")); - + return true; } - + @Override public boolean start() { - _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); + _executor.scheduleWithFixedDelay(new ExpiredInvitationsCleanup(), _projectCleanupExpInvInterval, _projectCleanupExpInvInterval, TimeUnit.SECONDS); return true; } @@ -172,99 +169,99 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ public String getName() { return _name; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", create=true) @DB public Project createProject(String name, String displayText, String accountName, Long domainId) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); Account owner = caller; - + //check if the user authorized to create the project if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL && !_allowUserToCreateProject) { - throw new PermissionDeniedException("Regular user is not permitted to create a project"); + throw new PermissionDeniedException("Regular user is not permitted to create a project"); } - + //Verify request parameters if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { throw new InvalidParameterValueException("Account name and domain id must be specified together"); } - + if (accountName != null) { owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null); } - + //don't allow 2 projects with the same name inside the same domain if (_projectDao.findByNameAndDomain(name, owner.getDomainId()) != null) { throw new InvalidParameterValueException("Project with name " + name + " already exists in domain id=" + owner.getDomainId()); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(owner, ResourceType.project); - + Transaction txn = Transaction.currentTxn(); txn.start(); - + //Create an account associated with the project StringBuilder acctNm = new StringBuilder("PrjAcct-"); acctNm.append(name).append("-").append(owner.getDomainId()); - + Account projectAccount = _accountMgr.createAccount(acctNm.toString(), Account.ACCOUNT_TYPE_PROJECT, domainId, null, null); - + Project project = _projectDao.persist(new ProjectVO(name, displayText, owner.getDomainId(), projectAccount.getId())); - + //assign owner to the project assignAccountToProject(project, owner.getId(), ProjectAccount.Role.Admin); - + if (project != null) { UserContext.current().setEventDetails("Project id=" + project.getId()); } - + //Increment resource count _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.project); - + txn.commit(); - + return project; } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_CREATE, eventDescription = "creating project", async=true) @DB public Project enableProject(long projectId){ Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //at this point enabling project doesn't require anything, so just update the state project.setState(State.Active); _projectDao.update(projectId, project); - + return project; } - - + + @Override - @ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true) + @ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true) public boolean deleteProject(long projectId) { UserContext ctx = UserContext.current(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); } - + _accountMgr.checkAccess(ctx.getCaller(),AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - - return deleteProject(ctx.getCaller(), ctx.getCallerUserId(), project); + + return deleteProject(ctx.getCaller(), ctx.getCallerUserId(), project); } @DB @@ -280,10 +277,10 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ Account projectOwner = getProjectOwner(project.getId()); if (projectOwner != null) { _resourceLimitMgr.decrementResourceCount(projectOwner.getId(), ResourceType.project); - } - + } + txn.commit(); - + if (updateResult) { //pass system caller when clenaup projects account if (!cleanupProject(project, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM)) { @@ -297,31 +294,31 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @DB private boolean cleanupProject(Project project, AccountVO caller, Long callerUserId) { - boolean result=true; + boolean result=true; //Delete project's account AccountVO account = _accountDao.findById(project.getProjectAccountId()); s_logger.debug("Deleting projects " + project + " internal account id=" + account.getId() + " as a part of project cleanup..."); - + result = result && _accountMgr.deleteAccount(account, callerUserId, caller); - + if (result) { //Unassign all users from the project - + Transaction txn = Transaction.currentTxn(); txn.start(); - + s_logger.debug("Unassigning all accounts from project " + project + " as a part of project cleanup..."); List projectAccounts = _projectAccountDao.listByProjectId(project.getId()); for (ProjectAccount projectAccount : projectAccounts) { result = result && unassignAccountFromProject(projectAccount.getProjectId(), projectAccount.getAccountId()); } - + s_logger.debug("Removing all invitations for the project " + project + " as a part of project cleanup..."); _projectInvitationDao.cleanupInvitations(project.getId()); - + txn.commit(); if (result) { s_logger.debug("Accounts are unassign successfully from project " + project + " as a part of project cleanup..."); @@ -329,10 +326,10 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { s_logger.warn("Failed to cleanup project's internal account"); } - + return result; } - + @Override public boolean unassignAccountFromProject(long projectId, long accountId) { ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); @@ -340,7 +337,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.debug("Account id=" + accountId + " is not assigned to project id=" + projectId + " so no need to unassign"); return true; } - + if ( _projectAccountDao.remove(projectAccount.getId())) { return true; } else { @@ -348,155 +345,34 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return false; } } - + @Override public ProjectVO getProject (long projectId) { return _projectDao.findById(projectId); } - + + @Override - public Pair, Integer> listProjects(Long id, String name, String displayText, String state, - String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, - boolean isRecursive, Map tags) { - Account caller = UserContext.current().getCaller(); - Long accountId = null; - String path = null; - - Filter searchFilter = new Filter(ProjectVO.class, "id", false, startIndex, pageSize); - SearchBuilder sb = _projectDao.createSearchBuilder(); - - if (_accountMgr.isAdmin(caller.getType())) { - if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system"); - } - - _accountMgr.checkAccess(caller, domain); - - if (accountName != null) { - Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); - if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = owner.getId(); - } - } - else { //domainId == null - if (accountName != null) { - throw new InvalidParameterValueException("could not find account " + accountName + " because domain is not specified"); - } - - } - } else { - if (accountName != null && !accountName.equals(caller.getAccountName())) { - throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized"); - } - - if (domainId != null && domainId.equals(caller.getDomainId())) { - throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized"); - } - - accountId = caller.getId(); - } - - if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { - accountId = caller.getId(); - } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { - DomainVO domain = _domainDao.findById(caller.getDomainId()); - path = domain.getPath(); - } - - if (path != null) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (accountId != null) { - SearchBuilder projectAccountSearch = _projectAccountDao.createSearchBuilder(); - projectAccountSearch.and("accountId", projectAccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.join("projectAccountSearch", projectAccountSearch, sb.entity().getId(), projectAccountSearch.entity().getProjectId(), JoinBuilder.JoinType.INNER); - } - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - if (id != null) { - sc.addAnd("id", Op.EQ, id); - } - - if (domainId != null && !isRecursive) { - sc.addAnd("domainId", Op.EQ, domainId); - } - - if (name != null) { - sc.addAnd("name", Op.EQ, name); - } - - if (displayText != null) { - sc.addAnd("displayText", Op.EQ, displayText); - } - - if (accountId != null) { - sc.setJoinParameters("projectAccountSearch", "accountId", accountId); - } - - if (state != null) { - sc.addAnd("state", Op.EQ, state); - } - - if (keyword != null) { - SearchCriteria ssc = _projectDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (path != null) { - sc.setJoinParameters("domainSearch", "path", path); - } - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Project.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - Pair, Integer> result = _projectDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); + public long getInvitationTimeout() { + return _invitationTimeOut; } - + + @Override public ProjectAccount assignAccountToProject(Project project, long accountId, ProjectAccount.Role accountRole) { return _projectAccountDao.persist(new ProjectAccountVO(project, accountId, accountRole)); } - + @Override @DB public boolean deleteAccountFromProject(long projectId, long accountId) { boolean success = true; Transaction txn = Transaction.currentTxn(); txn.start(); - + //remove account ProjectAccountVO projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); success = _projectAccountDao.remove(projectAccount.getId()); - + //remove all invitations for account if (success) { s_logger.debug("Removed account " + accountId + " from project " + projectId + " , cleaning up old invitations for account/project..."); @@ -505,36 +381,36 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ success = success && _projectInvitationDao.remove(invite.getId()); } } - + txn.commit(); return success; } - + @Override public Account getProjectOwner(long projectId) { ProjectAccount prAcct = _projectAccountDao.getProjectOwner(projectId); if (prAcct != null) { return _accountMgr.getAccount(prAcct.getAccountId()); } - + return null; } - + @Override public ProjectVO findByProjectAccountId(long projectAccountId) { return _projectDao.findByProjectAccountId(projectAccountId); } - + @Override public ProjectVO findByProjectAccountIdIncludingRemoved(long projectAccountId) { return _projectDao.findByProjectAccountIdIncludingRemoved(projectAccountId); } - + @Override public Project findByNameAndDomainId(String name, long domainId) { return _projectDao.findByNameAndDomain(name, domainId); } - + @Override public boolean canAccessProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project @@ -545,10 +421,10 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _accountMgr.checkAccess(caller, _domainDao.findById(owner.getDomainId())); return true; } - + return _projectAccountDao.canAccessProjectAccount(caller.getId(), accountId); } - + public boolean canModifyProjectAccount(Account caller, long accountId) { //ROOT admin always can access the project if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { @@ -560,29 +436,29 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return _projectAccountDao.canModifyProjectAccount(caller.getId(), accountId); } - + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_UPDATE, eventDescription = "updating project", async=true) public Project updateProject(long projectId, String displayText, String newOwnerName) throws ResourceAllocationException{ Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { throw new InvalidParameterValueException("Unable to find the project id=" + projectId); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + Transaction txn = Transaction.currentTxn(); txn.start(); if (displayText != null) { project.setDisplayText(displayText); _projectDao.update(projectId, project); } - + if (newOwnerName != null) { //check that the new owner exists Account futureOwnerAccount = _accountMgr.getActiveAccountByName(newOwnerName, project.getDomainId()); @@ -595,68 +471,68 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ if (futureOwner == null) { throw new InvalidParameterValueException("Account " + newOwnerName + " doesn't belong to the project. Add it to the project first and then change the project's ownership"); } - + //do resource limit check _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(futureOwnerAccount.getId()), ResourceType.project); - + //unset the role for the old owner ProjectAccountVO currentOwner = _projectAccountDao.findByProjectIdAccountId(projectId, currentOwnerAccount.getId()); currentOwner.setAccountRole(Role.Regular); _projectAccountDao.update(currentOwner.getId(), currentOwner); _resourceLimitMgr.decrementResourceCount(currentOwnerAccount.getId(), ResourceType.project); - + //set new owner futureOwner.setAccountRole(Role.Admin); _projectAccountDao.update(futureOwner.getId(), futureOwner); _resourceLimitMgr.incrementResourceCount(futureOwnerAccount.getId(), ResourceType.project); - + } else { s_logger.trace("Future owner " + newOwnerName + "is already the owner of the project id=" + projectId); } } - + txn.commit(); - + return _projectDao.findById(projectId); - + } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_ADD, eventDescription = "adding account to project", async=true) public boolean addAccountToProject(long projectId, String accountName, String email) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //User can be added to Active project only if (project.getState() != Project.State.Active) { - InvalidParameterValueException ex = new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Can't add account to the specified project id in state=" + project.getState() + " as it's no longer active"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //check that account-to-add exists Account account = null; if (accountName != null) { account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id"); - // We don't have a DomainVO object with us, so just pass the tablename "domain" manually. + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in specified domain id"); + // We don't have a DomainVO object with us, so just pass the tablename "domain" manually. ex.addProxyObject("domain", project.getDomainId(), "domainId"); throw ex; } - + //verify permissions - only project owner can assign _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account already added to the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount != null) { @@ -664,7 +540,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return true; } } - + if (_invitationRequired) { return inviteAccountToProject(project, account, email); } else { @@ -679,7 +555,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - + private boolean inviteAccountToProject(Project project, Account account, String email) { if (account != null) { if (createAccountInvitation(project, account.getId()) != null) { @@ -687,9 +563,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { s_logger.warn("Failed to generate invitation for account " + account.getAccountName() + " to project id=" + project); return false; - } + } } - + if (email != null) { //generate the token String token = generateToken(10); @@ -698,108 +574,66 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { s_logger.warn("Failed to generate invitation for email " + email + " to project id=" + project); return false; - } + } } - + return false; } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE, eventDescription = "removing account from project", async=true) public boolean deleteAccountFromProject(long projectId, String accountName) { Account caller = UserContext.current().getCaller(); - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); // Since we don't have a domainVO object, pass the table name manually. - ex.addProxyObject("domain", project.getDomainId(), "domainId"); + ex.addProxyObject("domain", project.getDomainId(), "domainId"); } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //Check if the account exists in the project ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, account.getId()); if (projectAccount == null) { InvalidParameterValueException ex = new InvalidParameterValueException("Account " + accountName + " is not assigned to the project with specified id"); // Use the projectVO object and not the projectAccount object to inject the projectId. - ex.addProxyObject(project, projectId, "projectId"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - - //can't remove the owner of the project - if (projectAccount.getAccountRole() == Role.Admin) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project"); - ex.addProxyObject(project, projectId, "projectId"); - throw ex; - } - - return deleteAccountFromProject(projectId, account.getId()); - } - - - @Override - public Pair, Integer> listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) { - Account caller = UserContext.current().getCaller(); - - //check that the project exists - Project project = getProject(projectId); - - if (project == null) { - throw new InvalidParameterValueException("Unable to find the project id=" + projectId); - } - - //verify permissions - only accounts belonging to the project can list project's account - if (!_accountMgr.isAdmin(caller.getType()) && _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) { - throw new PermissionDeniedException("Account " + caller + " is not authorized to list users of the project id=" + projectId); - } - - Filter searchFilter = new Filter(ProjectAccountVO.class, "id", false, startIndex, pageSizeVal); - SearchBuilder sb = _projectAccountDao.createSearchBuilder(); - sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ); - sb.and("projectId", sb.entity().getProjectId(), Op.EQ); - - SearchBuilder accountSearch; - if (accountName != null) { - accountSearch = _accountDao.createSearchBuilder(); - accountSearch.and("accountName", accountSearch.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - sc.setParameters("projectId", projectId); - - if (role != null) { - sc.setParameters("accountRole", role); - } - - if (accountName != null) { - sc.setJoinParameters("accountSearch", "accountName", accountName); - } - Pair, Integer> result = _projectAccountDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); + //can't remove the owner of the project + if (projectAccount.getAccountRole() == Role.Admin) { + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to delete account " + accountName + " from the project with specified id as the account is the owner of the project"); + ex.addProxyObject(project, projectId, "projectId"); + throw ex; + } + + return deleteAccountFromProject(projectId, account.getId()); } - - public ProjectInvitation createAccountInvitation(Project project, Long accountId) { + + + + + public ProjectInvitation createAccountInvitation(Project project, Long accountId) { if (activeInviteExists(project, accountId, null)) { throw new InvalidParameterValueException("There is already a pending invitation for account id=" + accountId + " to the project id=" + project); } - + ProjectInvitation invitation= _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), accountId, project.getDomainId(), null, null)); - + return invitation; } @@ -811,14 +645,14 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ ProjectInvitationVO invite = null; if (accountId != null) { invite = _projectInvitationDao.findByAccountIdProjectId(accountId, project.getId()); - } else if (email != null) { - invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); - } - + } else if (email != null) { + invite = _projectInvitationDao.findByEmailAndProjectId(email, project.getId()); + } + if (invite != null) { - if (invite.getState() == ProjectInvitation.State.Completed || + if (invite.getState() == ProjectInvitation.State.Completed || (invite.getState() == ProjectInvitation.State.Pending && _projectInvitationDao.isActive(invite.getId(), _invitationTimeOut))) { - return true; + return true; } else { if (invite.getState() == ProjectInvitation.State.Pending) { expireInvitation(invite); @@ -836,13 +670,13 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ txn.commit(); return false; } - + public ProjectInvitation generateTokenBasedInvitation(Project project, String email, String token) { //verify if the invitation was already generated - if (activeInviteExists(project, null, email)) { + if (activeInviteExists(project, null, email)) { throw new InvalidParameterValueException("There is already a pending invitation for email " + email + " to the project id=" + project); } - + ProjectInvitation projectInvitation = _projectInvitationDao.persist(new ProjectInvitationVO(project.getId(), null, project.getDomainId(), email, token)); try { _emailInvite.sendInvite(token, email, project.getId()); @@ -851,96 +685,52 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ _projectInvitationDao.remove(projectInvitation.getId()); return null; } - + return projectInvitation; } - + private boolean expireInvitation(ProjectInvitationVO invite) { s_logger.debug("Expiring invitation id=" + invite.getId()); invite.setState(ProjectInvitation.State.Expired); return _projectInvitationDao.update(invite.getId(), invite); } - - @Override - public Pair, Integer> listProjectInvitations(Long id, Long projectId, - String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, boolean listAll) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true); - domainId = domainIdRecursiveListProject.first(); - isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(ProjectInvitationVO.class, "id", true, startIndex, pageSizeVal); - SearchBuilder sb = _projectInvitationDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (projectId != null){ - sc.setParameters("projectId", projectId); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (activeOnly) { - sc.setParameters("state", ProjectInvitation.State.Pending); - sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - _invitationTimeOut)); - } - - Pair, Integer> result = _projectInvitationDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); - } - @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async=true) public boolean updateInvitation(long projectId, String accountName, String token, boolean accept) { Account caller = UserContext.current().getCaller(); Long accountId = null; boolean result = true; - + //if accountname and token are null, default accountname to caller's account name if (accountName == null && token == null) { accountName = caller.getAccountName(); } - + //check that the project exists Project project = getProject(projectId); - + if (project == null) { throw new InvalidParameterValueException("Unable to find the project id=" + projectId); } - + if (accountName != null) { //check that account-to-remove exists Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId()); if (account == null) { throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId()); } - + //verify permissions _accountMgr.checkAccess(caller, null, true, account); - + accountId = account.getId(); } else { accountId = caller.getId(); } - + //check that invitation exists ProjectInvitationVO invite = null; if (token == null) { @@ -948,7 +738,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { invite = _projectInvitationDao.findPendingByTokenAndProjectId(token, projectId, ProjectInvitation.State.Pending); } - + if (invite != null) { if (!_projectInvitationDao.isActive(invite.getId(), _invitationTimeOut) && accept) { expireInvitation(invite); @@ -956,116 +746,116 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } else { Transaction txn = Transaction.currentTxn(); txn.start(); - + ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined; - + //update invitation s_logger.debug("Marking invitation " + invite + " with state " + newState); invite.setState(newState); result = _projectInvitationDao.update(invite.getId(), invite); - + if (result && accept) { //check if account already exists for the project (was added before invitation got accepted) ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountId); if (projectAccount != null) { s_logger.debug("Account " + accountName + " already added to the project id=" + projectId); } else { - assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); + assignAccountToProject(project, accountId, ProjectAccount.Role.Regular); } } else { s_logger.warn("Failed to update project invitation " + invite + " with state " + newState); } - + txn.commit(); } } else { throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId); } - + return result; } - + @Override public List listPermittedProjectAccounts(long accountId) { return _projectAccountDao.listPermittedAccountIds(accountId); } - + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACTIVATE, eventDescription = "activating project") @DB public Project activateProject(long projectId) { Account caller = UserContext.current().getCaller(); - + //check that the project exists ProjectVO project = getProject(projectId); - + if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + //verify permissions _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + //allow project activation only when it's in Suspended state Project.State currentState = project.getState(); - + if (currentState == State.Active) { s_logger.debug("The project id=" + projectId + " is already active, no need to activate it again"); return project; - } - + } + if (currentState != State.Suspended) { throw new InvalidParameterValueException("Can't activate the project in " + currentState + " state"); } - + Transaction txn = Transaction.currentTxn(); txn.start(); - + project.setState(Project.State.Active); _projectDao.update(projectId, project); - + _accountMgr.enableAccount(project.getProjectAccountId()); - + txn.commit(); - + return _projectDao.findById(projectId); } - - + + @Override @ActionEvent(eventType = EventTypes.EVENT_PROJECT_SUSPEND, eventDescription = "suspending project", async = true) public Project suspendProject (long projectId) throws ConcurrentOperationException, ResourceUnavailableException { Account caller = UserContext.current().getCaller(); - + ProjectVO project= getProject(projectId); //verify input parameters if (project == null) { InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + _accountMgr.checkAccess(caller,AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (suspendProject(project)) { s_logger.debug("Successfully suspended project id=" + projectId); return _projectDao.findById(projectId); } else { CloudRuntimeException ex = new CloudRuntimeException("Failed to suspend project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } - + } - + private boolean suspendProject(ProjectVO project) throws ConcurrentOperationException, ResourceUnavailableException { - + s_logger.debug("Marking project " + project + " with state " + State.Suspended + " as a part of project suspend..."); project.setState(State.Suspended); boolean updateResult = _projectDao.update(project.getId(), project); - + if (updateResult) { long projectAccountId = project.getProjectAccountId(); if (!_accountMgr.disableAccount(projectAccountId)) { @@ -1076,8 +866,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return true; } - - + + public static String generateToken(int length) { String charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random rand = new Random(System.currentTimeMillis()); @@ -1088,7 +878,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } return sb.toString(); } - + class EmailInvite { private Session _smtpSession; private final String _smtpHost; @@ -1138,7 +928,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } - public void sendInvite(String token, String email, long projectId) throws MessagingException, UnsupportedEncodingException { + public void sendInvite(String token, String email, long projectId) throws MessagingException, UnsupportedEncodingException { if (_smtpSession != null) { InternetAddress address = null; if (email != null) { @@ -1148,9 +938,9 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ s_logger.error("Exception creating address for: " + email, ex); } } - + String content = "You've been invited to join the CloudStack project id=" + projectId + ". Please use token " + token + " to complete registration"; - + SMTPMessage msg = new SMTPMessage(_smtpSession); msg.setSender(new InternetAddress(_emailSender, _emailSender)); msg.setFrom(new InternetAddress(_emailSender, _emailSender)); @@ -1174,36 +964,36 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } } } - - + + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_REMOVE, eventDescription = "removing project invitation", async=true) public boolean deleteProjectInvitation(long id) { Account caller = UserContext.current().getCaller(); - + ProjectInvitation invitation = _projectInvitationDao.findById(id); if (invitation == null) { throw new InvalidParameterValueException("Unable to find project invitation by id " + id); } - + //check that the project exists Project project = getProject(invitation.getProjectId()); - + //check permissions - only project owner can remove the invitations _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId())); - + if (_projectInvitationDao.remove(id)) { s_logger.debug("Project Invitation id=" + id + " is removed"); return true; } else { s_logger.debug("Failed to remove project invitation id=" + id); - return false; + return false; } } - + public class ExpiredInvitationsCleanup implements Runnable { - @Override - public void run() { + @Override + public void run() { try { TimeZone.getDefault(); List invitationsToExpire = _projectInvitationDao.listInvitationsToExpire(_invitationTimeOut); @@ -1228,7 +1018,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ @Override public boolean allowUserToCreateProject() { - return _allowUserToCreateProject; + return _allowUserToCreateProject; } - + } diff --git a/server/src/com/cloud/projects/ProjectVO.java b/server/src/com/cloud/projects/ProjectVO.java index 9a84a213da7..53947f1562d 100644 --- a/server/src/com/cloud/projects/ProjectVO.java +++ b/server/src/com/cloud/projects/ProjectVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="projects") -public class ProjectVO implements Project, Identity { +public class ProjectVO implements Project, Identity, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index 8d50886d13a..ffc09f0effe 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -30,8 +30,13 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.AddS3Cmd; -import com.cloud.api.commands.ListS3sCmd; +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; +import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd; +import org.apache.cloudstack.api.command.admin.host.*; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; import com.cloud.storage.S3; import com.cloud.storage.S3VO; import com.cloud.storage.s3.S3Manager; @@ -51,19 +56,12 @@ import com.cloud.agent.api.UpdateHostPasswordCommand; import com.cloud.agent.manager.AgentAttache; import com.cloud.agent.manager.allocator.PodAllocator; import com.cloud.agent.transport.Request; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddClusterCmd; -import com.cloud.api.commands.AddHostCmd; -import com.cloud.api.commands.AddSecondaryStorageCmd; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.CancelMaintenanceCmd; -import com.cloud.api.commands.DeleteClusterCmd; -import com.cloud.api.commands.ListSwiftsCmd; -import com.cloud.api.commands.PrepareForMaintenanceCmd; -import com.cloud.api.commands.ReconnectHostCmd; -import com.cloud.api.commands.UpdateHostCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.host.AddHostCmd; +import org.apache.cloudstack.api.command.admin.host.CancelMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostCmd; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; @@ -74,7 +72,6 @@ import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterVO; -import com.cloud.dc.ClusterVSMMapVO; import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; @@ -135,7 +132,6 @@ import com.cloud.user.UserContext; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.UriUtils; -import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; @@ -192,22 +188,22 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma @Inject protected ConfigurationDao _configDao; @Inject - protected HostTagsDao _hostTagsDao; + protected HostTagsDao _hostTagsDao; @Inject protected GuestOSCategoryDao _guestOSCategoryDao; - @Inject + @Inject protected StoragePoolDao _storagePoolDao; @Inject protected DataCenterIpAddressDao _privateIPAddressDao; @Inject protected IPAddressDao _publicIPAddressDao; @Inject - protected VirtualMachineManager _vmMgr; + protected VirtualMachineManager _vmMgr; @Inject - protected VMInstanceDao _vmDao; + protected VMInstanceDao _vmDao; @Inject protected HighAvailabilityManager _haMgr; - @Inject + @Inject protected StorageService _storageSvr; @Inject(adapter = Discoverer.class) protected Adapters _discoverers; @@ -602,7 +598,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma if (pod == null) { throw new InvalidParameterValueException("Can't find pod by id " + podId); } - // check if pod belongs to the zone + // check if pod belongs to the zone if (!Long.valueOf(pod.getDataCenterId()).equals(dcId)) { InvalidParameterValueException ex = new InvalidParameterValueException("Pod with specified podId" + podId + " doesn't belong to the zone with specified zoneId" + dcId); ex.addProxyObject(pod, podId, "podId"); @@ -664,7 +660,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod with specified podId and data center with specified dcID", e); ex.addProxyObject(pod, podId, "podId"); ex.addProxyObject(zone, dcId, "dcId"); - throw ex; + throw ex; } } clusterId = cluster.getId(); @@ -765,7 +761,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma // Verify that host exists HostVO host = _hostDao.findById(hostId); if (host == null) { - throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist"); + throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist"); } _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), host.getDataCenterId()); @@ -773,7 +769,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma * TODO: check current agent status and updateAgentStatus to removed. If it was already removed, that means * someone is deleting host concurrently, return. And consider the situation of CloudStack shutdown during delete. * A global lock? - * + * */ AgentAttache attache = _agentMgr.findAttache(hostId); // Get storage pool host mappings here because they can be removed as a part of handleDisconnect later @@ -868,7 +864,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma @DB public boolean deleteCluster(DeleteClusterCmd cmd) { Transaction txn = Transaction.currentTxn(); - try { + try { txn.start(); ClusterVO cluster = _clusterDao.lockRow(cmd.getId(), true); if (cluster == null) { @@ -994,7 +990,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma try { txn.start(); _clusterDao.update(cluster.getId(), cluster); - txn.commit(); + txn.commit(); } catch (Exception e) { s_logger.error("Unable to update cluster due to " + e.getMessage(), e); throw new CloudRuntimeException("Failed to update cluster. Please contact Cloud Support."); @@ -1010,12 +1006,12 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma cluster.setManagedState(Managed.ManagedState.PrepareUnmanaged); _clusterDao.update(cluster.getId(), cluster); txn.commit(); - List hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); + List hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); for( HostVO host : hosts ) { - if(host.getType().equals(Host.Type.Routing) && !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) + if(host.getType().equals(Host.Type.Routing) && !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) && !host.getStatus().equals(Status.Up) && !host.getStatus().equals(Status.Alert) ) { String msg = "host " + host.getPrivateIpAddress() + " should not be in " + host.getStatus().toString() + " status"; - throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg); + throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg); } } @@ -1032,9 +1028,9 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma Thread.sleep(5 * 1000); } catch (Exception e) { } - hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); + hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId()); for( HostVO host : hosts ) { - if ( !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) + if ( !host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected) && !host.getStatus().equals(Status.Alert)) { lsuccess = false; break; @@ -1046,7 +1042,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } if ( success == false ) { - throw new CloudRuntimeException("PrepareUnmanaged Failed due to some hosts are still in UP status after 5 Minutes, please try later "); + throw new CloudRuntimeException("PrepareUnmanaged Failed due to some hosts are still in UP status after 5 Minutes, please try later "); } } finally { txn.start(); @@ -1054,7 +1050,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma _clusterDao.update(cluster.getId(), cluster); txn.commit(); } - } else if( newManagedState.equals(Managed.ManagedState.Managed)) { + } else if( newManagedState.equals(Managed.ManagedState.Managed)) { txn.start(); cluster.setManagedState(Managed.ManagedState.Managed); _clusterDao.update(cluster.getId(), cluster); @@ -1180,7 +1176,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma throw new InvalidParameterValueException("There are other servers in PrepareForMaintenance OR ErrorInMaintenance STATUS in cluster " + host.getClusterId()); } - if (_storageMgr.isLocalStorageActiveOnHost(host)) { + if (_storageMgr.isLocalStorageActiveOnHost(host.getId())) { throw new InvalidParameterValueException("There are active VMs using the host's local storage pool. Please stop all VMs on this host that use local storage."); } @@ -1374,7 +1370,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma public void unregisterResourceStateAdapter(String name) { synchronized (_resourceStateAdapters) { _resourceStateAdapters.remove(name); - } + } } private Object dispatchToStateAdapters(ResourceStateAdapter.Event event, boolean singleTaker, Object... args) { @@ -1626,7 +1622,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } } - + if (s_logger.isDebugEnabled()) { new Request(-1l, -1l, cmds, true, false).logD("Startup request from directly connected host: ", true); } @@ -1667,7 +1663,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma } } } - + if (tempHost != null) { /* Change agent status to Alert */ _agentMgr.agentStatusTransitTo(tempHost, Status.Event.AgentDisconnected, _nodeId); @@ -1775,7 +1771,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma host.setCpus(ssCmd.getCpus()); host.setTotalMemory(ssCmd.getMemory()); host.setSpeed(ssCmd.getSpeed()); - host.setHypervisorType(hyType); + host.setHypervisorType(hyType); return host; } diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java index 7f446d747cb..c17b0ea83da 100755 --- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java +++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java @@ -30,7 +30,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.alert.AlertManager; import com.cloud.configuration.Config; import com.cloud.configuration.Resource; @@ -242,6 +242,36 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { return max; } + @Override + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type) { + + long max = Resource.RESOURCE_UNLIMITED; // if resource limit is not found, then we treat it as unlimited + + // No limits for Root Admin accounts + if (_accountMgr.isRootAdmin(accountType)) { + return max; + } + + + // Check if limit is configured for account + if (limit != null) { + max = limit.longValue(); + } else { + // If the account has an no limit set, then return global default account limits + Long value = null; + if (accountType == Account.ACCOUNT_TYPE_PROJECT) { + value = projectResourceLimitMap.get(type); + } else { + value = accountResourceLimitMap.get(type); + } + if (value != null) { + return value; + } + } + + return max; + } + @Override public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type) { long max = Resource.RESOURCE_UNLIMITED; diff --git a/server/src/com/cloud/secstorage/CommandExecLogVO.java b/server/src/com/cloud/secstorage/CommandExecLogVO.java index e9d7d9a2580..4ec023e4e55 100644 --- a/server/src/com/cloud/secstorage/CommandExecLogVO.java +++ b/server/src/com/cloud/secstorage/CommandExecLogVO.java @@ -28,10 +28,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.DateUtil; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="cmd_exec_log") -public class CommandExecLogVO { +public class CommandExecLogVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index c0c29ed8eb8..5d246281630 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -70,7 +70,6 @@ import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.Script; -import com.cloud.uuididentity.dao.IdentityDao; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @@ -103,7 +102,6 @@ public class ConfigurationServerImpl implements ConfigurationServer { private final AccountDao _accountDao; private final ResourceCountDao _resourceCountDao; private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao; - private final IdentityDao _identityDao; public ConfigurationServerImpl() { ComponentLocator locator = ComponentLocator.getLocator(Name); @@ -120,7 +118,6 @@ public class ConfigurationServerImpl implements ConfigurationServer { _accountDao = locator.getDao(AccountDao.class); _resourceCountDao = locator.getDao(ResourceCountDao.class); _ntwkOfferingServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class); - _identityDao = locator.getDao(IdentityDao.class); } @Override @@ -254,12 +251,14 @@ public class ConfigurationServerImpl implements ConfigurationServer { // Update the cloud identifier updateCloudIdentifier(); - updateUuids(); + // We should not update seed data UUID column here since this will be invoked in upgrade case as well. + //updateUuids(); // Set init to true _configDao.update("init", "Hidden", "true"); } + /* private void updateUuids() { _identityDao.initializeDefaultUuid("disk_offering"); _identityDao.initializeDefaultUuid("network_offerings"); @@ -281,6 +280,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _identityDao.initializeDefaultUuid("user_ip_address"); _identityDao.initializeDefaultUuid("counter"); } + */ private String getMountParent() { return getEnvironmentProperty("mount.parent"); @@ -307,7 +307,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { @DB protected void saveUser() { // insert system account - String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')"; + String insertSql = "INSERT INTO `cloud`.`account` (id, uuid, account_name, type, domain_id) VALUES (1, UUID(), 'system', '1', '1')"; Transaction txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -315,8 +315,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { } catch (SQLException ex) { } // insert system user - insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created)" + - " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())"; + insertSql = "INSERT INTO `cloud`.`user` (id, uuid, username, password, account_id, firstname, lastname, created)" + + " VALUES (1, UUID(), 'system', RAND(), 1, 'system', 'cloud', now())"; txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -332,7 +332,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String lastname = "cloud"; // create an account for the admin user first - insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')"; + insertSql = "INSERT INTO `cloud`.`account` (id, uuid, account_name, type, domain_id) VALUES (" + id + ", UUID(), '" + username + "', '1', '1')"; txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -341,8 +341,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { } // now insert the user - insertSql = "INSERT INTO `cloud`.`user` (id, username, account_id, firstname, lastname, created, state) " + - "VALUES (" + id + ",'" + username + "', 2, '" + firstname + "','" + lastname + "',now(), 'disabled')"; + insertSql = "INSERT INTO `cloud`.`user` (id, uuid, username, account_id, firstname, lastname, created, state) " + + "VALUES (" + id + ", UUID(), '" + username + "', 2, '" + firstname + "','" + lastname + "',now(), 'disabled')"; txn = Transaction.currentTxn(); try { @@ -368,8 +368,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { if (!rs.next()) { // save default security group if (tableName.equals("security_group")) { - insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " + - "VALUES ('default', 'Default Security Group', 2, 1)"; + insertSql = "INSERT INTO " + tableName + " (uuid, name, description, account_id, domain_id) " + + "VALUES (UUID(), 'default', 'Default Security Group', 2, 1)"; } else { insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " + "VALUES ('default', 'Default Security Group', 2, 1, 'admin')"; @@ -548,7 +548,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { String username = System.getProperty("user.name"); Boolean devel = Boolean.valueOf(_configDao.getValue("developer")); - if (!username.equalsIgnoreCase("cloud") || !devel) { + if (!username.equalsIgnoreCase("cloud") && !devel) { s_logger.warn("Systemvm keypairs could not be set. Management server should be run as cloud user, or in development mode."); return; } @@ -842,16 +842,16 @@ public class ConfigurationServerImpl implements ConfigurationServer { @DB protected void createDefaultNetworkOfferings() { - NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, + NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public, true); publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering); - NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, + NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, TrafficType.Management, false); managementNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(managementNetworkOffering); - NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, + NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, TrafficType.Control, false); controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering); - NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, + NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage, true); storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering); NetworkOfferingVO privateGatewayNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPrivateGatewayNetworkOffering, GuestType.Isolated); @@ -971,7 +971,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, false, true, null, null, true, Availability.Optional, - null, Network.GuestType.Shared, true, false, false, false, true, true, true, true); + null, Network.GuestType.Shared, true, false, false, false, true, true, true, false); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering); diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index 91f82f874d5..29c76e051c5 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -25,11 +25,12 @@ import com.cloud.info.ConsoleProxyInfo; import com.cloud.storage.GuestOSVO; import com.cloud.storage.StoragePoolVO; import com.cloud.utils.Pair; +import com.cloud.utils.component.PluggableService; import com.cloud.vm.VirtualMachine; /** */ -public interface ManagementServer extends ManagementService { +public interface ManagementServer extends ManagementService, PluggableService { /** * returns the instance id of this management server. @@ -43,8 +44,6 @@ public interface ManagementServer extends ManagementService { */ @Override String getVersion(); - - String[] getApiConfig(); /** * Retrieves a host by id diff --git a/server/src/com/cloud/server/ManagementServerExt.java b/server/src/com/cloud/server/ManagementServerExt.java index 0804e4fe05f..4e506a3bc4a 100644 --- a/server/src/com/cloud/server/ManagementServerExt.java +++ b/server/src/com/cloud/server/ManagementServerExt.java @@ -21,7 +21,7 @@ import java.util.TimeZone; import com.cloud.api.commands.GenerateUsageRecordsCmd; import com.cloud.api.commands.GetUsageRecordsCmd; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.usage.UsageVO; public interface ManagementServerExt extends ManagementServer { /** diff --git a/server/src/com/cloud/server/ManagementServerExtImpl.java b/server/src/com/cloud/server/ManagementServerExtImpl.java index 992d006e37d..c8c188b38ad 100644 --- a/server/src/com/cloud/server/ManagementServerExtImpl.java +++ b/server/src/com/cloud/server/ManagementServerExtImpl.java @@ -29,7 +29,8 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.projects.Project; -import com.cloud.server.api.response.UsageTypeResponse; +import com.cloud.utils.PropertiesUtil; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.usage.UsageJobVO; import com.cloud.usage.UsageTypes; import com.cloud.usage.UsageVO; @@ -206,8 +207,9 @@ public class ManagementServerExtImpl extends ManagementServerImpl implements Man } @Override - public String[] getApiConfig() { - return new String[] { "commands.properties", "commands-ext.properties" }; + public List> getCommands() { + //TODO: Add api cmd classes + return null; } private Date computeAdjustedTime(Date initialDate, TimeZone targetTZ, boolean adjustToDayStart) { diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 500c067fbb7..4efae630f36 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -42,10 +42,32 @@ import java.util.concurrent.TimeUnit; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; +import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; +import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; +import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.DestroySystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; +import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; +import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; +import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; +import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; @@ -56,49 +78,25 @@ import com.cloud.alert.Alert; import com.cloud.alert.AlertManager; import com.cloud.alert.AlertVO; import com.cloud.alert.dao.AlertDao; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CreateSSHKeyPairCmd; -import com.cloud.api.commands.DeleteSSHKeyPairCmd; -import com.cloud.api.commands.DestroySystemVmCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.commands.GetVMPasswordCmd; -import com.cloud.api.commands.ListAlertsCmd; -import com.cloud.api.commands.ListAsyncJobsCmd; -import com.cloud.api.commands.ListCapabilitiesCmd; -import com.cloud.api.commands.ListCapacityCmd; -import com.cloud.api.commands.ListCfgsByCmd; -import com.cloud.api.commands.ListClustersCmd; -import com.cloud.api.commands.ListDiskOfferingsCmd; -import com.cloud.api.commands.ListEventsCmd; -import com.cloud.api.commands.ListGuestOsCategoriesCmd; -import com.cloud.api.commands.ListGuestOsCmd; -import com.cloud.api.commands.ListHostsCmd; -import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListPodsByCmd; -import com.cloud.api.commands.ListPublicIpAddressesCmd; -import com.cloud.api.commands.ListRoutersCmd; -import com.cloud.api.commands.ListSSHKeyPairsCmd; -import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListStoragePoolsCmd; -import com.cloud.api.commands.ListSystemVMsCmd; -import com.cloud.api.commands.ListTemplatesCmd; -import com.cloud.api.commands.ListVMGroupsCmd; -import com.cloud.api.commands.ListVlanIpRangesCmd; -import com.cloud.api.commands.ListZonesByCmd; -import com.cloud.api.commands.RebootSystemVmCmd; -import com.cloud.api.commands.RegisterSSHKeyPairCmd; -import com.cloud.api.commands.StopSystemVmCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; -import com.cloud.api.commands.UpdateIsoCmd; -import com.cloud.api.commands.UpdateTemplateCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoCmd; -import com.cloud.api.commands.UpdateVMGroupCmd; -import com.cloud.api.commands.UpgradeSystemVMCmd; -import com.cloud.api.commands.UploadCustomCertificateCmd; -import com.cloud.api.response.ExtractResponse; -import com.cloud.async.AsyncJob; +import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; +import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; +import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; +import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; +import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; +import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; + +import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; +import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; +import org.apache.cloudstack.api.response.ExtractResponse; + import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; @@ -140,6 +138,7 @@ import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; +import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -169,7 +168,6 @@ import com.cloud.network.NetworkVO; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.NetworkDao; -import com.cloud.network.router.VirtualRouter; import com.cloud.org.Cluster; import com.cloud.org.Grouping.AllocationState; import com.cloud.projects.Project; @@ -213,11 +211,9 @@ import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; import com.cloud.user.SSHKeyPair; import com.cloud.user.SSHKeyPairVO; import com.cloud.user.User; -import com.cloud.user.UserAccount; import com.cloud.user.UserContext; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; @@ -227,6 +223,7 @@ import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; +import com.cloud.utils.PropertiesUtil; import com.cloud.utils.Ternary; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; @@ -247,9 +244,7 @@ import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SSHKeysHelper; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.InstanceGroup; import com.cloud.vm.InstanceGroupVO; -import com.cloud.vm.NicVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; @@ -277,10 +272,12 @@ public class ManagementServerImpl implements ManagementServer { private final AlertManager _alertMgr; private final IPAddressDao _publicIpAddressDao; private final DomainRouterDao _routerDao; + private final DomainRouterJoinDao _routerJoinDao; private final ConsoleProxyDao _consoleProxyDao; private final ClusterDao _clusterDao; private final SecondaryStorageVmDao _secStorageVmDao; private final EventDao _eventDao; + private final EventJoinDao _eventJoinDao; private final DataCenterDao _dcDao; private final VlanDao _vlanDao; private final AccountVlanMapDao _accountVlanMapDao; @@ -315,6 +312,7 @@ public class ManagementServerImpl implements ManagementServer { private final AsyncJobManager _asyncMgr; private final int _purgeDelay; private final InstanceGroupDao _vmGroupDao; + private final InstanceGroupJoinDao _vmGroupJoinDao; private final UploadMonitor _uploadMonitor; private final UploadDao _uploadDao; private final SSHKeyPairDao _sshKeyPairDao; @@ -323,7 +321,7 @@ public class ManagementServerImpl implements ManagementServer { private final Adapters _hostAllocators; private final ConfigurationManager _configMgr; private final ResourceTagDao _resourceTagDao; - + @Inject ProjectManager _projectMgr; private final ResourceManager _resourceMgr; @@ -343,7 +341,7 @@ public class ManagementServerImpl implements ManagementServer { private final StatsCollector _statsCollector; private final Map _availableIdsMap; - + private Adapters _userAuthenticators; private String _hashKey = null; @@ -352,7 +350,9 @@ public class ManagementServerImpl implements ManagementServer { ComponentLocator locator = ComponentLocator.getLocator(Name); _configDao = locator.getDao(ConfigurationDao.class); _routerDao = locator.getDao(DomainRouterDao.class); + _routerJoinDao = locator.getDao(DomainRouterJoinDao.class); _eventDao = locator.getDao(EventDao.class); + _eventJoinDao = locator.getDao(EventJoinDao.class); _dcDao = locator.getDao(DataCenterDao.class); _vlanDao = locator.getDao(VlanDao.class); _accountVlanMapDao = locator.getDao(AccountVlanMapDao.class); @@ -390,6 +390,7 @@ public class ManagementServerImpl implements ManagementServer { _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _poolDao = locator.getDao(StoragePoolDao.class); _vmGroupDao = locator.getDao(InstanceGroupDao.class); + _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); _uploadDao = locator.getDao(UploadDao.class); _configs = _configDao.getConfiguration(); _vmInstanceDao = locator.getDao(VMInstanceDao.class); @@ -425,7 +426,7 @@ public class ManagementServerImpl implements ManagementServer { for (String id : availableIds) { _availableIdsMap.put(id, true); } - + _userAuthenticators = locator.getAdapters(UserAuthenticator.class); if (_userAuthenticators == null || !_userAuthenticators.isSet()) { s_logger.error("Unable to find an user authenticator."); @@ -451,8 +452,10 @@ public class ManagementServerImpl implements ManagementServer { String keyword = cmd.getKeyword(); if (domainId != null) { // for domainId != null - // right now, we made the decision to only list zones associated with this domain - dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private zones + // right now, we made the decision to only list zones associated + // with this domain + dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private + // zones } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { if (keyword != null) { dcs = _dcDao.findByKeyword(keyword); @@ -460,7 +463,8 @@ public class ManagementServerImpl implements ManagementServer { dcs = _dcDao.listAll(); // all zones } } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { - // it was decided to return all zones for the user's domain, and everything above till root + // it was decided to return all zones for the user's domain, and + // everything above till root // list all zones belonging to this domain, and all of its parents // check the parent, if not null, add zones for that parent to list dcs = new ArrayList(); @@ -479,7 +483,8 @@ public class ManagementServerImpl implements ManagementServer { dcs.addAll(_dcDao.listPublicZones(keyword)); removeDisabledZones = true; } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - // it was decided to return all zones for the domain admin, and everything above till root + // it was decided to return all zones for the domain admin, and + // everything above till root dcs = new ArrayList(); DomainVO domainRecord = _domainDao.findById(account.getDomainId()); // this covers path till root @@ -496,7 +501,8 @@ public class ManagementServerImpl implements ManagementServer { } // this covers till leaf if (domainRecord != null) { - // find all children for this domain based on a like search by path + // find all children for this domain based on a like search by + // path List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); List allChildDomainIds = new ArrayList(); // create list of domainIds for search @@ -569,11 +575,14 @@ public class ManagementServerImpl implements ManagementServer { throw new InvalidParameterValueException("privatePort is an invalid value"); } - // s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " + + // s_logger.debug("Checking if " + privateIp + + // " is a valid private IP address. Guest IP address is: " + // _configs.get("guest.ip.network")); // - // if (!NetUtils.isValidPrivateIp(privateIp, _configs.get("guest.ip.network"))) { - // throw new InvalidParameterValueException("Invalid private ip address"); + // if (!NetUtils.isValidPrivateIp(privateIp, + // _configs.get("guest.ip.network"))) { + // throw new + // InvalidParameterValueException("Invalid private ip address"); // } if (!NetUtils.isValidProto(proto)) { throw new InvalidParameterValueException("Invalid protocol"); @@ -622,7 +631,8 @@ public class ManagementServerImpl implements ManagementServer { return cal.getTime(); } - // This method is used for permissions check for both disk and service offerings + // This method is used for permissions check for both disk and service + // offerings private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { if (accountDomainId == offeringDomainId) { @@ -653,11 +663,13 @@ public class ManagementServerImpl implements ManagementServer { public List searchForServiceOfferings(ListServiceOfferingsCmd cmd) { // Note - // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way -// till + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till // root Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); isAscending = (isAscending == null ? true : isAscending); @@ -678,16 +690,20 @@ public class ManagementServerImpl implements ManagementServer { } // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the so associated with this domain + // if a domainId is provided, we just return the so associated with this + // domain if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - // check if the user's domain == so's domain || user's domain is a child of so's domain + // check if the user's domain == so's domain || user's domain is a + // child of so's domain if (!isPermissible(caller.getDomainId(), domainId)) { - throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering"); + throw new PermissionDeniedException("The account:" + caller.getAccountName() + + " does not fall in the same domain hierarchy as the service offering"); } } // For non-root users - if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { if (isSystem) { throw new InvalidParameterValueException("Only root admins can access system's offering"); } @@ -708,8 +724,8 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(vmInstance, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); + ex.addProxyObject(vmInstance, vmId, "vmId"); throw ex; } @@ -718,8 +734,10 @@ public class ManagementServerImpl implements ManagementServer { ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - // Only return offerings with the same Guest IP type and storage pool preference - // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, offering.getGuestIpType()); + // Only return offerings with the same Guest IP type and storage + // pool preference + // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, + // offering.getGuestIpType()); sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); } if (id != null) { @@ -742,16 +760,17 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("vm_type", SearchCriteria.Op.EQ, vmTypeStr); } - sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem); sc.addAnd("removed", SearchCriteria.Op.NULL); return _offeringsDao.search(sc, searchFilter); } - private List searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, Filter searchFilter) { + private List searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, + Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user -// or + // it was decided to return all offerings for the user's domain, and + // everything above till root (for normal user + // or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -780,11 +799,11 @@ public class ManagementServerImpl implements ManagementServer { } else if (vmId != null) { UserVmVO vmInstance = _userVmDao.findById(vmId); if ((vmInstance == null) || (vmInstance.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); - ex.addProxyObject(vmInstance, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); + ex.addProxyObject(vmInstance, vmId, "vmId"); throw ex; } - + _accountMgr.checkAccess(caller, null, false, vmInstance); ServiceOfferingVO offering = _offeringsDao.findById(vmInstance.getServiceOfferingId()); @@ -827,20 +846,20 @@ public class ManagementServerImpl implements ManagementServer { return sol; } - + @Override public List searchForClusters(long zoneId, Long startIndex, Long pageSizeVal, String hypervisorType) { - Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); - SearchCriteria sc = _clusterDao.createSearchCriteria(); - - zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + Filter searchFilter = new Filter(ClusterVO.class, "id", true, startIndex, pageSizeVal); + SearchCriteria sc = _clusterDao.createSearchCriteria(); - sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); - sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); - - return _clusterDao.search(sc, searchFilter); + zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId); + + sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); + sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hypervisorType); + + return _clusterDao.search(sc, searchFilter); } - + @Override public Pair, Integer> searchForClusters(ListClustersCmd cmd) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -896,22 +915,6 @@ public class ManagementServerImpl implements ManagementServer { return new Pair, Integer>(result.first(), result.second()); } - @Override - public List searchForServers(ListHostsCmd cmd) { - - Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); - Object name = cmd.getHostName(); - Object type = cmd.getType(); - Object state = cmd.getState(); - Object pod = cmd.getPodId(); - Object cluster = cmd.getClusterId(); - Object id = cmd.getId(); - Object keyword = cmd.getKeyword(); - Object resourceState = cmd.getResourceState(); - Object haHosts = cmd.getHaHost(); - - return searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState, haHosts); - } @Override public Pair, List> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) { @@ -926,8 +929,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO vm = _vmInstanceDao.findById(vmId); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); - ex.addProxyObject(vm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with specified id"); + ex.addProxyObject(vm, vmId, "vmId"); throw ex; } // business logic @@ -940,8 +943,8 @@ public class ManagementServerImpl implements ManagementServer { throw ex; } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) - && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) + && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is not XenServer/VMware/KVM/OVM, cannot migrate this VM."); } @@ -961,8 +964,9 @@ public class ManagementServerImpl implements ManagementServer { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm); } - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id"); - ex.addProxyObject(srcHost, srcHostId, "hostId"); + InvalidParameterValueException ex = new InvalidParameterValueException( + "Unable to find the host (with specified id) of VM with specified id"); + ex.addProxyObject(srcHost, srcHostId, "hostId"); ex.addProxyObject(vm, vmId, "vmId"); throw ex; } @@ -972,7 +976,8 @@ public class ManagementServerImpl implements ManagementServer { s_logger.debug("Searching for all hosts in cluster: " + cluster + " for migrating VM " + vm); } - List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, null); + List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, + null); // filter out the current host allHostsInCluster.remove(srcHost); @@ -1011,10 +1016,10 @@ public class ManagementServerImpl implements ManagementServer { return new Pair, List>(allHostsInCluster, suitableHosts); } - private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, - Object resourceState, Object haHosts) { + private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, + Object cluster, Object id, Object keyword, Object resourceState, Object haHosts) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); - + SearchBuilder sb = _hostDao.createSearchBuilder(); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); @@ -1024,12 +1029,12 @@ public class ManagementServerImpl implements ManagementServer { sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); - + String haTag = _haMgr.getHaTag(); SearchBuilder hostTagSearch = null; if (haHosts != null && haTag != null && !haTag.isEmpty()) { hostTagSearch = _hostTagsDao.createSearchBuilder(); - if ((Boolean)haHosts) { + if ((Boolean) haHosts) { hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.EQ); } else { hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.NEQ); @@ -1037,9 +1042,9 @@ public class ManagementServerImpl implements ManagementServer { } hostTagSearch.cp(); - sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); + sb.join("hostTagSearch", hostTagSearch, sb.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); } - + SearchCriteria sc = sb.create(); if (keyword != null) { @@ -1077,7 +1082,7 @@ public class ManagementServerImpl implements ManagementServer { if (resourceState != null) { sc.setParameters("resourceState", resourceState); } - + if (haHosts != null && haTag != null && !haTag.isEmpty()) { sc.setJoinParameters("hostTagSearch", "tag", haTag); } @@ -1122,7 +1127,7 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState); } - Pair, Integer> result = _hostPodDao.searchAndCount(sc, searchFilter); + Pair, Integer> result = _hostPodDao.searchAndCount(sc, searchFilter); return new Pair, Integer>(result.first(), result.second()); } @@ -1144,8 +1149,10 @@ public class ManagementServerImpl implements ManagementServer { } Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); - // Since we don't have a DomainVO object here, we directly set tablename to "domain". + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + + " in specified domain"); + // Since we don't have a DomainVO object here, we directly set + // tablename to "domain". String tablename = "domain"; ex.addProxyObject(tablename, domainId, "domainId"); throw ex; @@ -1166,8 +1173,8 @@ public class ManagementServerImpl implements ManagementServer { if (projectId != null) { Project project = _projectMgr.getProject(projectId); if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId); + ex.addProxyObject(project, projectId, "projectId"); throw ex; } accountId = project.getProjectAccountId(); @@ -1193,7 +1200,8 @@ public class ManagementServerImpl implements ManagementServer { if (accountId != null) { SearchBuilder accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder(); accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); + sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), + JoinBuilder.JoinType.INNER); } if (podId != null) { @@ -1295,8 +1303,10 @@ public class ManagementServerImpl implements ManagementServer { listAll = true; } List permittedAccountIds = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, + domainIdRecursiveListProject, listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); @@ -1305,8 +1315,9 @@ public class ManagementServerImpl implements ManagementServer { } HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, - cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), + cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, + listProjectResourcesCriteria, tags); } @Override @@ -1315,7 +1326,7 @@ public class ManagementServerImpl implements ManagementServer { Long id = cmd.getId(); Map tags = cmd.getTags(); Account caller = UserContext.current().getCaller(); - + boolean listAll = false; if (templateFilter != null && templateFilter == TemplateFilter.all) { if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { @@ -1323,10 +1334,12 @@ public class ManagementServerImpl implements ManagementServer { } listAll = true; } - + List permittedAccountIds = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, + listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); for (Long accountId : permittedAccountIds) { @@ -1336,15 +1349,13 @@ public class ManagementServerImpl implements ManagementServer { boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured)); HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, - cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr, - cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(), + cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); } - private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, - boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, - boolean showDomr, boolean onlyReady, List permittedAccounts, Account caller, - ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, + Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, + List permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { VMTemplateVO template = null; if (templateId != null) { @@ -1360,7 +1371,8 @@ public class ManagementServerImpl implements ManagementServer { }// If ISO not requested then it shouldn't be an ISO. if (!isIso && template.getFormat() == ImageFormat.ISO) { s_logger.error("Incorrect format of the template id " + templateId); - InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id"); + InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + + " of the specified template id"); ex.addProxyObject(template, templateId, "templateId"); throw ex; } @@ -1380,14 +1392,12 @@ public class ManagementServerImpl implements ManagementServer { Set> templateZonePairSet = new HashSet>(); if (_swiftMgr.isSwiftEnabled()) { if (template == null) { - templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, - hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, - permittedAccounts, caller, tags); + templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, tags); Set> templateZonePairSet2 = new HashSet>(); - templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, - bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, - permittedAccounts, caller, listProjectResourcesCriteria, tags); - + templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); + for (Pair tmpltPair : templateZonePairSet2) { if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { templateZonePairSet.add(tmpltPair); @@ -1404,14 +1414,14 @@ public class ManagementServerImpl implements ManagementServer { } } else if (_s3Mgr.isS3Enabled()) { if (template == null) { - templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, + templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, tags); Set> templateZonePairSet2 = new HashSet>(); - templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, + templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); - + for (Pair tmpltPair : templateZonePairSet2) { if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { templateZonePairSet.add(tmpltPair); @@ -1427,9 +1437,8 @@ public class ManagementServerImpl implements ManagementServer { } } else { if (template == null) { - templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, - bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, - permittedAccounts, caller, listProjectResourcesCriteria, tags); + templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); } else { // if template is not public, perform permission check here if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { @@ -1453,7 +1462,7 @@ public class ManagementServerImpl implements ManagementServer { return updateTemplateOrIso(cmd); } - private VMTemplateVO updateTemplateOrIso(UpdateTemplateOrIsoCmd cmd) { + private VMTemplateVO updateTemplateOrIso(BaseUpdateTemplateOrIsoCmd cmd) { Long id = cmd.getId(); String name = cmd.getTemplateName(); String displayText = cmd.getDisplayText(); @@ -1467,22 +1476,23 @@ public class ManagementServerImpl implements ManagementServer { // verify that template exists VMTemplateVO template = _templateDao.findById(id); if (template == null || template.getRemoved() != null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); - ex.addProxyObject(template, id, "templateId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id"); + ex.addProxyObject(template, id, "templateId"); throw ex; } // Don't allow to modify system template if (id == Long.valueOf(1)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); - ex.addProxyObject(template, id, "templateId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to update template/iso of specified id"); + ex.addProxyObject(template, id, "templateId"); throw ex; } // do a permission check _accountMgr.checkAccess(account, AccessType.ModifyEntry, true, template); - boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && sortKey == null); + boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null + && bootable == null && sortKey == null); if (!updateNeeded) { return template; } @@ -1506,7 +1516,8 @@ public class ManagementServerImpl implements ManagementServer { try { imageFormat = ImageFormat.valueOf(format.toUpperCase()); } catch (IllegalArgumentException e) { - throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + + EnumUtils.listValues(ImageFormat.values())); } template.setFormat(imageFormat); @@ -1535,231 +1546,8 @@ public class ManagementServerImpl implements ManagementServer { return _templateDao.findById(id); } - @Override - public List searchForEvents(ListEventsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - Long id = cmd.getId(); - String type = cmd.getType(); - String level = cmd.getLevel(); - Date startDate = cmd.getStartDate(); - Date endDate = cmd.getEndDate(); - String keyword = cmd.getKeyword(); - Integer entryTime = cmd.getEntryTime(); - Integer duration = cmd.getDuration(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(EventVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _eventDao.createSearchBuilder(); - - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - } - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); - sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ); - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); - sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ); - sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); - sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); - sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "accountType", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (keyword != null) { - SearchCriteria ssc = _eventDao.createSearchCriteria(); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("level", SearchCriteria.Op.SC, ssc); - } - - if (level != null) { - sc.setParameters("levelEQ", level); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (startDate != null && endDate != null) { - sc.setParameters("createDateB", startDate, endDate); - } else if (startDate != null) { - sc.setParameters("createDateG", startDate); - } else if (endDate != null) { - sc.setParameters("createDateL", endDate); - } - - if ((entryTime != null) && (duration != null)) { - if (entryTime <= duration) { - throw new InvalidParameterValueException("Entry time must be greater than duration"); - } - Calendar calMin = Calendar.getInstance(); - Calendar calMax = Calendar.getInstance(); - calMin.add(Calendar.SECOND, -entryTime); - calMax.add(Calendar.SECOND, -duration); - Date minTime = calMin.getTime(); - Date maxTime = calMax.getTime(); - - sc.setParameters("state", com.cloud.event.Event.State.Completed); - sc.setParameters("startId", 0); - sc.setParameters("createDate", minTime, maxTime); - List startedEvents = _eventDao.searchAllEvents(sc, searchFilter); - List pendingEvents = new ArrayList(); - for (EventVO event : startedEvents) { - EventVO completedEvent = _eventDao.findCompletedEvent(event.getId()); - if (completedEvent == null) { - pendingEvents.add(event); - } - } - return pendingEvents; - } else { - return _eventDao.searchAllEvents(sc, searchFilter); - } - } - - @Override - public Pair, Integer> searchForRouters(ListRoutersCmd cmd) { - Long id = cmd.getId(); - String name = cmd.getRouterName(); - String state = cmd.getState(); - Long zone = cmd.getZoneId(); - Long pod = cmd.getPodId(); - Long hostId = cmd.getHostId(); - String keyword = cmd.getKeyword(); - Long networkId = cmd.getNetworkId(); - Long vpcId = cmd.getVpcId(); - Boolean forVpc = cmd.getForVpc(); - - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(DomainRouterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _routerDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("dataCenterId", sb.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); - sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); - - if (forVpc != null) { - if (forVpc) { - sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); - } else { - sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); - } - } - - if (networkId != null) { - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - SearchBuilder networkSearch = _networkDao.createSearchBuilder(); - networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (keyword != null) { - SearchCriteria ssc = _routerDao.createSearchCriteria(); - ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (zone != null) { - sc.setParameters("dataCenterId", zone); - } - - if (pod != null) { - sc.setParameters("podId", pod); - } - - if (hostId != null) { - sc.setParameters("hostId", hostId); - } - - if (networkId != null) { - sc.setJoinParameters("nicSearch", "networkId", networkId); - } - - if (vpcId != null) { - sc.setParameters("vpcId", vpcId); - } - - Pair, Integer> result = _routerDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); - } @Override public Pair, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd) { @@ -1777,7 +1565,6 @@ public class ManagementServerImpl implements ManagementServer { Long vpcId = cmd.getVpcId(); Map tags = cmd.getTags(); - Boolean isAllocated = cmd.isAllocatedOnly(); if (isAllocated == null) { isAllocated = Boolean.TRUE; @@ -1792,15 +1579,15 @@ public class ManagementServerImpl implements ManagementServer { if (isAllocated) { Account caller = UserContext.current().getCaller(); - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), - permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, + domainIdRecursiveListProject, cmd.listAll(), false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - } + _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + } sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); sb.and("address", sb.entity().getAddress(), SearchCriteria.Op.EQ); @@ -1824,7 +1611,7 @@ public class ManagementServerImpl implements ManagementServer { if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { + for (int count = 0; count < tags.size(); count++) { tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); tagSearch.cp(); @@ -1834,7 +1621,6 @@ public class ManagementServerImpl implements ManagementServer { sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } - SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ); sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); @@ -1854,7 +1640,7 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria sc = sb.create(); if (isAllocated) { - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); } sc.setJoinParameters("vlanSearch", "vlanType", vlanType); @@ -1876,7 +1662,7 @@ public class ManagementServerImpl implements ManagementServer { if (vpcId != null) { sc.setParameters("vpcId", vpcId); } - + if (ipId != null) { sc.setParameters("id", ipId); } @@ -1930,11 +1716,11 @@ public class ManagementServerImpl implements ManagementServer { if (osCategoryId != null) { sc.addAnd("categoryId", SearchCriteria.Op.EQ, osCategoryId); } - + if (description != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + description + "%"); } - + if (keyword != null) { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1955,11 +1741,11 @@ public class ManagementServerImpl implements ManagementServer { if (id != null) { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - + if (name != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - + if (keyword != null) { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } @@ -1979,7 +1765,8 @@ public class ManagementServerImpl implements ManagementServer { } @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true) - private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, + ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -2047,11 +1834,12 @@ public class ManagementServerImpl implements ManagementServer { // check if domain exists in the system DomainVO domain = _domainDao.findById(domainId); if (domain == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); - ex.addProxyObject(domain, domainId, "domainId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id"); + ex.addProxyObject(domain, domainId, "domainId"); throw ex; } else if (domain.getParent() == null && domainName != null) { - // check if domain is ROOT domain - and deny to edit it with the new name + // check if domain is ROOT domain - and deny to edit it with the new + // name throw new InvalidParameterValueException("ROOT domain can not be edited with a new name"); } @@ -2068,9 +1856,10 @@ public class ManagementServerImpl implements ManagementServer { boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId); if (!domains.isEmpty() && !sameDomain) { - InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system"); - ex.addProxyObject(domain, domainId, "domainId"); - throw ex; + InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + + domainName + "' since it already exists in the system"); + ex.addProxyObject(domain, domainId, "domainId"); + throw ex; } } @@ -2157,7 +1946,7 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("type", SearchCriteria.Op.EQ, type); } - Pair, Integer> result =_alertDao.searchAndCount(sc, searchFilter); + Pair, Integer> result = _alertDao.searchAndCount(sc, searchFilter); return new Pair, Integer>(result.first(), result.second()); } @@ -2176,13 +1965,15 @@ public class ManagementServerImpl implements ManagementServer { List summedCapacities = new ArrayList(); if (zoneId == null && podId == null) {// Group by Zone, capacity type - List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal()); + List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, + cmd.getPageSizeVal()); if (summedCapacitiesAtZone != null) { summedCapacities.addAll(summedCapacitiesAtZone); } } if (podId == null) {// Group by Pod, capacity type - List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal()); + List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, + cmd.getPageSizeVal()); if (summedCapacitiesAtPod != null) { summedCapacities.addAll(summedCapacitiesAtPod); } @@ -2193,7 +1984,8 @@ public class ManagementServerImpl implements ManagementServer { } // Group by Cluster, capacity type - List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal()); + List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, + cmd.getPageSizeVal()); if (summedCapacitiesAtCluster != null) { summedCapacities.addAll(summedCapacitiesAtCluster); } @@ -2245,20 +2037,22 @@ public class ManagementServerImpl implements ManagementServer { } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), - capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), + capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), + capacity.getClusterId()); list.add(summedCapacity); } else { List dcList = _dcDao.listEnabledZones(); for (DataCenterVO dc : dcList) { CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId()); if (capacity.getTotalCapacity() != 0) { - capacity.setUsedPercentage((float)capacity.getUsedCapacity() / capacity.getTotalCapacity()); + capacity.setUsedPercentage((float) capacity.getUsedCapacity() / capacity.getTotalCapacity()); } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), - capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), + capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), + capacity.getClusterId()); list.add(summedCapacity); }// End of for } @@ -2285,9 +2079,8 @@ public class ManagementServerImpl implements ManagementServer { List capacities = new ArrayList(); for (SummedCapacity summedCapacity : summedCapacities) { - CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, - summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), - summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); + CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, summedCapacity.getUsedCapacity() + + summedCapacity.getReservedCapacity(), summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); if (summedCapacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { capacity.setTotalCapacity((long) (summedCapacity.getTotalCapacity() * ApiDBUtils.getCpuOverprovisioningFactor())); @@ -2295,7 +2088,8 @@ public class ManagementServerImpl implements ManagementServer { capacities.add(capacity); } - // op_host_Capacity contains only allocated stats and the real time stats are stored "in memory". + // op_host_Capacity contains only allocated stats and the real time + // stats are stored "in memory". // Show Sec. Storage only when the api is invoked for the zone layer. List dcList = new ArrayList(); if (zoneId == null && podId == null && clusterId == null) { @@ -2303,11 +2097,11 @@ public class ManagementServerImpl implements ManagementServer { } else if (zoneId != null) { dcList.add(ApiDBUtils.findZoneById(zoneId)); } else { - if (clusterId != null){ - zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); - }else{ - zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); - } + if (clusterId != null) { + zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); + } else { + zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); + } if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { capacities.add(_storageMgr.getStoragePoolUsedStats(null, clusterId, podId, zoneId)); } @@ -2334,12 +2128,14 @@ public class ManagementServerImpl implements ManagementServer { } public static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user -// or + // it was decided to return all offerings for the user's domain, and + // everything above till root (for normal user + // or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -2404,11 +2200,13 @@ public class ManagementServerImpl implements ManagementServer { @Override public List searchForDiskOfferings(ListDiskOfferingsCmd cmd) { // Note - // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way -// till + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till // root Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); @@ -2416,31 +2214,38 @@ public class ManagementServerImpl implements ManagementServer { Filter searchFilter = new Filter(DiskOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); - // SearchBuilder and SearchCriteria are now flexible so that the search builder can be built with all possible - // search terms and only those with criteria can be set. The proper SQL should be generated as a result. + // SearchBuilder and SearchCriteria are now flexible so that the search + // builder can be built with all possible + // search terms and only those with criteria can be set. The proper SQL + // should be generated as a result. Account account = UserContext.current().getCaller(); Object name = cmd.getDiskOfferingName(); Object id = cmd.getId(); Object keyword = cmd.getKeyword(); Long domainId = cmd.getDomainId(); // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the disk offering associated with this domain + // if a domainId is provided, we just return the disk offering + // associated with this domain if (domainId != null) { if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - return _diskOfferingDao.listByDomainId(domainId);// no perm check + return _diskOfferingDao.listByDomainId(domainId);// no perm + // check } else { - // check if the user's domain == do's domain || user's domain is a child of so's domain + // check if the user's domain == do's domain || user's domain is + // a child of so's domain if (isPermissible(account.getDomainId(), domainId)) { // perm check succeeded return _diskOfferingDao.listByDomainId(domainId); } else { - throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the disk offering"); + throw new PermissionDeniedException("The account:" + account.getAccountName() + + " does not fall in the same domain hierarchy as the disk offering"); } } } // For non-root users - if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter); } @@ -2449,12 +2254,16 @@ public class ManagementServerImpl implements ManagementServer { sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL); - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... /* - * sb.addAnd("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (domainId != null) { - * SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.addAnd("path", - * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, - * sb.entity().getDomainId(), domainSearch.entity().getId()); } + * sb.addAnd("domainId", sb.entity().getDomainId(), + * SearchCriteria.Op.EQ); if (domainId != null) { + * SearchBuilder domainSearch = + * _domainDao.createSearchBuilder(); domainSearch.addAnd("path", + * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); + * sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), + * domainSearch.entity().getId()); } */ SearchCriteria sc = sb.create(); @@ -2474,20 +2283,23 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("id", id); } - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... /* - * if (domainId != null) { sc.setParameters("domainId", domainId); // //DomainVO domain = - * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path - * like - * 'foo%' //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); // } + * if (domainId != null) { sc.setParameters("domainId", domainId); // + * //DomainVO domain = _domainDao.findById((Long)domainId); // // I want + * to join on user_vm.domain_id = domain.id where domain.path like + * 'foo%' //sc.setJoinParameters("domainSearch", "path", + * domain.getPath() + "%"); // } */ return _diskOfferingDao.search(sc, searchFilter); } @Override - public String[] getApiConfig() { - return new String[] { "commands.properties" }; + public List> getCommands() { + //TODO: Add cmd classes + return null; } protected class EventPurgeTask implements Runnable { @@ -2524,23 +2336,6 @@ public class ManagementServerImpl implements ManagementServer { } } - @Override - public Pair, Integer> searchForStoragePools(ListStoragePoolsCmd cmd) { - - Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); - Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); - c.addCriteria(Criteria.ID, cmd.getId()); - c.addCriteria(Criteria.NAME, cmd.getStoragePoolName()); - c.addCriteria(Criteria.CLUSTERID, cmd.getClusterId()); - c.addCriteria(Criteria.ADDRESS, cmd.getIpAddress()); - c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); - c.addCriteria(Criteria.PATH, cmd.getPath()); - c.addCriteria(Criteria.PODID, cmd.getPodId()); - c.addCriteria(Criteria.DATACENTERID, zoneId); - - Pair, Integer> result = searchForStoragePools(c); - return new Pair, Integer>(result.first(), result.second()); - } @Override public Pair, Integer> searchForStoragePools(Criteria c) { @@ -2594,80 +2389,6 @@ public class ManagementServerImpl implements ManagementServer { return _poolDao.searchAndCount(sc, searchFilter); } - @Override - public Pair, Integer> searchForAsyncJobs(ListAsyncJobsCmd cmd) { - - Account caller = UserContext.current().getCaller(); - - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _jobDao.createSearchBuilder(); - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - SearchBuilder accountSearch = null; - boolean accountJoinIsDone = false; - if (permittedAccounts.isEmpty() && domainId != null) { - accountSearch = _accountDao.createSearchBuilder(); - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("domainId", domainSearch.entity().getId(), SearchCriteria.Op.EQ); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - accountJoinIsDone = true; - accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - if (accountSearch == null) { - accountSearch = _accountDao.createSearchBuilder(); - } - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - } - - if (!accountJoinIsDone) { - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - } - - Object keyword = cmd.getKeyword(); - Object startDate = cmd.getStartDate(); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setJoinParameters("domainSearch", "domainId", domainId); - } - } - - if (keyword != null) { - sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } - - if (startDate != null) { - sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); - } - - Pair, Integer> result = _jobDao.searchAndCount(sc, searchFilter); - return new Pair, Integer> (result.first(), result.second()); - } @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { @@ -2675,7 +2396,8 @@ public class ManagementServerImpl implements ManagementServer { } @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true) - private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, + OperationTimedoutException, ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -2723,7 +2445,7 @@ public class ManagementServerImpl implements ManagementServer { sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); sb.and("nulltype", sb.entity().getType(), SearchCriteria.Op.IN); - + if (storageId != null) { SearchBuilder volumeSearch = _volumeDao.createSearchBuilder(); volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); @@ -2736,9 +2458,9 @@ public class ManagementServerImpl implements ManagementServer { SearchCriteria ssc = _vmInstanceDao.createSearchCriteria(); ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - + sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); - } + } if (id != null) { sc.setParameters("id", id); @@ -2765,7 +2487,7 @@ public class ManagementServerImpl implements ManagementServer { } else { sc.setParameters("nulltype", VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.ConsoleProxy); } - + if (storageId != null) { sc.setJoinParameters("volumeSearch", "poolId", storageId); } @@ -2778,8 +2500,8 @@ public class ManagementServerImpl implements ManagementServer { public VirtualMachine.Type findSystemVMTypeById(long instanceId) { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(instanceId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); - ex.addProxyObject(systemVm, instanceId, "instanceId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm of specified instanceId"); + ex.addProxyObject(systemVm, instanceId, "instanceId"); throw ex; } return systemVm.getType(); @@ -2790,8 +2512,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(vmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, vmId, "vmId"); throw ex; } @@ -2800,8 +2522,8 @@ public class ManagementServerImpl implements ManagementServer { } else if (systemVm.getType() == VirtualMachine.Type.SecondaryStorageVm) { return startSecondaryStorageVm(vmId); } else { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, vmId, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, vmId, "vmId"); throw ex; } } @@ -2813,8 +2535,8 @@ public class ManagementServerImpl implements ManagementServer { // verify parameters VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(id, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, id, "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, id, "vmId"); throw ex; } @@ -2835,8 +2557,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, cmd.getId(), "vmId"); throw ex; } @@ -2852,8 +2574,8 @@ public class ManagementServerImpl implements ManagementServer { VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(cmd.getId(), VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); - ex.addProxyObject(systemVm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a system vm with specified vmId"); + ex.addProxyObject(systemVm, cmd.getId(), "vmId"); throw ex; } @@ -2890,8 +2612,8 @@ public class ManagementServerImpl implements ManagementServer { // verify that user exists User user = _accountMgr.getUserIncludingRemoved(userId); if ((user == null) || (user.getRemoved() != null)) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); - ex.addProxyObject(user, userId, "userId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find active user of specified id"); + ex.addProxyObject(user, userId, "userId"); throw ex; } @@ -2939,19 +2661,20 @@ public class ManagementServerImpl implements ManagementServer { supportELB = networkType; } } - + long diskOffMaxSize = Long.valueOf(_configDao.getValue(Config.CustomDiskOfferingMaxSize.key())); String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key()); capabilities.put("securityGroupsEnabled", securityGroupsEnabled); - capabilities.put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); + capabilities + .put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); capabilities.put("cloudStackVersion", getVersion()); capabilities.put("supportELB", supportELB); capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired()); capabilities.put("allowusercreateprojects", _projectMgr.allowUserToCreateProject()); capabilities.put("customDiskOffMaxSize", diskOffMaxSize); - + return capabilities; } @@ -2976,8 +2699,8 @@ public class ManagementServerImpl implements ManagementServer { VolumeVO volume = _volumeDao.findById(volumeId); if (volume == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); - ex.addProxyObject(volume, volumeId, "volumeId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId"); + ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } @@ -2990,23 +2713,31 @@ public class ManagementServerImpl implements ManagementServer { if (volume.getPoolId() == null) { throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it"); } - // Extract activity only for detached volumes or for volumes whose instance is stopped + // Extract activity only for detached volumes or for volumes whose + // instance is stopped if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) { - s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); - PermissionDeniedException ex = new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); + s_logger.debug("Invalid state of the volume with ID: " + volumeId + + ". It should be either detached or the VM should be in stopped state."); + PermissionDeniedException ex = new PermissionDeniedException( + "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } - if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence. + if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont + // have any + // template + // dependence. VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes + if (template != null) { // For ISO based volumes template = null and + // we allow extraction of all ISO based + // volumes boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global -// admins are always allowed to extract - PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); - ex.addProxyObject(volume, volumeId, "volumeId"); + // admins are always allowed to extract + PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); + ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } } @@ -3019,7 +2750,8 @@ public class ManagementServerImpl implements ManagementServer { extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD; } - // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same. + // If mode is upload perform extra checks on url and also see if there + // is an ongoing upload on the same. if (extractMode == Upload.Mode.FTP_UPLOAD) { URI uri = new URI(url); if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) { @@ -3040,7 +2772,8 @@ public class ManagementServerImpl implements ManagementServer { } if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) { - throw new IllegalArgumentException(volume.getName() + " upload is in progress. Please wait for some time to schedule another upload for the same"); + throw new IllegalArgumentException(volume.getName() + + " upload is in progress. Please wait for some time to schedule another upload for the same"); } } @@ -3052,14 +2785,19 @@ public class ManagementServerImpl implements ManagementServer { List extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME, UploadVO.Status.DOWNLOAD_URL_CREATED); if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) { - return extractURLList.get(0).getId(); // If download url already exists then return + return extractURLList.get(0).getId(); // If download url already + // exists then return } else { - UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode); + UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, + url, extractMode); s_logger.debug("Extract Mode - " + uploadJob.getMode()); uploadJob = _uploadDao.createForUpdate(uploadJob.getId()); // Update the async Job - ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId, UploadVO.Status.COPY_IN_PROGRESS.toString(), uploadJob.getId()); + + ExtractResponse resultObj = new ExtractResponse(ApiDBUtils.findVolumeById(volumeId).getUuid(), + volume.getName(), ApiDBUtils.findAccountById(accountId).getUuid(), UploadVO.Status.COPY_IN_PROGRESS.toString(), + uploadJob.getUuid()); resultObj.setResponseName(cmd.getCommandName()); AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if (asyncExecutor != null) { @@ -3105,10 +2843,13 @@ public class ManagementServerImpl implements ManagementServer { uploadJob.setInstallPath(volumeLocalPath); _uploadDao.update(uploadJob.getId(), uploadJob); - if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is copied perform the actual uploading + if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is + // copied perform the actual + // uploading _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr); return uploadJob.getId(); - } else { // Volume is copied now make it visible under apache and create a URL. + } else { // Volume is copied now make it visible under apache and + // create a URL. _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId()); return uploadJob.getId(); } @@ -3140,8 +2881,8 @@ public class ManagementServerImpl implements ManagementServer { // Verify input parameters InstanceGroupVO group = _vmGroupDao.findById(groupId.longValue()); if (group == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); - ex.addProxyObject(group, groupId, "groupId"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a vm group with specified groupId"); + ex.addProxyObject(group, groupId, "groupId"); throw ex; } @@ -3161,77 +2902,7 @@ public class ManagementServerImpl implements ManagementServer { return _vmGroupDao.findById(groupId); } - @Override - public Pair, Integer> searchForVmGroups(ListVMGroupsCmd cmd) { - Long id = cmd.getId(); - String name = cmd.getGroupName(); - String keyword = cmd.getKeyword(); - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(InstanceGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - SearchBuilder sb = _vmGroupDao.createSearchBuilder(); - - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); - } - } - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - if (keyword != null) { - SearchCriteria ssc = _vmGroupDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - Pair, Integer> result = _vmGroupDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); - } @Override public String getVersion() { @@ -3322,7 +2993,8 @@ public class ManagementServerImpl implements ManagementServer { @Override public String getHashKey() { - // although we may have race conditioning here, database transaction serialization should + // although we may have race conditioning here, database transaction + // serialization should // give us the same key if (_hashKey == null) { _hashKey = _configDao.getValueAndInitIfNotExist(Config.HashKey.key(), Config.HashKey.getCategory(), UUID.randomUUID().toString()); @@ -3365,8 +3037,9 @@ public class ManagementServerImpl implements ManagementServer { SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); - ex.addProxyObject(owner, owner.getDomainId(), "domainId"); + InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); + ex.addProxyObject(owner, owner.getDomainId(), "domainId"); throw ex; } @@ -3381,8 +3054,10 @@ public class ManagementServerImpl implements ManagementServer { Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -3449,8 +3124,8 @@ public class ManagementServerImpl implements ManagementServer { UserVmVO vm = _userVmDao.findById(cmd.getId()); if (vm == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("No VM with specified id found."); + ex.addProxyObject(vm, cmd.getId(), "vmId"); throw ex; } @@ -3460,8 +3135,8 @@ public class ManagementServerImpl implements ManagementServer { _userVmDao.loadDetails(vm); String password = vm.getDetail("Encrypted.Password"); if (password == null || password.equals("")) { - InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); - ex.addProxyObject(vm, cmd.getId(), "vmId"); + InvalidParameterValueException ex = new InvalidParameterValueException("No password for VM with specified id found."); + ex.addProxyObject(vm, cmd.getId(), "vmId"); throw ex; } @@ -3502,13 +3177,16 @@ public class ManagementServerImpl implements ManagementServer { nvp.setValue(DBEncryptionUtil.encrypt(cmd.getPassword())); _detailsDao.persist(nvp); } else { - // if one host in the cluster has diff username then rollback to maintain consistency + // if one host in the cluster has diff username then + // rollback to maintain consistency txn.rollback(); - throw new InvalidParameterValueException("The username is not same for all hosts, please modify passwords for individual hosts."); + throw new InvalidParameterValueException( + "The username is not same for all hosts, please modify passwords for individual hosts."); } } txn.commit(); - // if hypervisor is xenserver then we update it in CitrixResourceBase + // if hypervisor is xenserver then we update it in + // CitrixResourceBase } catch (Exception e) { txn.rollback(); throw new CloudRuntimeException("Failed to update password " + e.getMessage()); @@ -3539,8 +3217,8 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public Pair, Integer> listHypervisorCapabilities(Long id, - HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal) { + public Pair, Integer> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, + Long startIndex, Long pageSizeVal) { Filter searchFilter = new Filter(HypervisorCapabilitiesVO.class, "id", true, startIndex, pageSizeVal); SearchCriteria sc = _hypervisorCapabilitiesDao.createSearchCriteria(); @@ -3558,7 +3236,7 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("hypervisorType", SearchCriteria.Op.SC, ssc); } - Pair, Integer> result = _hypervisorCapabilitiesDao.searchAndCount(sc, searchFilter); + Pair, Integer> result = _hypervisorCapabilitiesDao.searchAndCount(sc, searchFilter); return new Pair, Integer>(result.first(), result.second()); } @@ -3567,8 +3245,8 @@ public class ManagementServerImpl implements ManagementServer { HypervisorCapabilitiesVO hpvCapabilities = _hypervisorCapabilitiesDao.findById(id, true); if (hpvCapabilities == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); - ex.addProxyObject(hpvCapabilities, id, "Id"); + InvalidParameterValueException ex = new InvalidParameterValueException("unable to find the hypervisor capabilities for specified id"); + ex.addProxyObject(hpvCapabilities, id, "Id"); throw ex; } @@ -3595,27 +3273,25 @@ public class ManagementServerImpl implements ManagementServer { return null; } } - - + @Override public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { Long systemVmId = cmd.getId(); Long serviceOfferingId = cmd.getServiceOfferingId(); Account caller = UserContext.current().getCaller(); - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, - VirtualMachine.Type.SecondaryStorageVm); + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { throw new InvalidParameterValueException("Unable to find SystemVm with id " + systemVmId); } _accountMgr.checkAccess(caller, null, true, systemVm); - + // Check that the specified service offering ID is valid _itMgr.checkIfCanUpgrade(systemVm, serviceOfferingId); boolean result = _itMgr.upgradeVmDb(systemVmId, serviceOfferingId); - + if (result) { return _vmInstanceDao.findById(systemVmId); } else { @@ -3623,26 +3299,27 @@ public class ManagementServerImpl implements ManagementServer { } } - + public void enableAdminUser(String password) { String encodedPassword = null; - + UserVO adminUser = _userDao.getUser(2); if (adminUser.getState() == Account.State.disabled) { - // This means its a new account, set the password using the authenticator - - for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { - UserAuthenticator authenticator = en.nextElement(); - encodedPassword = authenticator.encode(password); - if (encodedPassword != null) { - break; - } - } - - adminUser.setPassword(encodedPassword); - adminUser.setState(Account.State.enabled); - _userDao.persist(adminUser); - s_logger.info("Admin user enabled"); + // This means its a new account, set the password using the + // authenticator + + for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { + UserAuthenticator authenticator = en.nextElement(); + encodedPassword = authenticator.encode(password); + if (encodedPassword != null) { + break; + } + } + + adminUser.setPassword(encodedPassword); + adminUser.setState(Account.State.enabled); + _userDao.persist(adminUser); + s_logger.info("Admin user enabled"); } } diff --git a/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java b/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java index 1be4c285260..355f3646a65 100644 --- a/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java +++ b/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java @@ -16,20 +16,19 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class BaremetalTemplateResponse extends BaseResponse { @SerializedName("id") @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java b/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java index cfde632b134..480107b1b9f 100644 --- a/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java +++ b/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java @@ -16,9 +16,10 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class NwDeviceDhcpResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ZONE_ID) @Param(description="Zone where to add PXE server") diff --git a/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java b/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java index 8240c9cb4a8..72063c39b7f 100644 --- a/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java +++ b/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java @@ -16,46 +16,46 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class NwDevicePxeServerResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ZONE_ID) @Param(description="Zone where to add PXE server") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.POD_ID) @Param(description="Pod where to add PXE server") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); - + private String podId; + @SerializedName(ApiConstants.URL) @Param(description="Ip of PXE server") private String url; - + @SerializedName(ApiConstants.TYPE) @Param(description="Type of add PXE server") private String type; - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - - public void setPodId(Long podId) { - this.podId.setValue(podId); + + public void setPodId(String podId) { + this.podId = podId; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - + public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } - + public void setType(String type) { this.type = type; } diff --git a/server/src/com/cloud/server/api/response/PxePingResponse.java b/server/src/com/cloud/server/api/response/PxePingResponse.java index 93d76907cc7..c37bd42774b 100644 --- a/server/src/com/cloud/server/api/response/PxePingResponse.java +++ b/server/src/com/cloud/server/api/response/PxePingResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java index 3b18f879189..441b9788108 100644 --- a/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java index d0033ab0312..56164eb7843 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java index b561b01823a..066c1c0fa2c 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class CreateVolumeOnFilerCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java index 21afec15022..0c7acfa9189 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class CreateVolumePoolCmdResponse extends BaseResponse{ } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java index d4dc5747556..b4e697b116e 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DeleteLUNCmdResponse extends BaseResponse{ } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java index 455caa00dcd..40083ec3a98 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DeleteVolumeOnFilerCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java index 4f9dc46338f..1740ddc222a 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class DeleteVolumePoolCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java index 6756b5d2c23..ce3160b699d 100644 --- a/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DissociateLunCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java index eb95c6d0a00..bd0ee3f4614 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java index ae6ef3e1237..b3f0fe31b3b 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java index 95e77b17a97..222e45c1320 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java index 33b2b788e83..fa0c069c842 100644 --- a/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ModifyVolumePoolCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/servlet/CloudStartupServlet.java b/server/src/com/cloud/servlet/CloudStartupServlet.java index 9efb4ea5a8c..484c7bf56aa 100755 --- a/server/src/com/cloud/servlet/CloudStartupServlet.java +++ b/server/src/com/cloud/servlet/CloudStartupServlet.java @@ -48,7 +48,7 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi s_locator = ComponentLocator.getLocator(ManagementServer.Name); ManagementServer ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name); ms.enableAdminUser("password"); - ApiServer.initApiServer(ms.getApiConfig()); + ApiServer.initApiServer(); } catch (InvalidParameterValueException ipve) { s_logger.error("Exception starting management server ", ipve); throw new ServletException (ipve.getMessage()); diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 7f073f1a74f..afa5c407316 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -35,7 +35,7 @@ import javax.servlet.http.HttpSession; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import com.cloud.api.IdentityService; +import org.apache.cloudstack.api.IdentityService; import com.cloud.exception.PermissionDeniedException; import com.cloud.host.HostVO; import com.cloud.server.ManagementServer; diff --git a/server/src/com/cloud/storage/StorageManager.java b/server/src/com/cloud/storage/StorageManager.java index ce00cbf4e81..97853ac76de 100755 --- a/server/src/com/cloud/storage/StorageManager.java +++ b/server/src/com/cloud/storage/StorageManager.java @@ -53,28 +53,28 @@ public interface StorageManager extends StorageService, Manager { * @return absolute ISO path */ public Pair getAbsoluteIsoPath(long templateId, long dataCenterId); - + /** * Returns the URL of the secondary storage host * @param zoneId * @return URL */ public String getSecondaryStorageURL(long zoneId); - + /** * Returns a comma separated list of tags for the specified storage pool * @param poolId * @return comma separated list of tags */ public String getStoragePoolTags(long poolId); - + /** * Returns the secondary storage host * @param zoneId * @return secondary storage host */ public HostVO getSecondaryStorageHost(long zoneId); - + /** * Returns the secondary storage host * @param zoneId @@ -89,7 +89,7 @@ public interface StorageManager extends StorageService, Manager { * @param destPoolPodId * @param destPoolClusterId * @return VolumeVO - * @throws ConcurrentOperationException + * @throws ConcurrentOperationException */ VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException; @@ -114,10 +114,10 @@ public interface StorageManager extends StorageService, Manager { /** * Marks the specified volume as destroyed in the management server database. The expunge thread will delete the volume from its storage pool. * @param volume - * @return + * @return */ boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException; - + /** Create capacity entries in the op capacity table * @param storagePool */ @@ -136,7 +136,7 @@ public interface StorageManager extends StorageService, Manager { Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException; Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Commands cmds) throws StorageUnavailableException; Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Command cmd) throws StorageUnavailableException; - + /** * Checks that one of the following is true: * 1. The volume is not attached to any VM @@ -145,21 +145,21 @@ public interface StorageManager extends StorageService, Manager { * @return true if one of the above conditions is true */ boolean volumeInactive(VolumeVO volume); - + String getVmNameOnVolume(VolumeVO volume); - + /** * Checks if a host has running VMs that are using its local storage pool. * @return true if local storage is active on the host */ - boolean isLocalStorageActiveOnHost(Host host); - + boolean isLocalStorageActiveOnHost(Long hostId); + /** * Cleans up storage pools by removing unused templates. * @param recurring - true if this cleanup is part of a recurring garbage collection thread */ void cleanupStorage(boolean recurring); - + String getPrimaryStorageNameLabel(VolumeVO volume); /** @@ -176,16 +176,16 @@ public interface StorageManager extends StorageService, Manager { */ DiskProfile allocateRawVolume(Type type, String name, DiskOfferingVO offering, Long size, T vm, Account owner); DiskProfile allocateTemplatedVolume(Type type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner); - + void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated); - + void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, ConcurrentOperationException; void release(VirtualMachineProfile profile); void cleanupVolumes(long vmId) throws ConcurrentOperationException; - + void prepareForMigration(VirtualMachineProfile vm, DeployDestination dest); Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException; @@ -217,7 +217,7 @@ public interface StorageManager extends StorageService, Manager { boolean stateTransitTo(Volume vol, Event event) throws NoTransitionException; - + VolumeVO allocateDuplicateVolume(VolumeVO oldVol, Long templateId); Host updateSecondaryStorage(long secStorageId, String newUrl); @@ -237,6 +237,6 @@ public interface StorageManager extends StorageService, Manager { HypervisorType getHypervisorTypeFromFormat(ImageFormat format); boolean storagePoolHasEnoughSpace(List volume, StoragePool pool); - + boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException; } diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 805a7039e03..07f4d8ac7cb 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -44,6 +44,10 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.storage.*; +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -66,18 +70,14 @@ import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.DeleteTemplateCommand; import com.cloud.agent.api.storage.DeleteVolumeCommand; import com.cloud.agent.api.storage.DestroyCommand; +import com.cloud.agent.api.storage.ResizeVolumeCommand; +import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; -import com.cloud.api.commands.CreateStoragePoolCmd; -import com.cloud.api.commands.CreateVolumeCmd; -import com.cloud.api.commands.DeletePoolCmd; -import com.cloud.api.commands.ListVolumesCmd; -import com.cloud.api.commands.UpdateStoragePoolCmd; -import com.cloud.api.commands.UploadVolumeCmd; +import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; import com.cloud.async.AsyncJobManager; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; @@ -129,11 +129,9 @@ import com.cloud.network.NetworkModel; import com.cloud.offering.ServiceOffering; import com.cloud.org.Grouping; import com.cloud.org.Grouping.AllocationState; -import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; import com.cloud.server.ManagementServer; -import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.StatsCollector; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; @@ -161,7 +159,6 @@ import com.cloud.storage.s3.S3Manager; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.storage.snapshot.SnapshotScheduler; -import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.TemplateManager; import com.cloud.user.Account; @@ -175,7 +172,6 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; import com.cloud.utils.UriUtils; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; @@ -183,7 +179,6 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; @@ -437,8 +432,8 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } @Override - public boolean isLocalStorageActiveOnHost(Host host) { - List storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId()); + public boolean isLocalStorageActiveOnHost(Long hostId) { + List storagePoolHostRefs = _storagePoolHostDao.listByHostId(hostId); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (storagePool.getPoolType() == StoragePoolType.LVM || storagePool.getPoolType() == StoragePoolType.EXT) { @@ -658,7 +653,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag Pair volumeDetails = createVolumeFromSnapshot(volume, snapshot); if (volumeDetails != null) { createdVolume = volumeDetails.first(); - UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(), createdVolume.getName(), + UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, createdVolume.getAccountId(), createdVolume.getDataCenterId(), createdVolume.getId(), createdVolume.getName(), createdVolume.getDiskOfferingId(), null, createdVolume.getSize()); _usageEventDao.persist(usageEvent); } @@ -744,21 +739,21 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @DB public VolumeVO copyVolumeFromSecToPrimary(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, List avoids, long size, HypervisorType hyperType) throws NoTransitionException { - + final HashSet avoidPools = new HashSet(avoids); DiskProfile dskCh = createDiskCharacteristics(volume, template, dc, diskOffering); dskCh.setHyperType(vm.getHypervisorType()); - // Find a suitable storage to create volume on + // Find a suitable storage to create volume on StoragePoolVO destPool = findStoragePool(dskCh, dc, pod, clusterId, null, vm, avoidPools); - - // Copy the volume from secondary storage to the destination storage pool + + // Copy the volume from secondary storage to the destination storage pool stateTransitTo(volume, Event.CopyRequested); VolumeHostVO volumeHostVO = _volumeHostDao.findByVolumeId(volume.getId()); HostVO secStorage = _hostDao.findById(volumeHostVO.getHostId()); String secondaryStorageURL = secStorage.getStorageUrl(); String[] volumePath = volumeHostVO.getInstallPath().split("/"); String volumeUUID = volumePath[volumePath.length - 1].split("\\.")[0]; - + CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volumeUUID, destPool, secondaryStorageURL, false, _copyvolumewait); CopyVolumeAnswer cvAnswer; try { @@ -771,23 +766,23 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (cvAnswer == null || !cvAnswer.getResult()) { stateTransitTo(volume, Event.CopyFailed); throw new CloudRuntimeException("Failed to copy the volume from secondary storage to the destination primary storage pool."); - } + } Transaction txn = Transaction.currentTxn(); - txn.start(); + txn.start(); volume.setPath(cvAnswer.getVolumePath()); volume.setFolder(destPool.getPath()); volume.setPodId(destPool.getPodId()); - volume.setPoolId(destPool.getId()); + volume.setPoolId(destPool.getId()); volume.setPodId(destPool.getPodId()); - stateTransitTo(volume, Event.CopySucceeded); + stateTransitTo(volume, Event.CopySucceeded); UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), null, volume.getSize()); _usageEventDao.persist(usageEvent); _volumeHostDao.remove(volumeHostVO.getId()); txn.commit(); return volume; - + } - + @Override @DB public VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId, ServiceOfferingVO offering, DiskOfferingVO diskOffering, @@ -982,7 +977,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag value = configDao.getValue(Config.RecreateSystemVmEnabled.key()); _recreateSystemVmEnabled = Boolean.parseBoolean(value); - + value = configDao.getValue(Config.StorageTemplateCleanupEnabled.key()); _templateCleanupEnabled = (value == null ? true : Boolean.parseBoolean(value)); @@ -1524,7 +1519,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } if(sPool.getStatus() != StoragePoolStatus.Maintenance){ s_logger.warn("Unable to delete storage id: " + id +" due to it is not in Maintenance state"); - throw new InvalidParameterValueException("Unable to delete storage due to it is not in Maintenance state, id: " + id); + throw new InvalidParameterValueException("Unable to delete storage due to it is not in Maintenance state, id: " + id); } if (sPool.getPoolType().equals(StoragePoolType.LVM) || sPool.getPoolType().equals(StoragePoolType.EXT)) { s_logger.warn("Unable to delete local storage id:" + id); @@ -1553,7 +1548,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag " for this pool"); } } - + // First get the host_id from storage_pool_host_ref for given pool id StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId()); @@ -1747,10 +1742,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return _volsDao.findById(volume.getId()); } - + /* * Upload the volume to secondary storage. - * + * */ @Override @DB @@ -1762,13 +1757,13 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag String volumeName = cmd.getVolumeName(); String url = cmd.getUrl(); String format = cmd.getFormat(); - + validateVolume(caller, ownerId, zoneId, volumeName, url, format); VolumeVO volume = persistVolume(caller, ownerId, zoneId, volumeName, url, cmd.getFormat()); _downloadMonitor.downloadVolumeToStorage(volume, zoneId, url, cmd.getChecksum(), ImageFormat.valueOf(format.toUpperCase())); - return volume; + return volume; } - + private boolean validateVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) throws ResourceAllocationException{ // permission check @@ -1776,7 +1771,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag // Check that the resource limit for volumes won't be exceeded _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.volume); - + // Verify that zone exists DataCenterVO zone = _dcDao.findById(zoneId); @@ -1788,22 +1783,22 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) { throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId); } - + if (url.toLowerCase().contains("file://")) { throw new InvalidParameterValueException("File:// type urls are currently unsupported"); } - + ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase()); if (imgfmt == null) { throw new IllegalArgumentException("Image format is incorrect " + format + ". Supported formats are " + EnumUtils.listValues(ImageFormat.values())); } - + String userSpecifiedName = volumeName; if (userSpecifiedName == null) { userSpecifiedName = getRandomVolumeName(); } if((!url.toLowerCase().endsWith("vhd"))&&(!url.toLowerCase().endsWith("vhd.zip")) - &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) + &&(!url.toLowerCase().endsWith("vhd.bz2"))&&(!url.toLowerCase().endsWith("vhd.gz")) &&(!url.toLowerCase().endsWith("qcow2"))&&(!url.toLowerCase().endsWith("qcow2.zip")) &&(!url.toLowerCase().endsWith("qcow2.bz2"))&&(!url.toLowerCase().endsWith("qcow2.gz")) &&(!url.toLowerCase().endsWith("ova"))&&(!url.toLowerCase().endsWith("ova.zip")) @@ -1811,7 +1806,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag &&(!url.toLowerCase().endsWith("img"))&&(!url.toLowerCase().endsWith("raw"))){ throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase()); } - + if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url.toLowerCase().endsWith("vhd.gz") )) || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz") )) || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url.toLowerCase().endsWith("ova.gz"))) @@ -1819,14 +1814,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase()); } validateUrl(url); - + return false; } - + private String validateUrl(String url){ try { URI uri = new URI(url); - if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") + if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) { throw new IllegalArgumentException("Unsupported scheme for url: " + url); } @@ -1847,16 +1842,16 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } catch (UnknownHostException uhe) { throw new IllegalArgumentException("Unable to resolve " + host); } - + return uri.toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } - + } - + private VolumeVO persistVolume(Account caller, long ownerId, Long zoneId, String volumeName, String url, String format) { - + Transaction txn = Transaction.currentTxn(); txn.start(); @@ -1867,7 +1862,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag volume.setAccountId(ownerId); volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId())); long diskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId(); - volume.setDiskOfferingId(diskOfferingId); + volume.setDiskOfferingId(diskOfferingId); //volume.setSize(size); volume.setInstanceId(null); volume.setUpdated(new Date()); @@ -1888,8 +1883,8 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag txn.commit(); return volume; } - - + + /* * Just allocate a volume in the database, don't send the createvolume cmd to hypervisor. The volume will be finally * created @@ -1991,7 +1986,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag * throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + * " is created from ROOT volume"); * } - * + * */ } @@ -2106,6 +2101,183 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } } + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_RESIZE, eventDescription = "resizing volume", async = true) + public VolumeVO resizeVolume(ResizeVolumeCmd cmd) { + VolumeVO volume = _volsDao.findById(cmd.getEntityId()); + Long newSize = null; + boolean shrinkOk = cmd.getShrinkOk(); + boolean success = false; + DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId()); + DiskOfferingVO newDiskOffering = null; + + newDiskOffering = _diskOfferingDao.findById(cmd.getNewDiskOfferingId()); + + /* Volumes with no hypervisor have never been assigned, and can be resized by recreating. + perhaps in the future we can just update the db entry for the volume */ + if(_volsDao.getHypervisorType(volume.getId()) == HypervisorType.None){ + throw new InvalidParameterValueException("Can't resize a volume that has never been attached, not sure which hypervisor type. Recreate volume to resize."); + } + + /* Only works for KVM/Xen for now */ + if(_volsDao.getHypervisorType(volume.getId()) != HypervisorType.KVM + && _volsDao.getHypervisorType(volume.getId()) != HypervisorType.XenServer){ + throw new InvalidParameterValueException("Cloudstack currently only supports volumes marked as KVM or XenServer hypervisor for resize"); + } + + if (volume == null) { + throw new InvalidParameterValueException("No such volume"); + } + + if (volume.getState() != Volume.State.Ready) { + throw new InvalidParameterValueException("Volume should be in ready state before attempting a resize"); + } + + if (!volume.getVolumeType().equals(Volume.Type.DATADISK)) { + throw new InvalidParameterValueException("Can only resize DATA volumes"); + } + + /* figure out whether or not a new disk offering or size parameter is required, get the correct size value */ + if (newDiskOffering == null) { + if (diskOffering.isCustomized()) { + newSize = cmd.getSize(); + + if (newSize == null) { + throw new InvalidParameterValueException("new offering is of custom size, need to specify a size"); + } + + newSize = ( newSize << 30 ); + } else { + throw new InvalidParameterValueException("current offering" + volume.getDiskOfferingId() + " cannot be resized, need to specify a disk offering"); + } + } else { + + if (newDiskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(newDiskOffering.getType())) { + throw new InvalidParameterValueException("Disk offering ID is missing or invalid"); + } + + if(diskOffering.getTags() != null) { + if(!newDiskOffering.getTags().equals(diskOffering.getTags())){ + throw new InvalidParameterValueException("Tags on new and old disk offerings must match"); + } + } else if (newDiskOffering.getTags() != null ){ + throw new InvalidParameterValueException("There are no tags on current disk offering, new disk offering needs to have no tags"); + } + + if (newDiskOffering.getDomainId() == null) { + // do nothing as offering is public + } else { + _configMgr.checkDiskOfferingAccess(UserContext.current().getCaller(), newDiskOffering); + } + + if (newDiskOffering.isCustomized()) { + newSize = cmd.getSize(); + + if (newSize == null) { + throw new InvalidParameterValueException("new offering is of custom size, need to specify a size"); + } + + newSize = ( newSize << 30 ); + } else { + newSize = newDiskOffering.getDiskSize(); + } + } + + if (newSize == null) { + throw new InvalidParameterValueException("could not detect a size parameter or fetch one from the diskofferingid parameter"); + } + + if (!validateVolumeSizeRange(newSize)) { + throw new InvalidParameterValueException("Requested size out of range"); + } + + /* does the caller have the authority to act on this volume? */ + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume); + + UserVmVO userVm = _userVmDao.findById(volume.getInstanceId()); + + StoragePool pool = _storagePoolDao.findById(volume.getPoolId()); + long currentSize = volume.getSize(); + + /* lets make certain they (think they) know what they're doing if they + want to shrink, by forcing them to provide the shrinkok parameter. This will + be checked again at the hypervisor level where we can see the actual disk size */ + if (currentSize > newSize && !shrinkOk) { + throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + + newSize + " would shrink the volume, need to sign off by supplying the shrinkok parameter with value of true"); + } + + /* get a list of hosts to send the commands to, try the system the + associated vm is running on first, then the last known place it ran. + If not attached to a userVm, we pass 'none' and resizevolume.sh is + ok with that since it only needs the vm name to live resize */ + long[] hosts = null; + String instanceName = "none"; + if (userVm != null) { + instanceName = userVm.getInstanceName(); + if(userVm.getHostId() != null) { + hosts = new long[] { userVm.getHostId() }; + } else if(userVm.getLastHostId() != null) { + hosts = new long[] { userVm.getLastHostId() }; + } + + /*Xen only works offline, SR does not support VDI.resizeOnline*/ + if(_volsDao.getHypervisorType(volume.getId()) == HypervisorType.XenServer + && ! userVm.getState().equals(State.Stopped)) { + throw new InvalidParameterValueException("VM must be stopped or disk detached in order to resize with the Xen HV"); + } + } + + try { + try { + stateTransitTo(volume, Volume.Event.ResizeRequested); + } catch (NoTransitionException etrans) { + throw new CloudRuntimeException("Unable to change volume state for resize: " + etrans.toString()); + } + + ResizeVolumeCommand resizeCmd = new ResizeVolumeCommand(volume.getPath(), new StorageFilerTO(pool), + currentSize, newSize, shrinkOk, instanceName); + ResizeVolumeAnswer answer = (ResizeVolumeAnswer) sendToPool(pool, hosts, resizeCmd); + + /* need to fetch/store new volume size in database. This value comes from + hypervisor rather than trusting that a success means we have a volume of the + size we requested */ + if (answer != null && answer.getResult()) { + long finalSize = answer.getNewSize(); + s_logger.debug("Resize: volume started at size " + currentSize + " and ended at size " + finalSize); + volume.setSize(finalSize); + if (newDiskOffering != null) { + volume.setDiskOfferingId(cmd.getNewDiskOfferingId()); + } + _volsDao.update(volume.getId(), volume); + + success = true; + return volume; + } else if (answer != null) { + s_logger.debug("Resize: returned '" + answer.getDetails() + "'"); + } + } catch (StorageUnavailableException e) { + s_logger.debug("volume failed to resize: "+e); + return null; + } finally { + if(success) { + try { + stateTransitTo(volume, Volume.Event.OperationSucceeded); + } catch (NoTransitionException etrans) { + throw new CloudRuntimeException("Failed to change volume state: " + etrans.toString()); + } + } else { + try { + stateTransitTo(volume, Volume.Event.OperationFailed); + } catch (NoTransitionException etrans) { + throw new CloudRuntimeException("Failed to change volume state: " + etrans.toString()); + } + } + } + return null; + } + @Override @DB public boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException { @@ -2196,7 +2368,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " + storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId()); } - + @Override public List getUpHostsInPool(long poolId) { SearchCriteria sc = UpHostsInPoolSearch.create(); @@ -2297,7 +2469,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.warn("Unable to destroy " + vol.getId(), e); } } - + // remove snapshots in Error state List snapshots = _snapshotDao.listAllByStatus(Snapshot.Status.Error); for (SnapshotVO snapshotVO : snapshots) { @@ -2307,7 +2479,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.warn("Unable to destroy " + snapshotVO.getId(), e); } } - + } finally { scanLock.unlock(); } @@ -2446,7 +2618,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag s_logger.warn("problem cleaning up snapshots in secondary storage " + secondaryStorageHost, e2); } } - + //CleanUp volumes on Secondary Storage. for (HostVO secondaryStorageHost : secondaryStorageHosts) { try { @@ -2474,7 +2646,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag _volumeHostDao.remove(destroyedVolumeHostVO.getId()); } } - + }catch (Exception e2) { s_logger.warn("problem cleaning up volumes in secondary storage " + secondaryStorageHost, e2); } @@ -2906,14 +3078,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM."); } - // Check that volume is completely Uploaded + // Check that volume is completely Uploaded if (volume.getState() == Volume.State.UploadOp){ VolumeHostVO volumeHost = _volumeHostDao.findByVolumeId(volume.getId()); if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ throw new InvalidParameterValueException("Please specify a volume that is not uploading"); - } + } } - + // Check that the volume is not already destroyed if (volume.getState() != Volume.State.Destroy) { if (!destroyVolume(volume)) { @@ -3273,7 +3445,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (s_logger.isDebugEnabled()) { s_logger.debug("Checking if we need to prepare " + vols.size() + " volumes for " + vm); } - + boolean recreate = _recreateSystemVmEnabled; List recreateVols = new ArrayList(vols.size()); @@ -3285,7 +3457,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } if (assignedPool == null && recreate) { assignedPool = _storagePoolDao.findById(vol.getPoolId()); - + } if (assignedPool != null || recreate) { Volume.State state = vol.getState(); @@ -3326,7 +3498,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId()); vm.addDisk(new VolumeTO(vol, pool)); } - + } } } else { @@ -3348,7 +3520,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag existingPool = _storagePoolDao.findById(vol.getPoolId()); s_logger.debug("existing pool: " + existingPool.getId()); } - + if (vol.getState() == Volume.State.Allocated || vol.getState() == Volume.State.Creating) { newVol = vol; } else { @@ -3404,12 +3576,6 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @DB protected VolumeVO switchVolume(VolumeVO existingVolume, VirtualMachineProfile vm) throws StorageUnavailableException { Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - stateTransitTo(existingVolume, Volume.Event.DestroyRequested); - } catch (NoTransitionException e) { - s_logger.debug("Unable to destroy existing volume: " + e.toString()); - } Long templateIdToUse = null; Long volTemplateId = existingVolume.getTemplateId(); @@ -3420,7 +3586,19 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } templateIdToUse = vmTemplateId; } + + txn.start(); VolumeVO newVolume = allocateDuplicateVolume(existingVolume, templateIdToUse); + // In case of Vmware if vm reference is not removed then during root disk cleanup + // the vm also gets deleted, so remove the reference + if (vm.getHypervisorType() == HypervisorType.VMware) { + _volsDao.detachVolume(existingVolume.getId()); + } + try { + stateTransitTo(existingVolume, Volume.Event.DestroyRequested); + } catch (NoTransitionException e) { + s_logger.debug("Unable to destroy existing volume: " + e.toString()); + } txn.commit(); return newVolume; @@ -3437,7 +3615,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (toBeCreated.getTemplateId() != null) { template = _templateDao.findById(toBeCreated.getTemplateId()); } - + StoragePool pool = null; if (sPool != null) { pool = sPool; @@ -3521,27 +3699,27 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag if (s_logger.isDebugEnabled()) { s_logger.debug("Expunging " + vol); } - + //Find out if the volume is present on secondary storage VolumeHostVO volumeHost = _volumeHostDao.findByVolumeId(vol.getId()); if(volumeHost != null){ if (volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED){ HostVO ssHost = _hostDao.findById(volumeHost.getHostId()); - DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(ssHost.getStorageUrl(), volumeHost.getInstallPath()); + DeleteVolumeCommand dtCommand = new DeleteVolumeCommand(ssHost.getStorageUrl(), volumeHost.getInstallPath()); Answer answer = _agentMgr.sendToSecStorage(ssHost, dtCommand); if (answer == null || !answer.getResult()) { s_logger.debug("Failed to delete " + volumeHost + " due to " + ((answer == null) ? "answer is null" : answer.getDetails())); return; } - }else if(volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ + }else if(volumeHost.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS){ s_logger.debug("Volume: " + vol.getName() + " is currently being uploaded; cant' delete it."); throw new CloudRuntimeException("Please specify a volume that is not currently being uploaded."); } _volumeHostDao.remove(volumeHost.getId()); _volumeDao.remove(vol.getId()); - return; + return; } - + String vmName = null; if (vol.getVolumeType() == Type.ROOT && vol.getInstanceId() != null) { VirtualMachine vm = _vmInstanceDao.findByIdIncludingRemoved(vol.getInstanceId()); @@ -3859,124 +4037,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return secHost; } - @Override - public Pair, Integer> searchForVolumes(ListVolumesCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - Long id = cmd.getId(); - Long vmInstanceId = cmd.getVirtualMachineId(); - String name = cmd.getVolumeName(); - String keyword = cmd.getKeyword(); - String type = cmd.getType(); - Map tags = cmd.getTags(); - - Long zoneId = cmd.getZoneId(); - Long podId = null; - // Object host = null; TODO - if (_accountMgr.isAdmin(caller.getType())) { - podId = cmd.getPodId(); - // host = cmd.getHostId(); TODO - } - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(VolumeVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - - // hack for now, this should be done better but due to needing a join I opted to - // do this quickly and worry about making it pretty later - SearchBuilder sb = _volumeDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE); - sb.and("instanceId", sb.entity().getInstanceId(), SearchCriteria.Op.EQ); - sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); - // Only return volumes that are not destroyed - sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); - - SearchBuilder diskOfferingSearch = _diskOfferingDao.createSearchBuilder(); - diskOfferingSearch.and("systemUse", diskOfferingSearch.entity().getSystemUse(), SearchCriteria.Op.NEQ); - sb.join("diskOfferingSearch", diskOfferingSearch, sb.entity().getDiskOfferingId(), diskOfferingSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - - // display UserVM volumes only - SearchBuilder vmSearch = _vmInstanceDao.createSearchBuilder(); - vmSearch.and("type", vmSearch.entity().getType(), SearchCriteria.Op.NIN); - vmSearch.or("nulltype", vmSearch.entity().getType(), SearchCriteria.Op.NULL); - sb.join("vmSearch", vmSearch, sb.entity().getInstanceId(), vmSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } - - // now set the SC criteria... - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (keyword != null) { - SearchCriteria ssc = _volumeDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - sc.setJoinParameters("diskOfferingSearch", "systemUse", 1); - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Volume.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (type != null) { - sc.setParameters("volumeType", "%" + type + "%"); - } - if (vmInstanceId != null) { - sc.setParameters("instanceId", vmInstanceId); - } - if (zoneId != null) { - sc.setParameters("dataCenterId", zoneId); - } - if (podId != null) { - sc.setParameters("podId", podId); - } - - // Don't return DomR and ConsoleProxy volumes - sc.setJoinParameters("vmSearch", "type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.DomainRouter); - - // Only return volumes that are not destroyed - sc.setParameters("state", Volume.State.Destroy); - - Pair, Integer> volumes = _volumeDao.searchAndCount(sc, searchFilter); - - return new Pair, Integer>(volumes.first(), volumes.second()); - } @Override public String getSupportedImageFormatForCluster(Long clusterId) { @@ -3994,14 +4055,14 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return null; } } - + @Override public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) { - + if(format == null) { return HypervisorType.None; } - + if (format == ImageFormat.VHD) { return HypervisorType.XenServer; } else if (format == ImageFormat.OVA) { @@ -4090,5 +4151,5 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } return true; } - + } diff --git a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java index 7ef9c9fc9d9..02db43bd756 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -35,7 +35,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.api.BaseCmd; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.domain.DomainVO; @@ -123,13 +123,13 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class); - - private String routerTmpltName; - private String consoleProxyTmpltName; - - protected VMTemplateDaoImpl() { - } - + + private String routerTmpltName; + private String consoleProxyTmpltName; + + protected VMTemplateDaoImpl() { + } + @Override public List listByPublic() { SearchCriteria sc = PublicSearch.create(); @@ -503,8 +503,8 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem return templateZonePairList; } - - @Override + + @Override public Set> searchTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List hypers, Boolean bootable, DomainVO domain, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr,List permittedAccounts, diff --git a/server/src/com/cloud/storage/s3/S3Manager.java b/server/src/com/cloud/storage/s3/S3Manager.java index 357f2aed463..0e47d7273d6 100644 --- a/server/src/com/cloud/storage/s3/S3Manager.java +++ b/server/src/com/cloud/storage/s3/S3Manager.java @@ -21,8 +21,8 @@ package com.cloud.storage.s3; import java.util.List; import com.cloud.agent.api.to.S3TO; -import com.cloud.api.commands.AddS3Cmd; -import com.cloud.api.commands.ListS3sCmd; +import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; import com.cloud.dc.DataCenterVO; import com.cloud.exception.DiscoveryException; import com.cloud.storage.S3; diff --git a/server/src/com/cloud/storage/s3/S3ManagerImpl.java b/server/src/com/cloud/storage/s3/S3ManagerImpl.java index 0da11ffa590..1db809b07b2 100644 --- a/server/src/com/cloud/storage/s3/S3ManagerImpl.java +++ b/server/src/com/cloud/storage/s3/S3ManagerImpl.java @@ -44,6 +44,7 @@ import java.util.concurrent.Callable; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -52,8 +53,7 @@ import com.cloud.agent.api.DeleteTemplateFromS3Command; import com.cloud.agent.api.DownloadTemplateFromS3ToSecondaryStorageCommand; import com.cloud.agent.api.UploadTemplateToS3FromSecondaryStorageCommand; import com.cloud.agent.api.to.S3TO; -import com.cloud.api.commands.AddS3Cmd; -import com.cloud.api.commands.ListS3sCmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index 7ab464b2524..6a0f71d1f6f 100755 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -26,6 +26,8 @@ import java.util.TimeZone; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; @@ -42,11 +44,9 @@ import com.cloud.agent.api.downloadSnapshotFromSwiftCommand; import com.cloud.agent.api.to.S3TO; import com.cloud.agent.api.to.SwiftTO; import com.cloud.alert.AlertManager; -import com.cloud.api.commands.CreateSnapshotPolicyCmd; -import com.cloud.api.commands.DeleteSnapshotPoliciesCmd; +import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; -import com.cloud.api.commands.ListSnapshotPoliciesCmd; -import com.cloud.api.commands.ListSnapshotsCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; diff --git a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java index 80c6a236a42..d7deb6fa74b 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java @@ -26,18 +26,17 @@ import java.util.TimerTask; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; -import com.cloud.api.commands.CreateSnapshotCmd; import com.cloud.user.Account; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; import com.cloud.async.AsyncJobVO; import com.cloud.async.dao.AsyncJobDao; -import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; diff --git a/server/src/com/cloud/storage/swift/SwiftManager.java b/server/src/com/cloud/storage/swift/SwiftManager.java index d897442da8e..0dd6e1cf22a 100644 --- a/server/src/com/cloud/storage/swift/SwiftManager.java +++ b/server/src/com/cloud/storage/swift/SwiftManager.java @@ -19,10 +19,10 @@ package com.cloud.storage.swift; import java.util.List; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import com.cloud.exception.DiscoveryException; import com.cloud.storage.Swift; import com.cloud.storage.SwiftVO; diff --git a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java index 893246940eb..dab16ced985 100644 --- a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java +++ b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java @@ -25,16 +25,16 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.DeleteObjectFromSwiftCommand; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/storage/upload/UploadListener.java b/server/src/com/cloud/storage/upload/UploadListener.java index 5e8e3e0a8ab..ee13cf9b0d8 100755 --- a/server/src/com/cloud/storage/upload/UploadListener.java +++ b/server/src/com/cloud/storage/upload/UploadListener.java @@ -24,6 +24,8 @@ import java.util.Map; import java.util.Timer; import java.util.TimerTask; +import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; import org.apache.log4j.Level; import org.apache.log4j.Logger; @@ -38,14 +40,12 @@ import com.cloud.agent.api.storage.UploadAnswer; import com.cloud.agent.api.storage.UploadCommand; import com.cloud.agent.api.storage.UploadProgressCommand; import com.cloud.agent.api.storage.UploadProgressCommand.RequestType; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd; +import org.apache.cloudstack.api.response.ExtractResponse; + +import com.cloud.api.ApiDBUtils; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; -import com.cloud.async.executor.ExtractJobResultObject; -import com.cloud.event.EventVO; import com.cloud.exception.AgentUnavailableException; import com.cloud.host.HostVO; import com.cloud.storage.Storage; @@ -57,12 +57,12 @@ import com.cloud.storage.upload.UploadState.UploadEvent; import com.cloud.utils.exception.CloudRuntimeException; public class UploadListener implements Listener { - + private static final class StatusTask extends TimerTask { private final UploadListener ul; private final RequestType reqType; - + public StatusTask( UploadListener ul, RequestType req) { this.reqType = req; this.ul = ul; @@ -74,10 +74,10 @@ public class UploadListener implements Listener { } } - + private static final class TimeoutTask extends TimerTask { private final UploadListener ul; - + public TimeoutTask( UploadListener ul) { this.ul = ul; } @@ -91,13 +91,13 @@ public class UploadListener implements Listener { public static final Logger s_logger = Logger.getLogger(UploadListener.class.getName()); public static final int SMALL_DELAY = 100; public static final long STATUS_POLL_INTERVAL = 10000L; - + public static final String UPLOADED=Status.UPLOADED.toString(); public static final String NOT_UPLOADED=Status.NOT_UPLOADED.toString(); public static final String UPLOAD_ERROR=Status.UPLOAD_ERROR.toString(); public static final String UPLOAD_IN_PROGRESS=Status.UPLOAD_IN_PROGRESS.toString(); public static final String UPLOAD_ABANDONED=Status.ABANDONED.toString(); - public static final Map responseNameMap; + public static final Map responseNameMap; static{ MaptempMap = new HashMap(); tempMap.put(Type.ISO.toString(), ExtractIsoCmd.getStaticName()); @@ -108,16 +108,16 @@ public class UploadListener implements Listener { } - private HostVO sserver; - + private HostVO sserver; + private boolean uploadActive = true; - + private UploadDao uploadDao; - + private final UploadMonitorImpl uploadMonitor; - + private UploadState currState; - + private UploadCommand cmd; private Timer timer; @@ -133,7 +133,7 @@ public class UploadListener implements Listener { private long eventId; private AsyncJobManager asyncMgr; private ExtractResponse resultObj; - + public AsyncJobManager getAsyncMgr() { return asyncMgr; } @@ -159,12 +159,12 @@ public class UploadListener implements Listener { } private final Map stateMap = new HashMap(); - private Long uploadId; - + private Long uploadId; + public UploadListener(HostVO host, Timer _timer, UploadDao uploadDao, UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd, Long accountId, String typeName, Type type, long eventId, long asyncJobId, AsyncJobManager asyncMgr) { - this.sserver = host; + this.sserver = host; this.uploadDao = uploadDao; this.uploadMonitor = uploadMonitor; this.cmd = cmd; @@ -180,15 +180,23 @@ public class UploadListener implements Listener { this.eventId = eventId; this.asyncJobId = asyncJobId; this.asyncMgr = asyncMgr; - this.resultObj = new ExtractResponse(uploadObj.getTypeId(), typeName, accountId, Status.NOT_UPLOADED.toString(), uploadId); + String extractId = null; + if ( type == Type.VOLUME ){ + extractId = ApiDBUtils.findVolumeById(uploadObj.getTypeId()).getUuid(); + } + else{ + extractId = ApiDBUtils.findTemplateById(uploadObj.getTypeId()).getUuid(); + } + this.resultObj = new ExtractResponse(extractId, typeName, ApiDBUtils.findAccountById(accountId).getUuid(), Status.NOT_UPLOADED.toString(), + ApiDBUtils.findUploadById(uploadId).getUuid()); resultObj.setResponseName(responseNameMap.get(type.toString())); updateDatabase(Status.NOT_UPLOADED, cmd.getUrl(),""); } - + public UploadListener(UploadMonitorImpl monitor) { uploadMonitor = monitor; - } - + } + public void checkProgress() { transition(UploadEvent.TIMEOUT_CHECK, null); } @@ -206,15 +214,15 @@ public class UploadListener implements Listener { public void setCommand(UploadCommand _cmd) { this.cmd = _cmd; } - + public void setJobId(String _jobId) { this.jobId = _jobId; } - + public String getJobId() { return jobId; } - + @Override public boolean processAnswers(long agentId, long seq, Answer[] answers) { boolean processed = false; @@ -232,7 +240,7 @@ public class UploadListener implements Listener { } return processed; } - + @Override public boolean processCommands(long agentId, long seq, Command[] commands) { @@ -240,13 +248,13 @@ public class UploadListener implements Listener { } @Override - public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) { + public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) { if (!(cmd instanceof StartupStorageCommand)) { return; } - + long agentId = agent.getId(); - + StartupStorageCommand storage = (StartupStorageCommand)cmd; if (storage.getResourceType() == Storage.StorageResourceType.STORAGE_HOST || storage.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE ) @@ -260,35 +268,35 @@ public class UploadListener implements Listener { AgentControlCommand cmd) { return null; } - + public void setUploadInactive(Status reason) { uploadActive=false; uploadMonitor.handleUploadEvent(sserver, accountId, typeName, type, uploadId, reason, eventId); } - + public void logUploadStart() { //uploadMonitor.logEvent(accountId, event, "Storage server " + sserver.getName() + " started upload of " +type.toString() + " " + typeName, EventVO.LEVEL_INFO, eventId); } - + public void cancelTimeoutTask() { if (timeoutTask != null) timeoutTask.cancel(); } - + public void cancelStatusTask() { if (statusTask != null) statusTask.cancel(); } @Override - public boolean processDisconnect(long agentId, com.cloud.host.Status state) { + public boolean processDisconnect(long agentId, com.cloud.host.Status state) { setDisconnected(); return true; } @Override - public boolean processTimeout(long agentId, long seq) { + public boolean processTimeout(long agentId, long seq) { return true; } - + private void initStateMachine() { stateMap.put(Status.NOT_UPLOADED.toString(), new NotUploadedState(this)); stateMap.put(Status.UPLOADED.toString(), new UploadCompleteState(this)); @@ -296,7 +304,7 @@ public class UploadListener implements Listener { stateMap.put(Status.UPLOAD_IN_PROGRESS.toString(), new UploadInProgressState(this)); stateMap.put(Status.ABANDONED.toString(), new UploadAbandonedState(this)); } - + private UploadState getState(String stateName) { return stateMap.get(stateName); } @@ -318,15 +326,15 @@ public class UploadListener implements Listener { throw new CloudRuntimeException("Unhandled event transition: currState="+prevName+", evt="+event); } } - + public Date getLastUpdated() { return lastUpdated; } - + public void setLastUpdated() { lastUpdated = new Date(); } - + public void log(String message, Level level) { s_logger.log(level, message + ", " + type.toString() + " = " + typeName + " at host " + sserver.getName()); } @@ -334,7 +342,7 @@ public class UploadListener implements Listener { public void setDisconnected() { transition(UploadEvent.DISCONNECT, null); } - + public void scheduleStatusCheck(com.cloud.agent.api.storage.UploadProgressCommand.RequestType getStatus) { if (statusTask != null) statusTask.cancel(); @@ -351,27 +359,27 @@ public class UploadListener implements Listener { log("Scheduling timeout at " + delay + " ms", Level.DEBUG); } } - + public void updateDatabase(Status state, String uploadErrorString) { resultObj.setResultString(uploadErrorString); resultObj.setState(state.toString()); asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); - + UploadVO vo = uploadDao.createForUpdate(); vo.setUploadState(state); vo.setLastUpdated(new Date()); vo.setErrorString(uploadErrorString); uploadDao.update(getUploadId(), vo); } - + public void updateDatabase(Status state, String uploadUrl,String uploadErrorString) { resultObj.setResultString(uploadErrorString); resultObj.setState(state.toString()); asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); - - + + UploadVO vo = uploadDao.createForUpdate(); vo.setUploadState(state); vo.setLastUpdated(new Date()); @@ -379,23 +387,23 @@ public class UploadListener implements Listener { vo.setJobId(null); vo.setUploadPercent(0); vo.setErrorString(uploadErrorString); - + uploadDao.update(getUploadId(), vo); } - + private Long getUploadId() { return uploadId; } - public synchronized void updateDatabase(UploadAnswer answer) { - + public synchronized void updateDatabase(UploadAnswer answer) { + if(answer.getErrorString().startsWith("553")){ answer.setErrorString(answer.getErrorString().concat("Please check if the file name already exists.")); } resultObj.setResultString(answer.getErrorString()); resultObj.setState(answer.getUploadStatus().toString()); resultObj.setUploadPercent(answer.getUploadPct()); - + if (answer.getUploadStatus() == Status.UPLOAD_IN_PROGRESS){ asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); @@ -411,7 +419,7 @@ public class UploadListener implements Listener { updateBuilder.setLastUpdated(new Date()); updateBuilder.setErrorString(answer.getErrorString()); updateBuilder.setJobId(answer.getJobId()); - + uploadDao.update(getUploadId(), updateBuilder); } @@ -427,9 +435,9 @@ public class UploadListener implements Listener { setDisconnected(); } } - + } - + private UploadCommand getCommand() { return cmd; } @@ -437,7 +445,7 @@ public class UploadListener implements Listener { public void logDisconnect() { s_logger.warn("Unable to monitor upload progress of " + typeName + " at host " + sserver.getName()); } - + public void scheduleImmediateStatusCheck(RequestType request) { if (statusTask != null) statusTask.cancel(); statusTask = new StatusTask(this, request); @@ -445,6 +453,6 @@ public class UploadListener implements Listener { } public void setCurrState(Status uploadState) { - this.currState = getState(currState.toString()); + this.currState = getState(currState.toString()); } } diff --git a/server/src/com/cloud/tags/ResourceTagVO.java b/server/src/com/cloud/tags/ResourceTagVO.java index 4a4a22b44ae..04ae757bf75 100644 --- a/server/src/com/cloud/tags/ResourceTagVO.java +++ b/server/src/com/cloud/tags/ResourceTagVO.java @@ -27,13 +27,14 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.server.ResourceTag; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="resource_tags") -public class ResourceTagVO implements Identity, ResourceTag{ +public class ResourceTagVO implements ResourceTag { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index 237a6774675..42d3c8332da 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -24,9 +24,12 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.ListTagsCmd; + +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.domain.Domain; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; @@ -74,15 +77,17 @@ import com.cloud.vm.dao.UserVmDao; public class TaggedResourceManagerImpl implements TaggedResourceService, Manager{ public static final Logger s_logger = Logger.getLogger(TaggedResourceManagerImpl.class); private String _name; - - private static Map> _daoMap= + + private static Map> _daoMap= new HashMap>(); - + @Inject AccountManager _accountMgr; @Inject ResourceTagDao _resourceTagDao; @Inject + ResourceTagJoinDao _resourceTagJoinDao; + @Inject IdentityDao _identityDao; @Inject DomainManager _domainMgr; @@ -117,7 +122,7 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager @Override public boolean configure(String name, Map params) throws ConfigurationException { - _name = name; + _name = name; _daoMap.put(TaggedResourceType.UserVm, _userVmDao); _daoMap.put(TaggedResourceType.Volume, _volumeDao); _daoMap.put(TaggedResourceType.Template, _templateDao); @@ -152,16 +157,16 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager return _name; } - - private Long getResourceId(String resourceId, TaggedResourceType resourceType) { + + private Long getResourceId(String resourceId, TaggedResourceType resourceType) { GenericDao dao = _daoMap.get(resourceType); if (dao == null) { throw new CloudRuntimeException("Dao is not loaded for the resource type " + resourceType); } Class claz = DbUtil.getEntityBeanType(dao); - + Long identityId = null; - + while (claz != null && claz != Object.class) { try { String tableName = DbUtil.getTableName(claz); @@ -177,7 +182,7 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager } claz = claz.getSuperclass(); } - + if (identityId == null) { throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType); } @@ -189,9 +194,9 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager Class claz = DbUtil.getEntityBeanType(dao); return DbUtil.getTableName(claz); } - + private Pair getAccountDomain(long resourceId, TaggedResourceType resourceType) { - + Pair pair = null; GenericDao dao = _daoMap.get(resourceType); Class claz = DbUtil.getEntityBeanType(dao); @@ -213,21 +218,21 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager Long accountId = pair.first(); Long domainId = pair.second(); - + if (accountId == null) { accountId = Account.ACCOUNT_ID_SYSTEM; } - + if (domainId == null) { domainId = Domain.ROOT_DOMAIN; } - + return new Pair(accountId, domainId); } @Override public TaggedResourceType getResourceType(String resourceTypeStr) { - + for (TaggedResourceType type : ResourceTag.TaggedResourceType.values()) { if (type.toString().equalsIgnoreCase(resourceTypeStr)) { return type; @@ -239,26 +244,26 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager @Override @DB @ActionEvent(eventType = EventTypes.EVENT_TAGS_CREATE, eventDescription = "creating resource tags") - public List createTags(List resourceIds, TaggedResourceType resourceType, + public List createTags(List resourceIds, TaggedResourceType resourceType, Map tags, String customer) { Account caller = UserContext.current().getCaller(); - + List resourceTags = new ArrayList(tags.size()); - + Transaction txn = Transaction.currentTxn(); txn.start(); - + for (String key : tags.keySet()) { for (String resourceId : resourceIds) { Long id = getResourceId(resourceId, resourceType); String resourceUuid = getUuid(resourceId, resourceType); - + //check if object exists if (_daoMap.get(resourceType).findById(id) == null) { - throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + + throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType); } - + Pair accountDomainPair = getAccountDomain(id, resourceType); Long domainId = accountDomainPair.second(); Long accountId = accountDomainPair.first(); @@ -269,143 +274,78 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId)); } else { throw new PermissionDeniedException("Account " + caller + " doesn't have permissions to create tags" + - " for resource " + key); + " for resource " + key); } - + String value = tags.get(key); - + if (value == null || value.isEmpty()) { throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty"); } - + ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(), - accountDomainPair.second(), + accountDomainPair.second(), id, resourceType, customer, resourceUuid); resourceTag = _resourceTagDao.persist(resourceTag); resourceTags.add(resourceTag); } } - + txn.commit(); - + return resourceTags; } - + @Override public String getUuid(String resourceId, TaggedResourceType resourceType) { GenericDao dao = _daoMap.get(resourceType); Class claz = DbUtil.getEntityBeanType(dao); - + String identiyUUId = null; - + while (claz != null && claz != Object.class) { try { String tableName = DbUtil.getTableName(claz); if (tableName == null) { throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database"); } - + claz = claz.getSuperclass(); if (claz == Object.class) { identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId); - } + } } catch (Exception ex) { //do nothing here, it might mean uuid field is missing and we have to search further } } - + if (identiyUUId == null) { return resourceId; } - + return identiyUUId; } - @Override - public Pair, Integer> listTags(ListTagsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String key = cmd.getKey(); - String value = cmd.getValue(); - String resourceId = cmd.getResourceId(); - String resourceType = cmd.getResourceType(); - String customerName = cmd.getCustomer(); - boolean listAll = cmd.listAll(); - - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), - cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(ResourceTagVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - - SearchBuilder sb = _resourceTagDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); - sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); - - if (resourceId != null) { - sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); - sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); - sb.cp(); - } - - sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); - - // now set the SC criteria... - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (key != null) { - sc.setParameters("key", key); - } - - if (value != null) { - sc.setParameters("value", value); - } - - if (resourceId != null) { - sc.setParameters("resourceId", resourceId); - sc.setParameters("resourceUuid", resourceId); - } - - if (resourceType != null) { - sc.setParameters("resourceType", resourceType); - } - - if (customerName != null) { - sc.setParameters("customer", customerName); - } - - Pair, Integer> result = _resourceTagDao.searchAndCount(sc, searchFilter); - return new Pair, Integer> (result.first(), result.second()); - } - @Override @DB @ActionEvent(eventType = EventTypes.EVENT_TAGS_DELETE, eventDescription = "deleting resource tags") public boolean deleteTags(List resourceIds, TaggedResourceType resourceType, Map tags) { Account caller = UserContext.current().getCaller(); - + SearchBuilder sb = _resourceTagDao.createSearchBuilder(); sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.IN); sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.IN); sb.cp(); sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); - + SearchCriteria sc = sb.create(); sc.setParameters("resourceId", resourceIds.toArray()); sc.setParameters("resourceUuid", resourceIds.toArray()); sc.setParameters("resourceType", resourceType); - + List resourceTags = _resourceTagDao.search(sc, null);; List tagsToRemove = new ArrayList(); - + // Finalize which tags should be removed for (ResourceTag resourceTag : resourceTags) { //1) validate the permissions @@ -429,16 +369,16 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager break; } } - } + } } else { tagsToRemove.add(resourceTag); } } - + if (tagsToRemove.isEmpty()) { throw new InvalidParameterValueException("Unable to find tags by parameters specified"); } - + //Remove the tags Transaction txn = Transaction.currentTxn(); txn.start(); diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HyervisorTemplateAdapter.java index bdb89f65f80..c80d1de0fbf 100755 --- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java +++ b/server/src/com/cloud/template/HyervisorTemplateAdapter.java @@ -25,15 +25,15 @@ import java.util.List; import javax.ejb.Local; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; diff --git a/server/src/com/cloud/template/TemplateAdapter.java b/server/src/com/cloud/template/TemplateAdapter.java index 26e10ee7e77..a5eb42d1b84 100755 --- a/server/src/com/cloud/template/TemplateAdapter.java +++ b/server/src/com/cloud/template/TemplateAdapter.java @@ -18,10 +18,10 @@ package com.cloud.template; import java.util.Map; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.exception.ResourceAllocationException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.VMTemplateVO; diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index 4a379b1e808..c938daa9b27 100755 --- a/server/src/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/com/cloud/template/TemplateAdapterBase.java @@ -21,14 +21,14 @@ import java.util.Map; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 805be3bf675..1372111eac3 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -34,9 +34,13 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.*; +import org.apache.cloudstack.api.command.user.template.*; import org.apache.log4j.Logger; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.downloadTemplateFromSwiftToSecondaryStorageCommand; @@ -45,19 +49,8 @@ import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.CopyTemplateCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ListIsoPermissionsCmd; -import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.ListTemplatePermissionsCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; -import com.cloud.api.commands.UpdateIsoPermissionsCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.UpdateTemplatePermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; import com.cloud.configuration.Config; @@ -1342,7 +1335,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe } @Override - public List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd) { + public List listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd) { Account caller = UserContext.current().getCaller(); Long id = cmd.getId(); @@ -1382,7 +1375,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe @DB @Override - public boolean updateTemplateOrIsoPermissions(UpdateTemplateOrIsoPermissionsCmd cmd) { + public boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd) { Transaction txn = Transaction.currentTxn(); // Input validation diff --git a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java index cfb783bb0fb..cd9e20c6a46 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java @@ -22,9 +22,6 @@ import com.cloud.utils.script.Script; import java.io.File; import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; /** * @author htrippaers @@ -33,7 +30,7 @@ import java.sql.SQLException; public class Upgrade40to41 implements DbUpgrade { /** - * + * */ public Upgrade40to41() { // TODO Auto-generated constructor stub @@ -72,7 +69,7 @@ public class Upgrade40to41 implements DbUpgrade { if (script == null) { throw new CloudRuntimeException("Unable to find db/schema-40to410.sql"); } - + return new File[] { new File(script) }; } @@ -81,7 +78,7 @@ public class Upgrade40to41 implements DbUpgrade { */ @Override public void performDataMigration(Connection conn) { - upgradeEIPNetworkOfferings(conn); + } /* (non-Javadoc) @@ -92,36 +89,4 @@ public class Upgrade40to41 implements DbUpgrade { return new File[0]; } - private void upgradeEIPNetworkOfferings(Connection conn) { - PreparedStatement pstmt = null; - ResultSet rs = null; - - try { - pstmt = conn.prepareStatement("select id, elastic_ip_service from `cloud`.`network_offerings` where traffic_type='Guest'"); - rs = pstmt.executeQuery(); - while (rs.next()) { - long id = rs.getLong(1); - // check if elastic IP service is enabled for network offering - if (rs.getLong(2) != 0) { - //update network offering with eip_associate_public_ip set to true - pstmt = conn.prepareStatement("UPDATE `cloud`.`network_offerings` set eip_associate_public_ip=? where id=?"); - pstmt.setBoolean(1, true); - pstmt.setLong(2, id); - pstmt.executeUpdate(); - } - } - } catch (SQLException e) { - throw new CloudRuntimeException("Unable to set elastic_ip_service for network offerings with EIP service enabled.", e); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - } } diff --git a/server/src/com/cloud/upgrade/dao/VersionVO.java b/server/src/com/cloud/upgrade/dao/VersionVO.java index ed707c56f51..b5e3f355e24 100644 --- a/server/src/com/cloud/upgrade/dao/VersionVO.java +++ b/server/src/com/cloud/upgrade/dao/VersionVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.upgrade.dao; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -31,7 +33,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="version") -public class VersionVO { +public class VersionVO implements InternalIdentity { public enum Step { Upgrade, Complete diff --git a/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java b/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java index f9c034a9400..7ad933c2b8c 100644 --- a/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java +++ b/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -28,7 +30,7 @@ import javax.persistence.Table; @Entity @Table(name="external_public_ip_statistics") @PrimaryKeyJoinColumn(name="id") -public class ExternalPublicIpStatisticsVO { +public class ExternalPublicIpStatisticsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -61,7 +63,7 @@ public class ExternalPublicIpStatisticsVO { this.currentBytesSent = 0; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageIPAddressVO.java b/server/src/com/cloud/usage/UsageIPAddressVO.java index 8e68182ad5a..a11dfe2b4b6 100644 --- a/server/src/com/cloud/usage/UsageIPAddressVO.java +++ b/server/src/com/cloud/usage/UsageIPAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_ip_address") -public class UsageIPAddressVO { +public class UsageIPAddressVO implements InternalIdentity { @Column(name="account_id") private long accountId; diff --git a/server/src/com/cloud/usage/UsageJobVO.java b/server/src/com/cloud/usage/UsageJobVO.java index 174b6a32150..7761e871665 100644 --- a/server/src/com/cloud/usage/UsageJobVO.java +++ b/server/src/com/cloud/usage/UsageJobVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_job") -public class UsageJobVO { +public class UsageJobVO implements InternalIdentity { public static final int JOB_TYPE_RECURRING = 0; public static final int JOB_TYPE_SINGLE = 1; @@ -80,7 +82,7 @@ public class UsageJobVO { public UsageJobVO() {} - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java index 3ed9a631c1f..e952b1ade0a 100644 --- a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java +++ b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_load_balancer_policy") -public class UsageLoadBalancerPolicyVO { +public class UsageLoadBalancerPolicyVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java index cc0cd433c28..641ae76071c 100644 --- a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java +++ b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_port_forwarding") -public class UsagePortForwardingRuleVO { +public class UsagePortForwardingRuleVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsageStorageVO.java b/server/src/com/cloud/usage/UsageStorageVO.java index bf2ee158831..1337edc3d59 100644 --- a/server/src/com/cloud/usage/UsageStorageVO.java +++ b/server/src/com/cloud/usage/UsageStorageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_storage") -public class UsageStorageVO { +public class UsageStorageVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsageTypes.java b/server/src/com/cloud/usage/UsageTypes.java index af77c323451..e5a48d5c143 100644 --- a/server/src/com/cloud/usage/UsageTypes.java +++ b/server/src/com/cloud/usage/UsageTypes.java @@ -19,7 +19,7 @@ package com.cloud.usage; import java.util.ArrayList; import java.util.List; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; public class UsageTypes { public static final int RUNNING_VM = 1; diff --git a/server/src/com/cloud/usage/UsageVO.java b/server/src/com/cloud/usage/UsageVO.java index 2e816ffdba3..bcb9c2d6363 100644 --- a/server/src/com/cloud/usage/UsageVO.java +++ b/server/src/com/cloud/usage/UsageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="cloud_usage") -public class UsageVO { +public class UsageVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -165,7 +167,7 @@ public class UsageVO { this.endDate = endDate; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageVolumeVO.java b/server/src/com/cloud/usage/UsageVolumeVO.java index 1e003720ae8..4ba88984fa5 100644 --- a/server/src/com/cloud/usage/UsageVolumeVO.java +++ b/server/src/com/cloud/usage/UsageVolumeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_volume") -public class UsageVolumeVO { +public class UsageVolumeVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/user/AccountDetailVO.java b/server/src/com/cloud/user/AccountDetailVO.java index 76c87b11107..a8afadba3fc 100755 --- a/server/src/com/cloud/user/AccountDetailVO.java +++ b/server/src/com/cloud/user/AccountDetailVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_details") -public class AccountDetailVO { +public class AccountDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index 90a34ad82b3..9ca4721187c 100755 --- a/server/src/com/cloud/user/AccountManager.java +++ b/server/src/com/cloud/user/AccountManager.java @@ -19,11 +19,9 @@ package com.cloud.user; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.domain.Domain; +import org.apache.cloudstack.acl.ControlledEntity; +import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.utils.Pair; @@ -93,9 +91,15 @@ public interface AccountManager extends AccountService { void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation); diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index f59547885fe..b910a03f99b 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -36,19 +36,22 @@ import javax.crypto.spec.SecretKeySpec; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.vo.ControlledViewEntity; + + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceLimit; @@ -117,7 +120,6 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; @@ -156,6 +158,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Inject private UserAccountDao _userAccountDao; @Inject + private UserAccountJoinDao _userAccountJoinDao; + @Inject private VolumeDao _volumeDao; @Inject private UserVmDao _userVmDao; @@ -292,7 +296,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } @@ -490,7 +494,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Override public boolean deleteAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); - + //delete the account record if (!_accountDao.remove(accountId)) { s_logger.error("Unable to delete account " + accountId); @@ -508,7 +512,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) { long accountId = account.getId(); boolean accountCleanupNeeded = false; - + try { //cleanup the users from the account List users = _userDao.listByAccount(accountId); @@ -518,10 +522,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag accountCleanupNeeded = true; } } - + //delete the account from project accounts _projectAccountDao.removeAccountFromProjects(accountId); - + // delete all vm groups belonging to accont List groups = _vmGroupDao.listByAccountId(accountId); for (InstanceGroupVO group : groups) { @@ -599,7 +603,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex); accountCleanupNeeded = true; } - + // Cleanup security groups int numRemoved = _securityGroupDao.removeByAccountId(accountId); s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId); @@ -622,7 +626,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } } - + //Delete all VPCs boolean vpcsDeleted = true; s_logger.debug("Deleting vpcs for account " + account.getId()); @@ -757,6 +761,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // ////////////// API commands ///////////////////// // /////////////////////////////////////////////////// + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account") @@ -773,7 +778,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (userName.isEmpty()) { throw new InvalidParameterValueException("Username is empty"); } - + if (firstName.isEmpty()) { throw new InvalidParameterValueException("Firstname is empty"); } @@ -845,7 +850,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user"); } - + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new PermissionDeniedException("Account id : " + account.getId() + " is a system account, can't add a user to it"); } @@ -902,21 +907,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (firstName.isEmpty()) { throw new InvalidParameterValueException("Firstname is empty"); } - + user.setFirstname(firstName); } if (lastName != null) { if (lastName.isEmpty()) { throw new InvalidParameterValueException("Lastname is empty"); } - + user.setLastname(lastName); } if (userName != null) { if (userName.isEmpty()) { throw new InvalidParameterValueException("Username is empty"); } - + // don't allow to have same user names in the same domain List duplicatedUsers = _userDao.findUsersByName(userName); for (UserVO duplicatedUser : duplicatedUsers) { @@ -930,7 +935,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag user.setUsername(userName); } - + if (password != null) { String encodedPassword = null; for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { @@ -1212,7 +1217,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new PermissionDeniedException("Account id : " + accountId + " is a system account, lock is not allowed"); } @@ -1241,7 +1246,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (account == null || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { throw new PermissionDeniedException("Account id : " + accountId + " is a system account, disable is not allowed"); } @@ -1393,7 +1398,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.info("Found " + removedAccounts.size() + " removed accounts to cleanup"); for (AccountVO account : removedAccounts) { s_logger.debug("Cleaning up " + account.getId()); - cleanupAccount(account, getSystemUser().getId(), getSystemAccount()); + cleanupAccount(account, getSystemUser().getId(), getSystemAccount()); } // cleanup disabled accounts @@ -1538,6 +1543,31 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } + @Override + public RoleType getRoleType(Account account) { + RoleType roleType = RoleType.Unknown; + if (account == null) + return roleType; + short accountType = account.getType(); + + // Account type to role type translation + switch (accountType) { + case Account.ACCOUNT_TYPE_ADMIN: + roleType = RoleType.Admin; + break; + case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: + roleType = RoleType.DomainAdmin; + break; + case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: + roleType = RoleType.ResourceAdmin; + break; + case Account.ACCOUNT_TYPE_NORMAL: + roleType = RoleType.User; + break; + } + return roleType; + } + @Override public User getActiveUser(long userId) { return _userDao.findById(userId); @@ -1692,7 +1722,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); } - + String encodedPassword = null; for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { UserAuthenticator authenticator = en.nextElement(); @@ -1840,7 +1870,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.error("Failed to authenticate user: " + username + " in domain " + domainId); return null; } - + if (s_logger.isDebugEnabled()) { s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in"); } @@ -1939,10 +1969,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag Long userId = cmd.getId(); User user = getUserIncludingRemoved(userId); - if (user == null) { + if (user == null) { throw new InvalidParameterValueException("unable to find user by id"); } - + //don't allow updating system user if (user.getId() == User.UID_SYSTEM) { throw new PermissionDeniedException("user id : " + user.getId() + " is system account, update is not allowed"); @@ -2014,223 +2044,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return null; } - @Override - public Pair, Integer> searchForAccounts(ListAccountsCmd cmd) { - Account caller = UserContext.current().getCaller(); - Long domainId = cmd.getDomainId(); - Long accountId = cmd.getId(); - String accountName = cmd.getSearchName(); - boolean isRecursive = cmd.isRecursive(); - boolean listAll = cmd.listAll(); - Boolean listForDomain = false; - if (accountId != null) { - Account account = _accountDao.findById(accountId); - if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by id " + accountId); - } - - checkAccess(caller, null, true, account); - } - - if (domainId != null) { - Domain domain = _domainMgr.getDomain(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); - } - - checkAccess(caller, domain); - - if (accountName != null) { - Account account = _accountDao.findActiveAccount(accountName, domainId); - if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); - } - checkAccess(caller, null, true, account); - } - } - - if (accountId == null) { - if (isAdmin(caller.getType()) && listAll && domainId == null) { - listForDomain = true; - isRecursive = true; - if (domainId == null) { - domainId = caller.getDomainId(); - } - } else if (isAdmin(caller.getType()) && domainId != null) { - listForDomain = true; - } else { - accountId = caller.getAccountId(); - } - } - - Filter searchFilter = new Filter(AccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - Object type = cmd.getAccountType(); - Object state = cmd.getState(); - Object isCleanupRequired = cmd.isCleanupRequired(); - Object keyword = cmd.getKeyword(); - - SearchBuilder sb = _accountDao.createSearchBuilder(); - sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("needsCleanup", sb.entity().getNeedsCleanup(), SearchCriteria.Op.EQ); - sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); - sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); - - if (listForDomain && isRecursive) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); - - if (keyword != null) { - SearchCriteria ssc = _accountDao.createSearchCriteria(); - ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("accountName", SearchCriteria.Op.SC, ssc); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (isCleanupRequired != null) { - sc.setParameters("needsCleanup", isCleanupRequired); - } - - if (accountName != null) { - sc.setParameters("accountName", accountName); - } - - // don't return account of type project to the end user - sc.setParameters("typeNEQ", 5); - - if (accountId != null) { - sc.setParameters("id", accountId); - } - - if (listForDomain) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - Pair, Integer> result = _accountDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); - } - - @Override - public Pair, Integer> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { - Account caller = UserContext.current().getCaller(); - - Long domainId = cmd.getDomainId(); - if (domainId != null) { - Domain domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); - } - - checkAccess(caller, domain); - } else { - // default domainId to the caller's domain - domainId = caller.getDomainId(); - } - - Filter searchFilter = new Filter(UserAccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - Long id = cmd.getId(); - Object username = cmd.getUsername(); - Object type = cmd.getAccountType(); - Object accountName = cmd.getAccountName(); - Object state = cmd.getState(); - Object keyword = cmd.getKeyword(); - - SearchBuilder sb = _userAccountDao.createSearchBuilder(); - sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE); - if (id != null && id == 1) { - // system user should NOT be searchable - List emptyList = new ArrayList(); - return new Pair, Integer>(emptyList, 0); - } else if (id != null) { - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - } else { - // this condition is used to exclude system user from the search results - sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ); - } - - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - - if ((accountName == null) && (domainId != null)) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - if (keyword != null) { - SearchCriteria ssc = _userAccountDao.createSearchCriteria(); - ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("username", SearchCriteria.Op.SC, ssc); - } - - if (username != null) { - sc.setParameters("username", username); - } - - if (id != null) { - sc.setParameters("id", id); - } else { - // Don't return system user, search builder with NEQ - sc.setParameters("id", 1); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (accountName != null) { - sc.setParameters("accountName", accountName); - if (domainId != null) { - sc.setParameters("domainId", domainId); - } - } else if (domainId != null) { - DomainVO domainVO = _domainDao.findById(domainId); - sc.setJoinParameters("domainSearch", "path", domainVO.getPath() + "%"); - } - - if (state != null) { - sc.setParameters("state", state); - } - - Pair, Integer> result = _userAccountDao.searchAndCount(sc, searchFilter); - return new Pair, Integer>(result.first(), result.second()); - } @Override public void buildACLSearchBuilder(SearchBuilder sb, @@ -2300,7 +2114,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override - public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List + public void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation) { Long domainId = domainIdRecursiveListProject.first(); @@ -2380,8 +2194,51 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } } - @Override - public UserAccount getUserByApiKey(String apiKey) { - return _userAccountDao.getUserByApiKey(apiKey); - } + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + + if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { + // if accountId isn't specified, we can do a domain match for the + // admin case if isRecursive is true + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + if (listProjectResourcesCriteria != null) { + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); + } + } + + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + if (listProjectResourcesCriteria != null) { + sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); + } + + if (!permittedAccounts.isEmpty()) { + sc.setParameters("accountIdIN", permittedAccounts.toArray()); + } else if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (isRecursive) { + sc.setParameters("domainPath", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + } + + @Override + public UserAccount getUserByApiKey(String apiKey) { + return _userAccountDao.getUserByApiKey(apiKey); + } } diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index c2346162028..54ca2ac44bd 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -24,10 +24,10 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import org.apache.log4j.Logger; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.domain.Domain; @@ -85,6 +85,11 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager return _domainDao.findById(domainId); } + @Override + public Domain getDomain(String domainUuid) { + return _domainDao.findByUuid(domainUuid); + } + @Override public String getName() { return _name; diff --git a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java index 6ec3f253fd6..3cd2bc93290 100644 --- a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java +++ b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java @@ -21,8 +21,7 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.IdentityMapper; -import com.cloud.api.IdentityService; +import org.apache.cloudstack.api.IdentityService; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.uuididentity.dao.IdentityDao; @@ -33,10 +32,6 @@ public class IdentityServiceImpl implements Manager, IdentityService { @Inject private IdentityDao _identityDao; - public Long getIdentityId(IdentityMapper mapper, String identityString) { - return _identityDao.getIdentityId(mapper, identityString); - } - public Long getIdentityId(String tableName, String identityString) { return _identityDao.getIdentityId(tableName, identityString); } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDao.java b/server/src/com/cloud/uuididentity/dao/IdentityDao.java index e2758fbe88b..e9149a0fe63 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDao.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDao.java @@ -17,13 +17,11 @@ package com.cloud.uuididentity.dao; -import com.cloud.api.IdentityMapper; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; public interface IdentityDao extends GenericDao { - Long getIdentityId(IdentityMapper mapper, String identityString); Long getIdentityId(String tableName, String identityString); String getIdentityUuid(String tableName, String identityString); void initializeDefaultUuid(String tableName); @@ -33,5 +31,5 @@ public interface IdentityDao extends GenericDao { * @param resourceType TODO * @return */ - Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType); -} + Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType); +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java index ce0ca1307fc..49d2fa77d08 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java @@ -27,7 +27,6 @@ import javax.ejb.Local; import org.apache.log4j.Logger; -import com.cloud.api.IdentityMapper; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; @@ -42,12 +41,6 @@ public class IdentityDaoImpl extends GenericDaoBase implements public IdentityDaoImpl() { } - @DB - public Long getIdentityId(IdentityMapper mapper, String identityString) { - assert(mapper.entityTableName() != null); - return getIdentityId(mapper.entityTableName(), identityString); - } - @DB public Long getIdentityId(String tableName, String identityString) { assert(tableName != null); diff --git a/server/src/com/cloud/vm/NicVO.java b/server/src/com/cloud/vm/NicVO.java index 3e9b4dc45b3..64b9153a347 100644 --- a/server/src/com/cloud/vm/NicVO.java +++ b/server/src/com/cloud/vm/NicVO.java @@ -29,14 +29,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.Mode; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "nics") -public class NicVO implements Nic, Identity { +public class NicVO implements Nic { protected NicVO() { } diff --git a/server/src/com/cloud/vm/UserVmManager.java b/server/src/com/cloud/vm/UserVmManager.java index 4ce9bfee86d..3e4a2dbf27f 100755 --- a/server/src/com/cloud/vm/UserVmManager.java +++ b/server/src/com/cloud/vm/UserVmManager.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import com.cloud.agent.api.VmStatsEntry; +import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; @@ -98,7 +99,7 @@ public interface UserVmManager extends VirtualMachineGuru, UserVmServi * @param tags TODO * @return List of UserVMs + count */ - Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags); + Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags); String getChecksum(Long hostId, String templatePath); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index a437e1f72b9..58910562beb 100644 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -5,7 +5,7 @@ // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at -// +// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, @@ -16,8 +16,6 @@ // under the License. package com.cloud.vm; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.*; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; @@ -27,8 +25,8 @@ import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; -import com.cloud.api.BaseCmd; -import com.cloud.api.commands.*; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -77,7 +75,6 @@ import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.dao.SecurityGroupDao; import com.cloud.network.security.dao.SecurityGroupVMMapDao; import com.cloud.network.vpc.VpcManager; -import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.dao.VpcDao; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -91,7 +88,6 @@ import com.cloud.projects.ProjectManager; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; import com.cloud.server.Criteria; -import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.*; @@ -102,7 +98,6 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.Volume.Type; import com.cloud.storage.dao.*; import com.cloud.storage.snapshot.SnapshotManager; -import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate; import com.cloud.template.VirtualMachineTemplate.BootloaderType; @@ -114,19 +109,30 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; -import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.crypt.RSAHelper; import com.cloud.utils.db.*; +import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.net.NetUtils; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.dao.*; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; @@ -162,6 +168,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Inject protected UserVmDao _vmDao = null; @Inject + protected UserVmJoinDao _vmJoinDao = null; + @Inject protected VolumeDao _volsDao = null; @Inject protected DataCenterDao _dcDao = null; @@ -241,9 +249,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager protected HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; @Inject protected SecurityGroupDao _securityGroupDao; - @Inject + @Inject protected CapacityManager _capacityMgr;; - @Inject + @Inject protected VMInstanceDao _vmInstanceDao; @Inject protected ResourceLimitService _resourceLimitMgr; @@ -253,7 +261,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager protected ProjectManager _projectMgr; @Inject protected ResourceManager _resourceMgr; - @Inject + @Inject protected NetworkServiceMapDao _ntwkSrvcDao; @Inject SecurityGroupVMMapDao _securityGroupVMMapDao; @@ -318,7 +326,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (result) { userVm.setPassword(password); - //update the password in vm_details table too + //update the password in vm_details table too // Check if an SSH key pair was selected for the instance and if so use it to encrypt & save the vm password String sshPublicKey = userVm.getDetail("SSH.PublicKey"); if (sshPublicKey != null && !sshPublicKey.equals("") && password != null && !password.equals("saved_password")) { @@ -361,7 +369,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserDataServiceProvider element = _networkMgr.getPasswordResetProvider(defaultNetwork); if (element == null) { - throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + + throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for password reset"); } @@ -377,7 +385,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager return true; } - if (rebootVirtualMachine(userId, vmId) == null) { + if (rebootVirtualMachine(userId, vmId) == null) { s_logger.warn("Failed to reboot the vm " + vmInstance); return false; } else { @@ -592,7 +600,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } // Check that there is some shared storage. - StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); + StoragePoolVO vmRootVolumePool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId()); List sharedVMPools = _storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(), vmRootVolumePool.getPodId(), vmRootVolumePool.getClusterId(), null, true); if (sharedVMPools.size() == 0) { throw new CloudRuntimeException("Cannot attach volume since there are no shared storage pools in the VM's cluster to copy the uploaded volume to."); @@ -1285,7 +1293,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } volume = _volsDao.findById(snapshot.getVolumeId()); - VolumeVO snapshotVolume = _volsDao.findByIdIncludingRemoved(snapshot.getVolumeId()); + VolumeVO snapshotVolume = _volsDao.findByIdIncludingRemoved(snapshot.getVolumeId()); //check permissions _accountMgr.checkAccess(caller, null, true, snapshot); @@ -1294,14 +1302,14 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation"); } - /* + /* // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT - if(snapshot.getHypervisorType() == HypervisorType.VMware && snapshotVolume.getVolumeType() == Type.DATADISK){ + if(snapshot.getHypervisorType() == HypervisorType.VMware && snapshotVolume.getVolumeType() == Type.DATADISK){ throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + " is created from Data Disk"); } */ - hyperType = snapshot.getHypervisorType(); + hyperType = snapshot.getHypervisorType(); } _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template); @@ -2093,7 +2101,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Can't create a vm with multiple networks one of" + " which is Security Group enabled"); } - + isSecurityGroupEnabledNetworkUsed = true; } @@ -2174,7 +2182,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } s_logger.debug("Creating network for account " + owner + " from the network offering id=" +requiredOfferings.get(0).getId() + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), + Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); @@ -2184,7 +2192,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } networkList.add(defaultNetwork); @@ -2211,7 +2219,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _networkModel.checkNetworkPermissions(owner, network); - //don't allow to use system networks + //don't allow to use system networks NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); if (networkOffering.isSystemOnly()) { throw new InvalidParameterValueException("Network id=" + networkId + " is system only and can't be used for vm deployment"); @@ -2432,7 +2440,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager ntwkIds.add(network.getId()); ntwkDomains.put(ntwkDomain, ntwkIds); } - } + } for (String ntwkDomain : ntwkDomains.keySet()) { for (Long ntwkId : ntwkDomains.get(ntwkDomain)) { @@ -2740,7 +2748,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); } - _accountMgr.checkAccess(caller, null, true, vm); UserVO user = _userDao.findById(userId); try { @@ -2761,10 +2768,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (ip != null && ip.getSystem()) { UserContext ctx = UserContext.current(); try { - long networkId = ip.getAssociatedWithNetworkId(); - Network guestNetwork = _networkModel.getNetwork(networkId); - NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); - assert (offering.getAssociatePublicIP() == true) : "User VM should not have system owned public IP associated with it when offering configured not to associate public IP."; _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), ctx.getCallerUserId(), true); } catch (Exception ex) { s_logger.warn("Failed to disable static nat and release system ip " + ip + " as a part of vm " + profile.getVirtualMachine() + " stop due to exception ", ex); @@ -2786,7 +2789,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (callerAccount != null && callerAccount.getRemoved() != null) { throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed"); } - + UserVmVO vm = _vmDao.findById(vmId); if (vm == null) { throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId); @@ -2874,12 +2877,12 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } vm = _itMgr.start(vm, params, callerUser, callerAccount, plan); - + Pair> vmParamPair = new Pair(vm, params); if (vm != null && vm.isUpdateParameters()) { // this value is not being sent to the backend; need only for api display purposes if (template.getEnablePassword()) { - vm.setPassword((String)vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword)); + vm.setPassword((String)vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword)); vm.setUpdateParameters(false); _vmDao.update(vm.getId(), vm); } @@ -2899,7 +2902,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a virtual machine with specified vmId"); ex.addProxyObject(vm, vmId, "vmId"); throw ex; - } + } if (vm.getState() == State.Destroyed || vm.getState() == State.Expunging) { s_logger.trace("Vm id=" + vmId + " is already destroyed"); @@ -2942,69 +2945,18 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } - @Override - public Pair, Integer> searchForUserVMs(ListVMsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String hypervisor = cmd.getHypervisor(); - boolean listAll = cmd.listAll(); - Long id = cmd.getId(); - Map tags = cmd.getTags(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); - c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); - c.addCriteria(Criteria.ID, cmd.getId()); - c.addCriteria(Criteria.NAME, cmd.getInstanceName()); - c.addCriteria(Criteria.STATE, cmd.getState()); - c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId()); - c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); - c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); - c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); - c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId()); - c.addCriteria(Criteria.ISO_ID, cmd.getIsoId()); - c.addCriteria(Criteria.VPC_ID, cmd.getVpcId()); - - if (domainId != null) { - c.addCriteria(Criteria.DOMAINID, domainId); - } - - if (HypervisorType.getType(hypervisor) != HypervisorType.None) { - c.addCriteria(Criteria.HYPERVISOR, hypervisor); - } else if (hypervisor != null) { - throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); - } - - // ignore these search requests if it's not an admin - if (_accountMgr.isAdmin(caller.getType())) { - c.addCriteria(Criteria.PODID, cmd.getPodId()); - c.addCriteria(Criteria.HOSTID, cmd.getHostId()); - c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId()); - } - - if (!permittedAccounts.isEmpty()) { - c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray()); - } - c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType())); - - Pair, Integer> result = searchForUserVMs(c, caller, domainId, isRecursive, - permittedAccounts, listAll, listProjectResourcesCriteria, tags); - return new Pair, Integer>(result.first(), result.second()); - } @Override - public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, + public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { - Filter searchFilter = new Filter(UserVmVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); + Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); + + //first search distinct vm id by using query criteria and pagination + SearchBuilder sb = _vmJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - SearchBuilder sb = _vmDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - Object id = c.getCriteria(Criteria.ID); Object name = c.getCriteria(Criteria.NAME); Object state = c.getCriteria(Criteria.STATE); @@ -3030,88 +2982,60 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); - sb.and("dataCenterId", sb.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); - sb.and("hostIdIN", sb.entity().getHostId(), SearchCriteria.Op.IN); + sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE); sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); - sb.and("isoId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ); + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); - if (groupId != null && (Long) groupId == -1) { - SearchBuilder vmSearch = _groupVMMapDao.createSearchBuilder(); - vmSearch.and("instanceId", vmSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); - sb.join("vmSearch", vmSearch, sb.entity().getId(), vmSearch.entity().getInstanceId(), JoinBuilder.JoinType.LEFTOUTER); - } else if (groupId != null) { - SearchBuilder groupSearch = _groupVMMapDao.createSearchBuilder(); - groupSearch.and("groupId", groupSearch.entity().getGroupId(), SearchCriteria.Op.EQ); - sb.join("groupSearch", groupSearch, sb.entity().getId(), groupSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + if (groupId != null && (Long) groupId != -1) { + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); } if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } if (networkId != null) { - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - - SearchBuilder networkSearch = _networkDao.createSearchBuilder(); - networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); } - - if(vpcId != null && networkId == null){ - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - SearchBuilder networkSearch = _networkDao.createSearchBuilder(); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - SearchBuilder vpcSearch = _vpcDao.createSearchBuilder(); - vpcSearch.and("vpcId", vpcSearch.entity().getId(), SearchCriteria.Op.EQ); - networkSearch.join("vpcSearch", vpcSearch, networkSearch.entity().getVpcId(), vpcSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + if(vpcId != null && networkId == null){ + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); } if (storageId != null) { - SearchBuilder volumeSearch = _volsDao.createSearchBuilder(); - volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ); - sb.join("volumeSearch", volumeSearch, sb.entity().getId(), volumeSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); + sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ); } // populate the search criteria with the values passed in - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + SearchCriteria sc = sb.create(); + + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); if (tags != null && !tags.isEmpty()) { int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.UserVm.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); count++; } } - if (groupId != null && (Long) groupId == -1) { - sc.setJoinParameters("vmSearch", "instanceId", (Object) null); - } else if (groupId != null) { - sc.setJoinParameters("groupSearch", "groupId", groupId); + if (groupId != null && (Long)groupId != -1) { + sc.setParameters("instanceGroupId", groupId); } if (keyword != null) { - SearchCriteria ssc = _vmDao.createSearchCriteria(); + SearchCriteria ssc = _vmJoinDao.createSearchCriteria(); ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -3133,11 +3057,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (networkId != null) { - sc.setJoinParameters("nicSearch", "networkId", networkId); + sc.setParameters("networkId", networkId); } - + if(vpcId != null && networkId == null){ - sc.setJoinParameters("vpcSearch", "vpcId", vpcId); + sc.setParameters("vpcId", vpcId); } if (name != null) { @@ -3176,25 +3100,29 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sc.setParameters("hostIdEQ", hostId); } else { if (hostName != null) { - List hosts = _resourceMgr.listHostsByNameLike((String) hostName); - if (hosts != null & !hosts.isEmpty()) { - Long[] hostIds = new Long[hosts.size()]; - for (int i = 0; i < hosts.size(); i++) { - HostVO host = hosts.get(i); - hostIds[i] = host.getId(); - } - sc.setParameters("hostIdIN", (Object[]) hostIds); - } else { - return new Pair, Integer>(new ArrayList(), 0); - } + sc.setParameters("hostName", hostName); } } if (storageId != null) { - sc.setJoinParameters("volumeSearch", "poolId", storageId); + sc.setParameters("poolId", storageId); } - - return _vmDao.searchAndCount(sc, searchFilter); + + // search vm details by ids + Pair, Integer> uniqueVmPair = _vmJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVmPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueVmPair; + } + List uniqueVms = uniqueVmPair.first(); + Long[] vmIds = new Long[uniqueVms.size()]; + int i = 0; + for (UserVmJoinVO v : uniqueVms ){ + vmIds[i++] = v.getId(); + } + List vms = _vmJoinDao.searchByIds(vmIds); + return new Pair, Integer>(vms, count); } @Override @@ -3202,7 +3130,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager UserVmVO userVm = _vmDao.findById(vmId); if (userVm == null) { InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id"); - ex.addProxyObject(userVm, vmId, "vmId"); + ex.addProxyObject(userVm, vmId, "vmId"); throw ex; } @@ -3318,7 +3246,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate"); } - + //check if migrating to same host long srcHostId = vm.getHostId(); if(destinationHost.getId() == srcHostId){ @@ -3388,11 +3316,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) { throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId()); } - + if (newAccount.getState() == Account.State.disabled) { throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled."); } - + // make sure the accounts are under same domain if (oldAccount.getDomainId() != newAccount.getDomainId()){ throw new InvalidParameterValueException("The account should be under same domain for moving VM between two accounts. Old owner domain =" + oldAccount.getDomainId() + @@ -3436,7 +3364,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //VV 3: check if volumes are with in resource limits _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size()); - + // VV 4: Check if new owner can use the vm template VirtualMachineTemplate template = _templateDao.findById(vm.getTemplateId()); if (!template.isPublicTemplate()) { @@ -3451,7 +3379,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager Transaction txn = Transaction.currentTxn(); txn.start(); //generate destroy vm event for usage - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), + _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString())); // update resource counts _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.user_vm); @@ -3480,7 +3408,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.user_vm); //generate usage events to account for this change - _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), + _usageEventDao.persist(new UsageEventVO(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterIdToDeployIn(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString())); txn.commit(); @@ -3491,7 +3419,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // OS 3: update the network List networkIdList = cmd.getNetworkIds(); List securityGroupIdList = cmd.getSecurityGroupIdList(); - + if (zone.getNetworkType() == NetworkType.Basic) { if (networkIdList != null && !networkIdList.isEmpty()) { throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM"); @@ -3551,7 +3479,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager NicProfile profile = new NicProfile(); profile.setDefaultNic(true); networks.add(new Pair(networkList.get(0), profile)); - + VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId()); VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi); _networkMgr.allocate(vmProfile, networks); @@ -3569,9 +3497,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager //cleanup the network for the oldOwner _networkMgr.cleanupNics(vmOldProfile); _networkMgr.expungeNics(vmOldProfile); - + Set applicableNetworks = new HashSet(); - + if (networkIdList != null && !networkIdList.isEmpty()){ // add any additional networks for (Long networkId : networkIdList) { @@ -3584,7 +3512,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _networkModel.checkNetworkPermissions(newAccount, network); - //don't allow to use system networks + //don't allow to use system networks NetworkOffering networkOffering = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); if (networkOffering.isSystemOnly()) { InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment"); @@ -3611,9 +3539,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (physicalNetwork == null) { throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags()); } - s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + + s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process"); - Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), + Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); defaultNetwork = _networkDao.findById(newNetwork.getId()); @@ -3624,7 +3552,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId()); } } else { - throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); + throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled); } applicableNetworks.add(defaultNetwork); @@ -3633,7 +3561,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager // add the new nics List> networks = new ArrayList>(); int toggle=0; - for (NetworkVO appNet: applicableNetworks){ + for (NetworkVO appNet: applicableNetworks){ NicProfile defaultNic = new NicProfile(); if (toggle==0){ defaultNic.setDefaultNic(true); @@ -3738,7 +3666,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager s_logger.debug("Restore VM " + vmId + " with template " + root.getTemplateId() + " successfully"); return vm; } - + @Override public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException, @@ -3758,5 +3686,5 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override public void prepareStop(VirtualMachineProfile profile) { } - + } diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java index f777a9e8782..e0647bbe67f 100755 --- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -767,7 +767,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene VirtualMachineTO vmTO = hvGuru.implement(vmProfile); cmds = new Commands(OnError.Stop); - cmds.addCommand(new StartCommand(vmTO)); + cmds.addCommand(new StartCommand(vmTO, dest.getHost())); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); diff --git a/server/src/com/cloud/vm/dao/NicDao.java b/server/src/com/cloud/vm/dao/NicDao.java index af3c7b379c1..762048b65bf 100644 --- a/server/src/com/cloud/vm/dao/NicDao.java +++ b/server/src/com/cloud/vm/dao/NicDao.java @@ -58,6 +58,4 @@ public interface NicDao extends GenericDao { NicVO findByNetworkIdInstanceIdAndBroadcastUri(long networkId, long instanceId, String broadcastUri); NicVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, long instanceId, String ip4Address); - - NicVO findByMacAddress(String macAddress); } diff --git a/server/src/com/cloud/vm/dao/NicDaoImpl.java b/server/src/com/cloud/vm/dao/NicDaoImpl.java index 00da2eb96a4..3cd7fa6b488 100644 --- a/server/src/com/cloud/vm/dao/NicDaoImpl.java +++ b/server/src/com/cloud/vm/dao/NicDaoImpl.java @@ -50,7 +50,6 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { AllFieldsSearch.and("address", AllFieldsSearch.entity().getIp4Address(), Op.EQ); AllFieldsSearch.and("isDefault", AllFieldsSearch.entity().isDefaultNic(), Op.EQ); AllFieldsSearch.and("broadcastUri", AllFieldsSearch.entity().getBroadcastUri(), Op.EQ); - AllFieldsSearch.and("macAddress", AllFieldsSearch.entity().getMacAddress(), Op.EQ); AllFieldsSearch.done(); IpSearch = createSearchBuilder(String.class); @@ -200,11 +199,4 @@ public class NicDaoImpl extends GenericDaoBase implements NicDao { sc.setParameters("address", ip4Address); return findOneBy(sc); } - - @Override - public NicVO findByMacAddress(String macAddress) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("macAddress", macAddress); - return findOneBy(sc); - } } diff --git a/server/src/com/cloud/vm/dao/UserVmData.java b/server/src/com/cloud/vm/dao/UserVmData.java index 82c737c0e5b..674fc005a85 100644 --- a/server/src/com/cloud/vm/dao/UserVmData.java +++ b/server/src/com/cloud/vm/dao/UserVmData.java @@ -21,7 +21,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import com.cloud.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; public class UserVmData { private Long id; diff --git a/server/test/com/cloud/api/APITest.java b/server/test/com/cloud/api/APITest.java new file mode 100644 index 00000000000..69c488f5a10 --- /dev/null +++ b/server/test/com/cloud/api/APITest.java @@ -0,0 +1,189 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.io.BufferedReader; +import java.io.EOFException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Iterator; + +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.Gson; + +/** + * Base class for API Test + * + * @author Min Chen + * + */ +public abstract class APITest { + + protected String rootUrl = "http://localhost:8080/client/api"; + protected String sessionKey = null; + protected String cookieToSent = null; + + + /** + * Sending an api request through Http GET + * @param command command name + * @param params command query parameters in a HashMap + * @return http request response string + */ + protected String sendRequest(String command, HashMap params){ + try { + // Construct query string + StringBuilder sBuilder = new StringBuilder(); + sBuilder.append("command="); + sBuilder.append(command); + if ( params != null && params.size() > 0){ + Iterator keys = params.keySet().iterator(); + while (keys.hasNext()){ + String key = keys.next(); + sBuilder.append("&"); + sBuilder.append(key); + sBuilder.append("="); + sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8")); + } + } + + // Construct request url + String reqUrl = rootUrl + "?" + sBuilder.toString(); + + // Send Http GET request + URL url = new URL(reqUrl); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + if ( !command.equals("login") && cookieToSent != null){ + // add the cookie to a request + conn.setRequestProperty("Cookie", cookieToSent); + } + conn.connect(); + + + if ( command.equals("login")){ + // if it is login call, store cookie + String headerName=null; + for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) { + if (headerName.equals("Set-Cookie")) { + String cookie = conn.getHeaderField(i); + cookie = cookie.substring(0, cookie.indexOf(";")); + String cookieName = cookie.substring(0, cookie.indexOf("=")); + String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length()); + cookieToSent = cookieName + "=" + cookieValue; + } + } + } + + // Get the response + StringBuilder response = new StringBuilder(); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + try { + while ((line = rd.readLine()) != null) { + response.append(line); + } + } catch (EOFException ex) { + // ignore this exception + System.out.println("EOF exception due to java bug"); + } + rd.close(); + + + + return response.toString(); + + } catch (Exception e) { + throw new CloudRuntimeException("Problem with sending api request", e); + } + } + + protected String createMD5String(String password) { + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Error", e); + } + + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + + // make sure our MD5 hash value is 32 digits long... + StringBuffer sb = new StringBuffer(); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + for (int i = 0; i < padding; i++) { + sb.append('0'); + } + sb.append(pwStr); + return sb.toString(); + } + + + protected Object fromSerializedString(String result, Class repCls) { + try { + if (result != null && !result.isEmpty()) { + + // get real content + int start = result.indexOf('{', result.indexOf('{') + 1); // find the second { + if ( start < 0 ){ + throw new CloudRuntimeException("Response format is wrong: " + result); + } + int end = result.lastIndexOf('}', result.lastIndexOf('}')-1); // find the second } backwards + if ( end < 0 ){ + throw new CloudRuntimeException("Response format is wrong: " + result); + } + String content = result.substring(start, end+1); + Gson gson = ApiGsonHelper.getBuilder().create(); + return gson.fromJson(content, repCls); + } + return null; + } catch (RuntimeException e) { + throw new CloudRuntimeException("Caught runtime exception when doing GSON deserialization on: " + result, e); + } + } + + /** + * Login call + * @param username user name + * @param password password (plain password, we will do MD5 hash here for you) + * @return login response string + */ + protected void login(String username, String password) + { + //String md5Psw = createMD5String(password); + // send login request + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("username", username); + params.put("password", password); + String result = this.sendRequest("login", params); + LoginResponse loginResp = (LoginResponse)fromSerializedString(result, LoginResponse.class); + sessionKey = loginResp.getSessionkey(); + + } +} diff --git a/server/test/com/cloud/api/ListPerfTest.java b/server/test/com/cloud/api/ListPerfTest.java new file mode 100644 index 00000000000..eb98d9187fe --- /dev/null +++ b/server/test/com/cloud/api/ListPerfTest.java @@ -0,0 +1,168 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import java.util.HashMap; + +import org.junit.Before; +import org.junit.Test; + + +/** + * Test fixture to do performance test for list command + * Currently we commented out this test suite since it requires a real MS and Db running. + * + * @author Min Chen + * + */ +public class ListPerfTest extends APITest { + + + + @Before + public void setup(){ + // always login for each testcase + login("admin", "password"); + } + + @Test + public void testListVM(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVirtualMachines", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list VM: " + (after - before) + " ms"); + + } + + @Test + public void testListVMXML(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVirtualMachines", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list VM: " + (after - before) + " ms"); + + } + + @Test + public void testListRouter(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listRouters", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Routers: " + (after - before) + " ms"); + + } + + @Test + public void testListRouterXML(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listRouters", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Routers: " + (after - before) + " ms"); + + } + + @Test + public void testListHosts(){ + // issue list Hosts calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listHosts", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Hosts: " + (after - before) + " ms"); + + } + + @Test + public void testListVolumes(){ + // issue list Volumes calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVolumes", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Volumes: " + (after - before) + " ms"); + + } + + @Test + public void testListAccounts(){ + // issue list Accounts calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listAccounts", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Accounts: " + (after - before) + " ms"); + + } + + @Test + public void testListUsers(){ + // issue list Users calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listUsers", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Users: " + (after - before) + " ms"); + + } + + @Test + public void testListStoragePools(){ + // issue list Storage pool calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listStoragePools", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list StoragePools: " + (after - before) + " ms"); + + } + + + +} diff --git a/server/test/com/cloud/api/LoginResponse.java b/server/test/com/cloud/api/LoginResponse.java new file mode 100644 index 00000000000..097ae42c999 --- /dev/null +++ b/server/test/com/cloud/api/LoginResponse.java @@ -0,0 +1,142 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.api; + +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +/** + * Login Response object + * + * @author Min Chen + * + */ +public class LoginResponse extends BaseResponse { + + @SerializedName("timeout") + @Param(description = "session timeout period") + private String timeout; + + @SerializedName("sessionkey") + @Param(description = "login session key") + private String sessionkey; + + @SerializedName("username") + @Param(description = "login username") + private String username; + + @SerializedName("userid") + @Param(description = "login user internal uuid") + private String userid; + + @SerializedName("firstname") + @Param(description = "login user firstname") + private String firstname; + + @SerializedName("lastname") + @Param(description = "login user lastname") + private String lastname; + + @SerializedName("account") + @Param(description = "login user account type") + private String account; + + @SerializedName("domainid") + @Param(description = "login user domain id") + private String domainid; + + @SerializedName("type") + @Param(description = "login user type") + private int type; + + public String getTimeout() { + return timeout; + } + + public void setTimeout(String timeout) { + this.timeout = timeout; + } + + public String getSessionkey() { + return sessionkey; + } + + public void setSessionkey(String sessionkey) { + this.sessionkey = sessionkey; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getAccount() { + return account; + } + + public void setAccount(String account) { + this.account = account; + } + + public String getDomainid() { + return domainid; + } + + public void setDomainid(String domainid) { + this.domainid = domainid; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + + +} diff --git a/server/test/com/cloud/keystore/KeystoreTest.java b/server/test/com/cloud/keystore/KeystoreTest.java index e0e21268184..47212c12cca 100644 --- a/server/test/com/cloud/keystore/KeystoreTest.java +++ b/server/test/com/cloud/keystore/KeystoreTest.java @@ -16,34 +16,22 @@ // under the License. package com.cloud.keystore; -import java.security.KeyStore; -import java.util.Date; -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import junit.framework.TestCase; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; -import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiSerializerHelper; -import com.cloud.api.response.AlertResponse; -import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.UserVmResponse; -import com.cloud.configuration.DefaultInterceptorLibrary; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.MockComponentLocator; -import com.cloud.utils.security.CertificateHelper; +import org.apache.cloudstack.api.response.AlertResponse; +import org.apache.cloudstack.api.response.UserVmResponse; public class KeystoreTest extends TestCase { private final static Logger s_logger = Logger.getLogger(KeystoreTest.class); - private String keyContent = - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALV5vGlkiWwoZX4hTRplPXP8qtST\n" + - "hwZhko8noeY5vf8ECwmd+vrCTw/JvnOtkx/8oYNbg/SeUt1EfOsk6gqJdBblGFBZRMcUJlIpqE9z\n" + + private String keyContent = + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALV5vGlkiWwoZX4hTRplPXP8qtST\n" + + "hwZhko8noeY5vf8ECwmd+vrCTw/JvnOtkx/8oYNbg/SeUt1EfOsk6gqJdBblGFBZRMcUJlIpqE9z\n" + "uv68U9G8Gfi/qvRSY336hibw0J5bZ4vn1QqmyHDB+Czea9AjFUV7AEVG15+vED7why+/AgMBAAEC\n" + "gYBmFBPnNKYYMKDmUdUNA+WNWJK/ADzzWe8WlzR6TACTcbLDthl289WFC/YVG42mcHRpbxDKiEQU\n" + "MnIR0rHTO34Qb/2HcuyweStU2gqR6omxBvMnFpJr90nD1HcOMJzeLHsphau0/EmKKey+gk4PyieD\n" + @@ -54,8 +42,8 @@ public class KeystoreTest extends TestCase { "/DURBUn+1l5pyCKrZnDbvaALSLATLvjmFTuGjoHszy2OeKnOZmEqExWnKKE/VYuPyhy6V7i3TwJA\n" + "f8skDgtPK0OsBCa6IljPaHoWBjPc4kFkSTSS1d56hUcWSikTmiuKdLyBb85AADSZYsvHWrte4opN\n" + "dhNukMJuRA==\n"; - - private String certContent = + + private String certContent = "-----BEGIN CERTIFICATE-----\n" + "MIIE3jCCA8agAwIBAgIFAqv56tIwDQYJKoZIhvcNAQEFBQAwgcoxCzAJBgNVBAYT\n" + "AlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYD\n" + @@ -85,27 +73,27 @@ public class KeystoreTest extends TestCase { "k0fLF4+i/pt9hVCz0QrZ28RUhXf825+EOL0Gw+Uzt+7RV2cCaJrlu4cDrDom2FRy\n" + "E8I=\n" + "-----END CERTIFICATE-----\n"; - + @Override @Before public void setUp() { -/* +/* MockComponentLocator locator = new MockComponentLocator("management-server"); locator.addDao("keystoreDao", KeystoreDaoImpl.class); locator.addManager("KeystoreManager", KeystoreManagerImpl.class); locator.makeActive(new DefaultInterceptorLibrary()); -*/ +*/ } - + @Override @After public void tearDown() throws Exception { } -/* +/* public void testKeystoreSave() throws Exception { KeystoreVO ksVo; - + ComponentLocator locator = ComponentLocator.getCurrentLocator(); KeystoreDao ksDao = locator.getDao(KeystoreDao.class); @@ -115,18 +103,18 @@ public class KeystoreTest extends TestCase { assertTrue(ksVo.getCertificate().equals("CPVMCertificate")); assertTrue(ksVo.getKey().equals("KeyForCertificate")); assertTrue(ksVo.getDomainSuffix().equals("realhostip.com")); - + ksDao.save("CPVMCertificate", "CPVMCertificate Again", "KeyForCertificate Again", "again.realhostip.com"); - + ksVo = ksDao.findByName("CPVMCertificate"); assertTrue(ksVo != null); assertTrue(ksVo.getCertificate().equals("CPVMCertificate Again")); assertTrue(ksVo.getKey().equals("KeyForCertificate Again")); assertTrue(ksVo.getDomainSuffix().equals("again.realhostip.com")); - + ksDao.expunge(ksVo.getId()); } - + public void testStripeKey() throws Exception { Pattern regex = Pattern.compile("(^[\\-]+[^\\-]+[\\-]+[\\n]?)([^\\-]+)([\\-]+[^\\-]+[\\-]+$)"); Matcher m = regex.matcher("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAm4bLUORp9oM65GV9XrPrbs+K563DjUR1M8mP1HaE+Y4lX5pk\nvQjC/xoEqSs5pxDDWXAkoexvxij8A4AWcsKU1Q+ep2E+GcytBoz8XINGvgb8cQNn\n/4PlVWKp7j5SDDNCfleYvmiRn8k6P4mxVJOHKzwb/IwQcKghyqAF1w==\n-----END RSA PRIVATE KEY-----"); @@ -138,19 +126,19 @@ public class KeystoreTest extends TestCase { assertTrue(false); } } - + public void testKeystoreManager() throws Exception { ComponentLocator locator = ComponentLocator.getCurrentLocator(); - + KeystoreManagerImpl ksMgr = ComponentLocator.inject(KeystoreManagerImpl.class); assertTrue(ksMgr.configure("TaskManager", new HashMap())); assertTrue(ksMgr.start()); - + ksMgr.saveCertificate("CPVMCertificate", certContent, keyContent, "realhostip.com"); - + byte[] ksBits = ksMgr.getKeystoreBits("CPVMCertificate", "realhostip", "vmops.com"); assertTrue(ksBits != null); - + try { KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com"); assertTrue(ks != null); @@ -162,11 +150,11 @@ public class KeystoreTest extends TestCase { KeystoreVO ksVo = ksDao.findByName("CPVMCertificate"); ksDao.expunge(ksVo.getId()); } -*/ +*/ public void testUuid() { UserVmResponse vm = new UserVmResponse(); - vm.setId(3L); -/* + vm.setId(Long.toString(3L)); +/* vm.setAccountName("admin"); vm.setName("i-2-3-KY"); vm.setDisplayName("i-2-3-KY"); @@ -177,18 +165,18 @@ public class KeystoreTest extends TestCase { vm.setZoneId(1L); vm.setZoneName("KY"); vm.setHostId(1L); - + vm.setObjectName("virtualmachine"); -*/ +*/ String result = ApiSerializerHelper.toSerializedStringOld(vm); - // String result = "com.cloud.api.response.UserVmResponse/virtualmachine/{\"id\":{\"_tableName\":\"vm_instance\",\"_value\":3},\"name\":\"i-2-3-KY\",\"displayname\":\"i-2-3-KY\",\"account\":\"admin\",\"projectid\":{\"_tableName\":\"projects\"},\"domainid\":{\"_tableName\":\"domain\",\"_value\":1},\"domain\":\"ROOT\",\"created\":\"2011-11-02T21:54:07-0700\",\"state\":\"Running\",\"haenable\":false,\"groupid\":{\"_tableName\":\"instance_group\"},\"zoneid\":{\"_tableName\":\"data_center\",\"_value\":1},\"zonename\":\"KY\",\"hostid\":{\"_tableName\":\"host\",\"_value\":1},\"hostname\":\"xenserver-basic\",\"templateid\":{\"_tableName\":\"vm_template\",\"_value\":2},\"templatename\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"templatedisplaytext\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"passwordenabled\":false,\"isoid\":{\"_tableName\":\"vm_template\"},\"serviceofferingid\":{\"_tableName\":\"disk_offering\",\"_value\":7},\"serviceofferingname\":\"Small Instance\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"guestosid\":{\"_tableName\":\"guest_os\",\"_value\":12},\"rootdeviceid\":0,\"rootdevicetype\":\"NetworkFilesystem\",\"securitygroup\":[],\"jobid\":{\"_tableName\":\"async_job\"},\"nic\":[{\"id\":7,\"networkid\":200,\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\",\"ipaddress\":\"10.1.1.116\",\"isolationuri\":\"vlan://1699\",\"broadcasturi\":\"vlan://1699\",\"traffictype\":\"Guest\",\"type\":\"Virtual\",\"isdefault\":true,\"macaddress\":\"02:00:39:a7:00:01\"}],\"hypervisor\":\"XenServer\"}"; + // String result = "org.apache.cloudstack.api.response.UserVmResponse/virtualmachine/{\"id\":{\"_tableName\":\"vm_instance\",\"_value\":3},\"name\":\"i-2-3-KY\",\"displayname\":\"i-2-3-KY\",\"account\":\"admin\",\"projectid\":{\"_tableName\":\"projects\"},\"domainid\":{\"_tableName\":\"domain\",\"_value\":1},\"domain\":\"ROOT\",\"created\":\"2011-11-02T21:54:07-0700\",\"state\":\"Running\",\"haenable\":false,\"groupid\":{\"_tableName\":\"instance_group\"},\"zoneid\":{\"_tableName\":\"data_center\",\"_value\":1},\"zonename\":\"KY\",\"hostid\":{\"_tableName\":\"host\",\"_value\":1},\"hostname\":\"xenserver-basic\",\"templateid\":{\"_tableName\":\"vm_template\",\"_value\":2},\"templatename\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"templatedisplaytext\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"passwordenabled\":false,\"isoid\":{\"_tableName\":\"vm_template\"},\"serviceofferingid\":{\"_tableName\":\"disk_offering\",\"_value\":7},\"serviceofferingname\":\"Small Instance\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"guestosid\":{\"_tableName\":\"guest_os\",\"_value\":12},\"rootdeviceid\":0,\"rootdevicetype\":\"NetworkFilesystem\",\"securitygroup\":[],\"jobid\":{\"_tableName\":\"async_job\"},\"nic\":[{\"id\":7,\"networkid\":200,\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\",\"ipaddress\":\"10.1.1.116\",\"isolationuri\":\"vlan://1699\",\"broadcasturi\":\"vlan://1699\",\"traffictype\":\"Guest\",\"type\":\"Virtual\",\"isdefault\":true,\"macaddress\":\"02:00:39:a7:00:01\"}],\"hypervisor\":\"XenServer\"}"; System.out.println(result); //Object obj = ApiSerializerHelper.fromSerializedString(result); AlertResponse alert = new AlertResponse(); - alert.setId(100L); + alert.setId("100"); alert.setDescription("Hello"); - + result = ApiSerializerHelper.toSerializedStringOld(alert); System.out.println(result); ApiSerializerHelper.fromSerializedString(result); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index cfaa16971a6..408cfd05cf7 100755 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -16,19 +16,11 @@ // under the License. package com.cloud.network; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.ejb.Local; -import javax.naming.ConfigurationException; - -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; @@ -48,11 +40,16 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; +import com.cloud.network.element.RemoteAccessVPNServiceProvider; +import com.cloud.network.element.Site2SiteVpnServiceProvider; +import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.element.UserDataServiceProvider; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; @@ -119,6 +116,12 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS return null; } + @Override + public Network getNetwork(String networkUuid) { + // TODO Auto-generated method stub + return null; + } + @Override public IpAddress getIp(long id) { // TODO Auto-generated method stub @@ -786,4 +789,44 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS // TODO Auto-generated method stub return null; } + + /* (non-Javadoc) + * @see com.cloud.network.NetworkManager#getNetworkLockTimeout() + */ + @Override + public int getNetworkLockTimeout() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isNetworkInlineMode(Network network) { + // TODO Auto-generated method stub + return false; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getProvidersForServiceInNetwork(Network network, + Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRuleCountForIp(Long addressId, Purpose purpose, State state) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } } diff --git a/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java b/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java index 9c3e3310403..c7c5513b6b2 100644 --- a/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java +++ b/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java @@ -28,6 +28,7 @@ import org.junit.Before; import org.junit.Ignore; import com.cloud.agent.MockAgentManagerImpl; +import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; import com.cloud.configuration.DefaultInterceptorLibrary; import com.cloud.configuration.dao.ConfigurationDaoImpl; import com.cloud.domain.dao.DomainDaoImpl; @@ -67,6 +68,7 @@ public class SecurityGroupManagerImpl2Test extends TestCase { locator.addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); locator.addDao("SecurityGroupRuleDao", SecurityGroupRuleDaoImpl.class); + locator.addDao("SecurityGroupJoinDao", SecurityGroupJoinDaoImpl.class); locator.addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class); locator.addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class); locator.addDao("UserVmDao", UserVmDaoImpl.class); diff --git a/server/test/com/cloud/projects/MockProjectManagerImpl.java b/server/test/com/cloud/projects/MockProjectManagerImpl.java index d8bce2fcf81..309fa45d660 100644 --- a/server/test/com/cloud/projects/MockProjectManagerImpl.java +++ b/server/test/com/cloud/projects/MockProjectManagerImpl.java @@ -22,6 +22,10 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; @@ -105,21 +109,6 @@ public class MockProjectManagerImpl implements ProjectManager, Manager { return false; } - @Override - public Pair, Integer> listProjectAccounts(long projectId, - String accountName, String role, Long startIndex, Long pageSizeVal) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Pair, Integer> listProjectInvitations(Long id, - Long projectId, String accountName, Long domainId, String state, - boolean activeOnly, Long startIndex, Long pageSizeVal, - boolean isRecursive, boolean listAll) { - // TODO Auto-generated method stub - return null; - } @Override public boolean updateInvitation(long projectId, String accountName, @@ -221,16 +210,16 @@ public class MockProjectManagerImpl implements ProjectManager, Manager { return false; } - /* (non-Javadoc) - * @see com.cloud.projects.ProjectService#listProjects(java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Long, java.lang.String, java.lang.Long, java.lang.Long, boolean, boolean, java.util.Map) - */ + + @Override - public Pair, Integer> listProjects(Long id, String name, String displayText, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, - boolean isRecursive, Map tags) { + public long getInvitationTimeout() { // TODO Auto-generated method stub - return null; + return 0; } - + + + @Override public Project findByProjectAccountIdIncludingRemoved(long projectAccountId) { return null; diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index 08234fda0a0..550304adfff 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -22,14 +22,16 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import com.cloud.api.query.vo.ControlledViewEntity; + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; + import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; @@ -297,18 +299,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS return null; } - @Override - public Pair, Integer> searchForAccounts(ListAccountsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Pair, Integer> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { - // TODO Auto-generated method stub - return null; - } - @Override public boolean enableAccount(long accountId) { // TODO Auto-generated method stub @@ -319,14 +309,14 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS public void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { // TODO Auto-generated method stub - + } @Override public void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { // TODO Auto-generated method stub - + } @Override @@ -334,6 +324,18 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS // TODO Auto-generated method stub } + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + /* (non-Javadoc) * @see com.cloud.user.AccountService#getUserByApiKey(java.lang.String) */ @@ -343,4 +345,9 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS return null; } + @Override + public RoleType getRoleType(Account account) { + return null; + } + } diff --git a/server/test/com/cloud/user/MockDomainManagerImpl.java b/server/test/com/cloud/user/MockDomainManagerImpl.java index c5ff30524c4..0fe259d5c77 100644 --- a/server/test/com/cloud/user/MockDomainManagerImpl.java +++ b/server/test/com/cloud/user/MockDomainManagerImpl.java @@ -23,8 +23,8 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.exception.PermissionDeniedException; @@ -46,6 +46,12 @@ public class MockDomainManagerImpl implements Manager, DomainManager, DomainSer return null; } + @Override + public Domain getDomain(String uuid) { + // TODO Auto-generated method stub + return null; + } + @Override public boolean isChildDomain(Long parentId, Long childId) { // TODO Auto-generated method stub diff --git a/server/test/com/cloud/vm/MockUserVmManagerImpl.java b/server/test/com/cloud/vm/MockUserVmManagerImpl.java index 35ee1396504..27508b14c5b 100644 --- a/server/test/com/cloud/vm/MockUserVmManagerImpl.java +++ b/server/test/com/cloud/vm/MockUserVmManagerImpl.java @@ -28,22 +28,24 @@ import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AssignVMCmd; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.CreateVMGroupCmd; -import com.cloud.api.commands.DeleteVMGroupCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DestroyVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.ListVMsCmd; -import com.cloud.api.commands.RebootVMCmd; -import com.cloud.api.commands.RecoverVMCmd; -import com.cloud.api.commands.ResetVMPasswordCmd; -import com.cloud.api.commands.RestoreVMCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpdateVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import com.cloud.api.query.vo.UserVmJoinVO; + +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import com.cloud.dc.DataCenter; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; @@ -192,7 +194,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana } @Override - public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { // TODO Auto-generated method stub return null; } @@ -400,11 +402,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana return null; } - @Override - public Pair, Integer> searchForUserVMs(ListVMsCmd cmd) { - // TODO Auto-generated method stub - return null; - } + @Override public Pair> startVirtualMachine(long vmId, Long hostId, Map additionalParams) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { @@ -415,7 +413,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana @Override public void prepareStop(VirtualMachineProfile profile) { // TODO Auto-generated method stub - + } /* (non-Javadoc) diff --git a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java index 2a2588629b6..3989ecfd0e3 100644 --- a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java +++ b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java @@ -24,26 +24,24 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import javax.naming.NamingException; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; import com.cloud.configuration.Configuration; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationService; @@ -84,7 +82,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi NetworkOfferingDao _ntwkOffDao; /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateConfiguration(com.cloud.api.commands.UpdateCfgCmd) + * @see com.cloud.configuration.ConfigurationService#updateConfiguration(org.apache.cloudstack.api.commands.UpdateCfgCmd) */ @Override public Configuration updateConfiguration(UpdateCfgCmd cmd) { @@ -93,7 +91,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createServiceOffering(com.cloud.api.commands.CreateServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createServiceOffering(org.apache.cloudstack.api.commands.CreateServiceOfferingCmd) */ @Override public ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd) { @@ -102,7 +100,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateServiceOffering(com.cloud.api.commands.UpdateServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateServiceOffering(org.apache.cloudstack.api.commands.UpdateServiceOfferingCmd) */ @Override public ServiceOffering updateServiceOffering(UpdateServiceOfferingCmd cmd) { @@ -111,7 +109,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteServiceOffering(com.cloud.api.commands.DeleteServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteServiceOffering(org.apache.cloudstack.api.commands.DeleteServiceOfferingCmd) */ @Override public boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd) { @@ -120,7 +118,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateDiskOffering(com.cloud.api.commands.UpdateDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateDiskOffering(org.apache.cloudstack.api.commands.UpdateDiskOfferingCmd) */ @Override public DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd) { @@ -129,7 +127,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteDiskOffering(com.cloud.api.commands.DeleteDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteDiskOffering(org.apache.cloudstack.api.commands.DeleteDiskOfferingCmd) */ @Override public boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd) { @@ -138,7 +136,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createDiskOffering(com.cloud.api.commands.CreateDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createDiskOffering(org.apache.cloudstack.api.commands.CreateDiskOfferingCmd) */ @Override public DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd) { @@ -156,7 +154,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#editPod(com.cloud.api.commands.UpdatePodCmd) + * @see com.cloud.configuration.ConfigurationService#editPod(org.apache.cloudstack.api.commands.UpdatePodCmd) */ @Override public Pod editPod(UpdatePodCmd cmd) { @@ -165,7 +163,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deletePod(com.cloud.api.commands.DeletePodCmd) + * @see com.cloud.configuration.ConfigurationService#deletePod(org.apache.cloudstack.api.commands.DeletePodCmd) */ @Override public boolean deletePod(DeletePodCmd cmd) { @@ -174,7 +172,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createZone(com.cloud.api.commands.CreateZoneCmd) + * @see com.cloud.configuration.ConfigurationService#createZone(org.apache.cloudstack.api.commands.CreateZoneCmd) */ @Override public DataCenter createZone(CreateZoneCmd cmd) { @@ -183,7 +181,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#editZone(com.cloud.api.commands.UpdateZoneCmd) + * @see com.cloud.configuration.ConfigurationService#editZone(org.apache.cloudstack.api.commands.UpdateZoneCmd) */ @Override public DataCenter editZone(UpdateZoneCmd cmd) { @@ -192,7 +190,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteZone(com.cloud.api.commands.DeleteZoneCmd) + * @see com.cloud.configuration.ConfigurationService#deleteZone(org.apache.cloudstack.api.commands.DeleteZoneCmd) */ @Override public boolean deleteZone(DeleteZoneCmd cmd) { @@ -201,7 +199,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createVlanAndPublicIpRange(com.cloud.api.commands.CreateVlanIpRangeCmd) + * @see com.cloud.configuration.ConfigurationService#createVlanAndPublicIpRange(org.apache.cloudstack.api.commands.CreateVlanIpRangeCmd) */ @Override public Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { @@ -219,7 +217,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteVlanIpRange(com.cloud.api.commands.DeleteVlanIpRangeCmd) + * @see com.cloud.configuration.ConfigurationService#deleteVlanIpRange(org.apache.cloudstack.api.commands.DeleteVlanIpRangeCmd) */ @Override public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) { @@ -228,7 +226,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createNetworkOffering(com.cloud.api.commands.CreateNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createNetworkOffering(org.apache.cloudstack.api.commands.CreateNetworkOfferingCmd) */ @Override public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) { @@ -237,7 +235,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateNetworkOffering(com.cloud.api.commands.UpdateNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateNetworkOffering(org.apache.cloudstack.api.commands.UpdateNetworkOfferingCmd) */ @Override public NetworkOffering updateNetworkOffering(UpdateNetworkOfferingCmd cmd) { @@ -246,7 +244,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#searchForNetworkOfferings(com.cloud.api.commands.ListNetworkOfferingsCmd) + * @see com.cloud.configuration.ConfigurationService#searchForNetworkOfferings(org.apache.cloudstack.api.commands.ListNetworkOfferingsCmd) */ @Override public List searchForNetworkOfferings(ListNetworkOfferingsCmd cmd) { @@ -255,7 +253,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteNetworkOffering(com.cloud.api.commands.DeleteNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteNetworkOffering(org.apache.cloudstack.api.commands.DeleteNetworkOfferingCmd) */ @Override public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) { @@ -344,7 +342,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateLDAP(com.cloud.api.commands.LDAPConfigCmd) + * @see com.cloud.configuration.ConfigurationService#updateLDAP(org.apache.cloudstack.api.commands.LDAPConfigCmd) */ @Override public boolean updateLDAP(LDAPConfigCmd cmd) throws NamingException { @@ -353,7 +351,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#removeLDAP(com.cloud.api.commands.LDAPRemoveCmd) + * @see com.cloud.configuration.ConfigurationService#removeLDAP(org.apache.cloudstack.api.commands.LDAPRemoveCmd) */ @Override public boolean removeLDAP(LDAPRemoveCmd cmd) { diff --git a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java index 1a3cbae46ba..78d2ea2bbe0 100644 --- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java @@ -16,11 +16,6 @@ // under the License. package com.cloud.vpc; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; @@ -37,13 +32,11 @@ import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.NetworkServiceMapDao; -import com.cloud.network.element.NetworkElement; -import com.cloud.network.element.RemoteAccessVPNServiceProvider; -import com.cloud.network.element.Site2SiteVpnServiceProvider; -import com.cloud.network.element.UserDataServiceProvider; +import com.cloud.network.element.*; import com.cloud.network.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; @@ -56,6 +49,11 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.vm.*; import com.cloud.vpc.dao.MockVpcVirtualRouterElement; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; import org.apache.log4j.Logger; import javax.ejb.Local; @@ -558,7 +556,7 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M /* (non-Javadoc) - * @see com.cloud.network.NetworkService#listTrafficTypeImplementor(com.cloud.api.commands.ListTrafficTypeImplementorsCmd) + * @see com.cloud.network.NetworkService#listTrafficTypeImplementor(org.apache.cloudstack.api.commands.ListTrafficTypeImplementorsCmd) */ @Override public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { @@ -654,7 +652,7 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M /* (non-Javadoc) - * @see com.cloud.network.NetworkManager#setupNetwork(com.cloud.user.Account, com.cloud.offerings.NetworkOfferingVO, com.cloud.network.Network, com.cloud.deploy.DeploymentPlan, java.lang.String, java.lang.String, boolean, java.lang.Long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) + * @see com.cloud.network.NetworkManager#setupNetwork(com.cloud.user.Account, com.cloud.offerings.NetworkOfferingVO, com.cloud.network.Network, com.cloud.deploy.DeploymentPlan, java.lang.String, java.lang.String, boolean, java.lang.Long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) */ @Override public List setupNetwork(Account owner, NetworkOffering offering, Network predefined, @@ -819,7 +817,7 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M /* (non-Javadoc) - * @see com.cloud.network.NetworkManager#createGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) + * @see com.cloud.network.NetworkManager#createGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) */ @Override public Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, @@ -1261,6 +1259,33 @@ public class MockNetworkManagerImpl implements NetworkManager, NetworkService, M return null; } - + @Override + public boolean isNetworkInlineMode(Network network) { + // TODO Auto-generated method stub + return false; + } + @Override + public List getProvidersForServiceInNetwork(Network network, Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRuleCountForIp(Long addressId, Purpose purpose, State state) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } } diff --git a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java index cb052ed64e4..a0c7b70190c 100644 --- a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java +++ b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java @@ -70,6 +70,13 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag return 0; } + + @Override + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type) { + // TODO Auto-generated method stub + return 0; + } + /* (non-Javadoc) * @see com.cloud.user.ResourceLimitService#findCorrectResourceLimitForDomain(com.cloud.domain.Domain, com.cloud.configuration.Resource.ResourceType) */ @@ -85,7 +92,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void incrementResourceCount(long accountId, ResourceType type, Long... delta) { // TODO Auto-generated method stub - + } /* (non-Javadoc) @@ -94,7 +101,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void decrementResourceCount(long accountId, ResourceType type, Long... delta) { // TODO Auto-generated method stub - + } /* (non-Javadoc) @@ -103,7 +110,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException { // TODO Auto-generated method stub - + } /* (non-Javadoc) diff --git a/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java b/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java index 64db5bbfb79..c112f31f73b 100644 --- a/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java +++ b/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java @@ -22,17 +22,16 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.*; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnCustomerGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteCustomerGateway; @@ -49,7 +48,7 @@ import com.cloud.vm.DomainRouterVO; public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2SiteVpnService, Manager{ /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnGateway(com.cloud.api.commands.CreateVpnGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnGateway(org.apache.cloudstack.api.commands.CreateVpnGatewayCmd) */ @Override public Site2SiteVpnGateway createVpnGateway(CreateVpnGatewayCmd cmd) { @@ -58,7 +57,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createCustomerGateway(com.cloud.api.commands.CreateVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createCustomerGateway(org.apache.cloudstack.api.commands.CreateVpnCustomerGatewayCmd) */ @Override public Site2SiteCustomerGateway createCustomerGateway(CreateVpnCustomerGatewayCmd cmd) { @@ -85,7 +84,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnConnection(com.cloud.api.commands.CreateVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnConnection(org.apache.cloudstack.api.commands.CreateVpnConnectionCmd) */ @Override public Site2SiteVpnConnection createVpnConnection(CreateVpnConnectionCmd cmd) throws NetworkRuleConflictException { @@ -94,7 +93,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteCustomerGateway(com.cloud.api.commands.DeleteVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteCustomerGateway(org.apache.cloudstack.api.commands.DeleteVpnCustomerGatewayCmd) */ @Override public boolean deleteCustomerGateway(DeleteVpnCustomerGatewayCmd deleteVpnCustomerGatewayCmd) { @@ -103,7 +102,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnGateway(com.cloud.api.commands.DeleteVpnGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnGateway(org.apache.cloudstack.api.commands.DeleteVpnGatewayCmd) */ @Override public boolean deleteVpnGateway(DeleteVpnGatewayCmd deleteVpnGatewayCmd) { @@ -112,7 +111,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnConnection(com.cloud.api.commands.DeleteVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnConnection(org.apache.cloudstack.api.commands.DeleteVpnConnectionCmd) */ @Override public boolean deleteVpnConnection(DeleteVpnConnectionCmd deleteVpnConnectionCmd) throws ResourceUnavailableException { @@ -121,7 +120,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#resetVpnConnection(com.cloud.api.commands.ResetVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#resetVpnConnection(org.apache.cloudstack.api.commands.ResetVpnConnectionCmd) */ @Override public Site2SiteVpnConnection resetVpnConnection(ResetVpnConnectionCmd resetVpnConnectionCmd) throws ResourceUnavailableException { @@ -130,7 +129,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForCustomerGateways(com.cloud.api.commands.ListVpnCustomerGatewaysCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForCustomerGateways(org.apache.cloudstack.api.commands.ListVpnCustomerGatewaysCmd) */ @Override public Pair, Integer> searchForCustomerGateways(ListVpnCustomerGatewaysCmd listVpnCustomerGatewaysCmd) { @@ -139,7 +138,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnGateways(com.cloud.api.commands.ListVpnGatewaysCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnGateways(org.apache.cloudstack.api.commands.ListVpnGatewaysCmd) */ @Override public Pair, Integer> searchForVpnGateways(ListVpnGatewaysCmd listVpnGatewaysCmd) { @@ -148,7 +147,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnConnections(com.cloud.api.commands.ListVpnConnectionsCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnConnections(org.apache.cloudstack.api.commands.ListVpnConnectionsCmd) */ @Override public Pair, Integer> searchForVpnConnections(ListVpnConnectionsCmd listVpnConnectionsCmd) { @@ -157,7 +156,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#updateCustomerGateway(com.cloud.api.commands.UpdateVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#updateCustomerGateway(org.apache.cloudstack.api.commands.UpdateVpnCustomerGatewayCmd) */ @Override public Site2SiteCustomerGateway updateCustomerGateway(UpdateVpnCustomerGatewayCmd updateVpnCustomerGatewayCmd) { diff --git a/server/test/com/cloud/vpc/MockVpcManagerImpl.java b/server/test/com/cloud/vpc/MockVpcManagerImpl.java index 1f41395b16a..25799d19b9e 100644 --- a/server/test/com/cloud/vpc/MockVpcManagerImpl.java +++ b/server/test/com/cloud/vpc/MockVpcManagerImpl.java @@ -23,9 +23,9 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -242,7 +242,7 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcService#listPrivateGateway(com.cloud.api.commands.ListPrivateGatewaysCmd) + * @see com.cloud.network.vpc.VpcService#listPrivateGateway(org.apache.cloudstack.api.commands.ListPrivateGatewaysCmd) */ @Override public Pair, Integer> listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd) { @@ -287,7 +287,7 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcService#listStaticRoutes(com.cloud.api.commands.ListStaticRoutesCmd) + * @see com.cloud.network.vpc.VpcService#listStaticRoutes(org.apache.cloudstack.api.commands.ListStaticRoutesCmd) */ @Override public Pair, Integer> listStaticRoutes(ListStaticRoutesCmd cmd) { @@ -395,7 +395,7 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcManager#createVpcGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, long, com.cloud.user.Account) + * @see com.cloud.network.vpc.VpcManager#createVpcGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, long, com.cloud.user.Account) */ @Override public Network createVpcGuestNetwork(long ntwkOffId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork pNtwk, diff --git a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java index 509d9c72f73..7c9a5823516 100644 --- a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java +++ b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java @@ -351,4 +351,10 @@ public class MockNetworkDaoImpl extends GenericDaoBase implemen return null; } + @Override + public List listRedundantNetworks() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/setup/bindir/cloud-setup-databases.in b/setup/bindir/cloud-setup-databases.in index bd5a0ba11f3..e50aa29aa62 100755 --- a/setup/bindir/cloud-setup-databases.in +++ b/setup/bindir/cloud-setup-databases.in @@ -212,7 +212,7 @@ for full help ""), ) - for f in ["create-database","create-schema","create-database-premium","create-schema-premium"]: + for f in ["create-database","create-schema", "create-database-premium","create-schema-premium", "create-schema-view"]: p = os.path.join(self.dbFilesPath,"%s.sql"%f) if not os.path.exists(p): continue text = file(p).read() @@ -359,7 +359,7 @@ for example: if not os.path.exists(dbf): self.errorAndExit("Cannot find %s"%dbf) - coreSchemas = ['create-database.sql', 'create-schema.sql', 'templates.sql', 'create-index-fk.sql'] + coreSchemas = ['create-database.sql', 'create-schema.sql', 'create-schema-view.sql', 'templates.sql', 'create-index-fk.sql'] if not self.serversetup: coreSchemas.append('server-setup.sql') diff --git a/setup/db/create-schema-view.sql b/setup/db/create-schema-view.sql new file mode 100644 index 00000000000..bf04c1caa57 --- /dev/null +++ b/setup/db/create-schema-view.sql @@ -0,0 +1,821 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you under the Apache License, Version 2.0 (the +-- "License"); you may not use this file except in compliance +-- with the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. +use cloud; + +--- DB views for list api --- +DROP VIEW IF EXISTS `cloud`.`user_vm_view`; +CREATE VIEW `cloud`.`user_vm_view` AS +select +vm_instance.id id, +vm_instance.name name, +user_vm.display_name display_name, +user_vm.user_data user_data, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +instance_group.id instance_group_id, +instance_group.uuid instance_group_uuid, +instance_group.name instance_group_name, +vm_instance.uuid uuid, +vm_instance.last_host_id last_host_id, +vm_instance.vm_type type, +vm_instance.vnc_password vnc_password, +vm_instance.limit_cpu_use limit_cpu_use, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.ha_enabled ha_enabled, +vm_instance.hypervisor_type hypervisor_type, +vm_instance.instance_name instance_name, +vm_instance.guest_os_id guest_os_id, +guest_os.uuid guest_os_uuid, +vm_instance.pod_id pod_id, +host_pod_ref.uuid pod_uuid, +vm_instance.private_ip_address private_ip_address, +vm_instance.private_mac_address private_mac_address, +vm_instance.vm_type vm_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.is_security_group_enabled security_group_enabled, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.name template_name, +vm_template.display_text template_display_text, +vm_template.enable_password password_enabled, +iso.id iso_id, +iso.uuid iso_uuid, +iso.name iso_name, +iso.display_text iso_display_text, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +service_offering.cpu cpu, +service_offering.speed speed, +service_offering.ram_size ram_size, +disk_offering.name service_offering_name, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.pool_type pool_type, +volumes.id volume_id, +volumes.uuid volume_uuid, +volumes.device_id volume_device_id, +volumes.volume_type volume_type, +security_group.id security_group_id, +security_group.uuid security_group_uuid, +security_group.name security_group_name, +security_group.description security_group_description, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +user_ip_address.id public_ip_id, +user_ip_address.uuid public_ip_uuid, +user_ip_address.public_ip_address public_ip_address, +ssh_keypairs.keypair_name keypair_name, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user_vm +inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join guest_os on vm_instance.guest_os_id = guest_os.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id +left join instance_group on instance_group_vm_map.group_id=instance_group.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join vm_template iso on iso.id=user_vm.iso_id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id +left join security_group on security_group_vm_map.security_group_id=security_group.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join user_ip_address on user_ip_address.vm_id=vm_instance.id +left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" +left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value +left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`domain_router_view`; +CREATE VIEW domain_router_view AS +select +vm_instance.id id, +vm_instance.name name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +vm_instance.uuid uuid, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.pod_id pod_id, +vm_instance.instance_name instance_name, +host_pod_ref.uuid pod_uuid, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.dns1 dns1, +data_center.dns2 dns2, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +disk_offering.name service_offering_name, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.name network_name, +networks.network_domain network_domain, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id, +domain_router.template_version template_version, +domain_router.scripts_version scripts_version, +domain_router.is_redundant_router is_redundant_router, +domain_router.redundant_state redundant_state, +domain_router.stop_pending stop_pending +from domain_router +inner join vm_instance on vm_instance.id = domain_router.id +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`security_group_view`; +CREATE VIEW security_group_view AS +select +security_group.id id, +security_group.name name, +security_group.description description, +security_group.uuid uuid, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +security_group_rule.id rule_id, +security_group_rule.uuid rule_uuid, +security_group_rule.type rule_type, +security_group_rule.start_port rule_start_port, +security_group_rule.end_port rule_end_port, +security_group_rule.protocol rule_protocol, +security_group_rule.allowed_network_id rule_allowed_network_id, +security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, +security_group_rule.create_status rule_create_status, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from security_group +left join security_group_rule on security_group.id = security_group_rule.security_group_id +inner join account on security_group.account_id=account.id +inner join domain on security_group.domain_id=domain.id +left join projects on projects.project_account_id = security_group.account_id +left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" +left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; +CREATE VIEW resource_tag_view AS +select +resource_tags.id, +resource_tags.uuid, +resource_tags.key, +resource_tags.value, +resource_tags.resource_id, +resource_tags.resource_uuid, +resource_tags.resource_type, +resource_tags.customer, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from resource_tags +inner join account on resource_tags.account_id=account.id +inner join domain on resource_tags.domain_id=domain.id +left join projects on projects.project_account_id = resource_tags.account_id; + + +DROP VIEW IF EXISTS `cloud`.`event_view`; +CREATE VIEW event_view AS +select +event.id, +event.uuid, +event.type, +event.state, +event.description, +event.created, +event.level, +event.parameters, +event.start_id, +eve.uuid start_uuid, +event.user_id, +user.username user_name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from event +inner join account on event.account_id=account.id +inner join domain on event.domain_id=domain.id +inner join user on event.user_id = user.id +left join projects on projects.project_account_id = event.account_id +left join event eve on event.start_id = eve.id; + +DROP VIEW IF EXISTS `cloud`.`instance_group_view`; +CREATE VIEW instance_group_view AS +select +instance_group.id, +instance_group.uuid, +instance_group.name, +instance_group.removed, +instance_group.created, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from instance_group +inner join account on instance_group.account_id=account.id +inner join domain on account.domain_id=domain.id +left join projects on projects.project_account_id = instance_group.account_id; + +DROP VIEW IF EXISTS `cloud`.`user_view`; +CREATE VIEW user_view AS +select +user.id, +user.uuid, +user.username, +user.password, +user.firstname, +user.lastname, +user.email, +user.state, +user.api_key, +user.secret_key, +user.created, +user.removed, +user.timezone, +user.registration_token, +user.is_registered, +user.incorrect_login_attempts, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user +inner join account on user.account_id = account.id +inner join domain on account.domain_id=domain.id +left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; + + + + +DROP VIEW IF EXISTS `cloud`.`project_view`; +CREATE VIEW project_view AS +select +projects.id, +projects.uuid, +projects.name, +projects.display_text, +projects.state, +projects.removed, +projects.created, +account.account_name owner, +pacct.account_id, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer +from projects +inner join domain on projects.domain_id=domain.id +inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" +inner join account on account.id = project_account.account_id +left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" +left join project_account pacct on projects.id = pacct.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_account_view`; +CREATE VIEW project_account_view AS +select +project_account.id, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +project_account.account_role, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_account +inner join account on project_account.account_id = account.id +inner join domain on account.domain_id=domain.id +inner join projects on projects.id = project_account.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; +CREATE VIEW project_invitation_view AS +select +project_invitations.id, +project_invitations.uuid, +project_invitations.email, +project_invitations.created, +project_invitations.state, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_invitations +left join account on project_invitations.account_id = account.id +left join domain on project_invitations.domain_id=domain.id +left join projects on projects.id = project_invitations.project_id; + +DROP VIEW IF EXISTS `cloud`.`host_view`; +CREATE VIEW host_view AS +select +host.id, +host.uuid, +host.name, +host.status, +host.disconnected, +host.type, +host.private_ip_address, +host.version, +host.hypervisor_type, +host.hypervisor_version, +host.capabilities, +host.last_ping, +host.created, +host.removed, +host.resource_state, +host.mgmt_server_id, +host.cpus, +host.speed, +host.ram, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +host_tags.tag, +guest_os_category.id guest_os_category_id, +guest_os_category.uuid guest_os_category_uuid, +guest_os_category.name guest_os_category_name, +mem_caps.used_capacity memory_used_capacity, +mem_caps.reserved_capacity memory_reserved_capacity, +cpu_caps.used_capacity cpu_used_capacity, +cpu_caps.reserved_capacity cpu_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from host +left join cluster on host.cluster_id = cluster.id +left join data_center on host.data_center_id = data_center.id +left join host_pod_ref on host.pod_id = host_pod_ref.id +left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" +left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) +left join host_tags on host_tags.host_id = host.id +left join op_host_capacity mem_caps on host.id = mem_caps.host_id and mem_caps.capacity_type = 0 +left join op_host_capacity cpu_caps on host.id = cpu_caps.host_id and cpu_caps.capacity_type = 1 +left join async_job on async_job.instance_id = host.id and async_job.instance_type = "Host" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`volume_view`; +CREATE VIEW volume_view AS +select +volumes.id, +volumes.uuid, +volumes.name, +volumes.device_id, +volumes.volume_type, +volumes.size, +volumes.created, +volumes.state, +volumes.attached, +volumes.removed, +volumes.pod_id, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +vm_instance.id vm_id, +vm_instance.uuid vm_uuid, +vm_instance.name vm_name, +vm_instance.state vm_state, +vm_instance.vm_type, +user_vm.display_name vm_display_name, +volume_host_ref.size volume_host_size, +volume_host_ref.created volume_host_created, +volume_host_ref.format, +volume_host_ref.download_pct, +volume_host_ref.download_state, +volume_host_ref.error_str, +disk_offering.id disk_offering_id, +disk_offering.uuid disk_offering_uuid, +disk_offering.name disk_offering_name, +disk_offering.display_text disk_offering_display_text, +disk_offering.use_local_storage, +disk_offering.system_use, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.name pool_name, +cluster.hypervisor_type, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.extractable, +vm_template.type template_type, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from volumes +inner join account on volumes.account_id=account.id +inner join domain on volumes.domain_id=domain.id +left join projects on projects.project_account_id = account.id +left join data_center on volumes.data_center_id = data_center.id +left join vm_instance on volumes.instance_id = vm_instance.id +left join user_vm on user_vm.id = vm_instance.id +left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id +left join disk_offering on volumes.disk_offering_id = disk_offering.id +left join storage_pool on volumes.pool_id = storage_pool.id +left join cluster on storage_pool.cluster_id = cluster.id +left join vm_template on volumes.template_id = vm_template.id +left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" +left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; +CREATE VIEW account_netstats_view AS +SELECT account_id, +sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, +sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent +FROM user_statistics +group by account_id; + + +DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; +CREATE VIEW account_vmstats_view AS +SELECT account_id, state, count(*) as vmcount +from vm_instance +group by account_id, state; + +DROP VIEW IF EXISTS `cloud`.`free_ip_view`; +CREATE VIEW free_ip_view AS +select count(user_ip_address.id) free_ip +from user_ip_address +inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" +where state = "Free"; + +DROP VIEW IF EXISTS `cloud`.`account_view`; +CREATE VIEW account_view AS +select +account.id, +account.uuid, +account.account_name, +account.type, +account.state, +account.removed, +account.cleanup_needed, +account.network_domain, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +account_netstats_view.bytesReceived, +account_netstats_view.bytesSent, +vmlimit.max vmLimit, +vmcount.count vmTotal, +runningvm.vmcount runningVms, +stoppedvm.vmcount stoppedVms, +iplimit.max ipLimit, +ipcount.count ipTotal, +free_ip_view.free_ip ipFree, +volumelimit.max volumeLimit, +volumecount.count volumeTotal, +snapshotlimit.max snapshotLimit, +snapshotcount.count snapshotTotal, +templatelimit.max templateLimit, +templatecount.count templateTotal, +vpclimit.max vpcLimit, +vpccount.count vpcTotal, +projectlimit.max projectLimit, +projectcount.count projectTotal, +networklimit.max networkLimit, +networkcount.count networkTotal, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from free_ip_view, account +inner join domain on account.domain_id=domain.id +left join data_center on account.default_zone_id = data_center.id +left join account_netstats_view on account.id = account_netstats_view.account_id +left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" +left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" +left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" +left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" +left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" +left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" +left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" +left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" +left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" +left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" +left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" +left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" +left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" +left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" +left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" +left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" +left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" +left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" +left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`async_job_view`; +CREATE VIEW async_job_view AS +select +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +user.id user_id, +user.uuid user_uuid, +async_job.id, +async_job.uuid, +async_job.job_cmd, +async_job.job_status, +async_job.job_process_status, +async_job.job_result_code, +async_job.job_result, +async_job.created, +async_job.removed, +async_job.instance_type, +async_job.instance_id, +CASE +WHEN async_job.instance_type = 'Volume' THEN volumes.uuid +WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid +WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid +WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid +WHEN async_job.instance_type = 'Host' THEN host.uuid +WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid +WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid +WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid +WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid +WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid +WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid +WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid +WHEN async_job.instance_type = 'Account' THEN acct.uuid +WHEN async_job.instance_type = 'User' THEN us.uuid +WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid +WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid +WHEN async_job.instance_type = 'Counter' THEN counter.uuid +WHEN async_job.instance_type = 'Condition' THEN conditions.uuid +WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid +WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid +WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid +ELSE null +END instance_uuid +from async_job +left join account on async_job.account_id = account.id +left join domain on domain.id = account.domain_id +left join user on async_job.user_id = user.id +left join volumes on async_job.instance_id = volumes.id +left join vm_template on async_job.instance_id = vm_template.id +left join vm_instance on async_job.instance_id = vm_instance.id +left join snapshots on async_job.instance_id = snapshots.id +left join host on async_job.instance_id = host.id +left join storage_pool on async_job.instance_id = storage_pool.id +left join user_ip_address on async_job.instance_id = user_ip_address.id +left join security_group on async_job.instance_id = security_group.id +left join physical_network on async_job.instance_id = physical_network.id +left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id +left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id +left join firewall_rules on async_job.instance_id = firewall_rules.id +left join account acct on async_job.instance_id = acct.id +left join user us on async_job.instance_id = us.id +left join static_routes on async_job.instance_id = static_routes.id +left join vpc_gateways on async_job.instance_id = vpc_gateways.id +left join counter on async_job.instance_id = counter.id +left join conditions on async_job.instance_id = conditions.id +left join autoscale_policies on async_job.instance_id = autoscale_policies.id +left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id +left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; + +DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; +CREATE VIEW storage_pool_view AS +select +storage_pool.id, +storage_pool.uuid, +storage_pool.name, +storage_pool.status, +storage_pool.path, +storage_pool.pool_type, +storage_pool.host_address, +storage_pool.created, +storage_pool.removed, +storage_pool.capacity_bytes, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +storage_pool_details.name tag, +op_host_capacity.used_capacity disk_used_capacity, +op_host_capacity.reserved_capacity disk_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from storage_pool +left join cluster on storage_pool.cluster_id = cluster.id +left join data_center on storage_pool.data_center_id = data_center.id +left join host_pod_ref on storage_pool.pod_id = host_pod_ref.id +left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id and storage_pool_details.value = 'true' +left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 +left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; \ No newline at end of file diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index 1b6ee5df112..174f53cd7ba 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -166,6 +166,7 @@ CREATE TABLE `cloud`.`version` ( INDEX `i_version__version`(`version`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; + INSERT INTO `version` (`version`, `updated`, `step`) VALUES('4.1.0', now(), 'Complete'); CREATE TABLE `cloud`.`op_it_work` ( @@ -305,9 +306,9 @@ CREATE TABLE `cloud`.`network_offerings` ( `state` char(32) COMMENT 'state of the network offering that has Disabled value by default', `guest_type` char(32) COMMENT 'type of guest network that can be shared or isolated', `elastic_ip_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides elastic ip service', - `eip_associate_public_ip` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if public IP is associated with user VM creation by default when EIP service is enabled.', `elastic_lb_service` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides elastic lb service', `specify_ip_ranges` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if the network offering provides an ability to define ip ranges', + `inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering LB provider is in inline mode', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`), @@ -745,12 +746,10 @@ CREATE TABLE `cloud`.`load_balancer_stickiness_policies` ( CREATE TABLE `cloud`.`inline_load_balancer_nic_map` ( `id` bigint unsigned NOT NULL auto_increment, - `load_balancer_id` bigint unsigned NOT NULL, `public_ip_address` char(40) NOT NULL, `nic_id` bigint unsigned NULL COMMENT 'nic id', PRIMARY KEY (`id`), UNIQUE KEY (`nic_id`), - CONSTRAINT `fk_inline_load_balancer_nic_map__load_balancer_id` FOREIGN KEY(`load_balancer_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_inline_load_balancer_nic_map__nic_id` FOREIGN KEY(`nic_id`) REFERENCES `nics`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -1120,6 +1119,7 @@ CREATE TABLE `cloud`.`upload` ( `id` bigint unsigned NOT NULL auto_increment, `host_id` bigint unsigned NOT NULL, `type_id` bigint unsigned NOT NULL, + `uuid` varchar(40), `type` varchar(255), `mode` varchar(255), `created` DATETIME NOT NULL, @@ -1342,7 +1342,7 @@ CREATE TABLE `cloud`.`async_job` ( `session_key` varchar(64) COMMENT 'all async-job manage to apply session based security enforcement', `instance_type` varchar(64) COMMENT 'instance_type and instance_id work together to allow attaching an instance object to a job', `instance_id` bigint unsigned, - `job_cmd` varchar(64) NOT NULL COMMENT 'command name', + `job_cmd` varchar(255) NOT NULL COMMENT 'command name', `job_cmd_originator` varchar(64) COMMENT 'command originator', `job_cmd_info` text COMMENT 'command parameter info', `job_cmd_ver` int(1) COMMENT 'command version', @@ -2075,7 +2075,6 @@ CREATE TABLE `cloud`.`external_load_balancer_devices` ( `device_state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'state (enabled/disabled/shutdown) of the device', `allocation_state` varchar(32) NOT NULL DEFAULT 'Free' COMMENT 'Allocation state (Free/Shared/Dedicated/Provider) of the device', `is_dedicated` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if device/appliance is provisioned for dedicated use only', - `is_inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if load balancer will be used in in-line configuration with firewall', `is_managed` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if load balancer appliance is provisioned and its life cycle is managed by by cloudstack', `host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external load balancer device', `parent_host_id` bigint unsigned COMMENT 'if the load balancer appliance is cloudstack managed, then host id on which this appliance is provisioned', @@ -2539,9 +2538,10 @@ CREATE TABLE `cloud`.`autoscale_vmgroup_policy_map` ( INDEX `i_autoscale_vmgroup_policy_map__vmgroup_id`(`vmgroup_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (1,'snmp','Linux User CPU - percentage', '1.3.6.1.4.1.2021.11.9.0', now()); -INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (2,'snmp','Linux System CPU - percentage', '1.3.6.1.4.1.2021.11.10.0', now()); -INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (3,'snmp','Linux CPU Idle - percentage', '1.3.6.1.4.1.2021.11.11.0', now()); -INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (100,'netscaler','Response Time - microseconds', 'RESPTIME', now()); +INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (1, UUID(), 'snmp','Linux User CPU - percentage', '1.3.6.1.4.1.2021.11.9.0', now()); +INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (2, UUID(), 'snmp','Linux System CPU - percentage', '1.3.6.1.4.1.2021.11.10.0', now()); +INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (3, UUID(), 'snmp','Linux CPU Idle - percentage', '1.3.6.1.4.1.2021.11.11.0', now()); +INSERT INTO `cloud`.`counter` (id, uuid, source, name, value,created) VALUES (100, UUID(), 'netscaler','Response Time - microseconds', 'RESPTIME', now()); SET foreign_key_checks = 1; + diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql index b09ebb94fea..c115135d006 100644 --- a/setup/db/db/schema-40to410.sql +++ b/setup/db/db/schema-40to410.sql @@ -52,11 +52,15 @@ CREATE TABLE `cloud`.`template_s3_ref` ( INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 's3.enable', 'false', 'enable s3'); +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'router.check.poolsize' , '10', 'Numbers of threads using to check redundant router status.'); + ALTER TABLE `cloud`.`snapshots` ADD COLUMN `s3_id` bigint unsigned COMMENT 'S3 to which this snapshot will be stored'; ALTER TABLE `cloud`.`snapshots` ADD CONSTRAINT `fk_snapshots__s3_id` FOREIGN KEY `fk_snapshots__s3_id` (`s3_id`) REFERENCES `s3` (`id`); -ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `eip_associate_public_ip` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'true if public IP is associated with user VM creation by default when EIP service is enabled.' AFTER `elastic_ip_service`; +ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering LB provider is in inline mode'; + +ALTER TABLE `cloud`.`external_load_balancer_devices` DROP COLUMN `is_inline`; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network','DEFAULT','NetworkManager','network.dhcp.nondefaultnetwork.setgateway.guestos','Windows','The guest OS\'s name start with this fields would result in DHCP server response gateway information even when the network it\'s on is not default network. Names are separated by comma.'); @@ -65,3 +69,878 @@ ALTER TABLE `sync_queue` ADD `queue_size` SMALLINT NOT NULL DEFAULT '0' COMMENT ALTER TABLE `sync_queue` ADD `queue_size_limit` SMALLINT NOT NULL DEFAULT '1' COMMENT 'max number of items the queue can process concurrently'; ALTER TABLE `sync_queue_item` ADD `queue_proc_time` DATETIME NOT NULL COMMENT 'when processing started for the item' AFTER `queue_proc_number`; + +ALTER TABLE `cloud`.`inline_load_balancer_nic_map` DROP FOREIGN KEY fk_inline_load_balancer_nic_map__load_balancer_id; + +ALTER TABLE `cloud`.`inline_load_balancer_nic_map` DROP COLUMN load_balancer_id; + +ALTER TABLE upload ADD uuid VARCHAR(40); +ALTER TABLE async_job modify job_cmd VARCHAR(255); + +-- populate uuid column with db id if uuid is null +UPDATE `cloud`.`account` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`alert` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`async_job` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`cluster` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`data_center` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`disk_offering` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`domain` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`event` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_firewall_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_load_balancer_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_nicira_nvp_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`firewall_rules` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`guest_os` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`guest_os_category` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`host` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`host_pod_ref` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`hypervisor_capabilities` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`instance_group` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`load_balancer_stickiness_policies` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_external_firewall_device_map` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_external_lb_device_map` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_offerings` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`networks` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`nics` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network_service_providers` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network_traffic_types` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`port_profile` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`project_invitations` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`projects` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`resource_tags` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_customer_gateway` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_vpn_connection` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_vpn_gateway` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`security_group` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`security_group_rule` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`snapshot_schedule` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`snapshots` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`static_routes` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`storage_pool` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`swift` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`upload` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user_ip_address` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user_vm_temp` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`virtual_router_providers` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`virtual_supervisor_module` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vlan` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vm_instance` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vm_template` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc_gateways` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc_offerings` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpn_users` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`volumes` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_vmgroups` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_vmprofiles` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_policies` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`counter` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`conditions` set uuid=id WHERE uuid is NULL; + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', '"detail.batch.query.size"', '2000', 'Default entity detail batch query size for listing'); + +--- DB views for list api --- +use cloud; + +DROP VIEW IF EXISTS `cloud`.`user_vm_view`; +CREATE VIEW `cloud`.`user_vm_view` AS +select +vm_instance.id id, +vm_instance.name name, +user_vm.display_name display_name, +user_vm.user_data user_data, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +instance_group.id instance_group_id, +instance_group.uuid instance_group_uuid, +instance_group.name instance_group_name, +vm_instance.uuid uuid, +vm_instance.last_host_id last_host_id, +vm_instance.vm_type type, +vm_instance.vnc_password vnc_password, +vm_instance.limit_cpu_use limit_cpu_use, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.ha_enabled ha_enabled, +vm_instance.hypervisor_type hypervisor_type, +vm_instance.instance_name instance_name, +vm_instance.guest_os_id guest_os_id, +guest_os.uuid guest_os_uuid, +vm_instance.pod_id pod_id, +host_pod_ref.uuid pod_uuid, +vm_instance.private_ip_address private_ip_address, +vm_instance.private_mac_address private_mac_address, +vm_instance.vm_type vm_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.is_security_group_enabled security_group_enabled, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.name template_name, +vm_template.display_text template_display_text, +vm_template.enable_password password_enabled, +iso.id iso_id, +iso.uuid iso_uuid, +iso.name iso_name, +iso.display_text iso_display_text, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +service_offering.cpu cpu, +service_offering.speed speed, +service_offering.ram_size ram_size, +disk_offering.name service_offering_name, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.pool_type pool_type, +volumes.id volume_id, +volumes.uuid volume_uuid, +volumes.device_id volume_device_id, +volumes.volume_type volume_type, +security_group.id security_group_id, +security_group.uuid security_group_uuid, +security_group.name security_group_name, +security_group.description security_group_description, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +user_ip_address.id public_ip_id, +user_ip_address.uuid public_ip_uuid, +user_ip_address.public_ip_address public_ip_address, +ssh_keypairs.keypair_name keypair_name, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user_vm +inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join guest_os on vm_instance.guest_os_id = guest_os.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id +left join instance_group on instance_group_vm_map.group_id=instance_group.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join vm_template iso on iso.id=user_vm.iso_id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id +left join security_group on security_group_vm_map.security_group_id=security_group.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join user_ip_address on user_ip_address.vm_id=vm_instance.id +left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" +left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value +left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`domain_router_view`; +CREATE VIEW domain_router_view AS +select +vm_instance.id id, +vm_instance.name name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +vm_instance.uuid uuid, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.pod_id pod_id, +vm_instance.instance_name instance_name, +host_pod_ref.uuid pod_uuid, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.dns1 dns1, +data_center.dns2 dns2, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +disk_offering.name service_offering_name, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.name network_name, +networks.network_domain network_domain, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id, +domain_router.template_version template_version, +domain_router.scripts_version scripts_version, +domain_router.is_redundant_router is_redundant_router, +domain_router.redundant_state redundant_state, +domain_router.stop_pending stop_pending +from domain_router +inner join vm_instance on vm_instance.id = domain_router.id +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`security_group_view`; +CREATE VIEW security_group_view AS +select +security_group.id id, +security_group.name name, +security_group.description description, +security_group.uuid uuid, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +security_group_rule.id rule_id, +security_group_rule.uuid rule_uuid, +security_group_rule.type rule_type, +security_group_rule.start_port rule_start_port, +security_group_rule.end_port rule_end_port, +security_group_rule.protocol rule_protocol, +security_group_rule.allowed_network_id rule_allowed_network_id, +security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, +security_group_rule.create_status rule_create_status, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from security_group +left join security_group_rule on security_group.id = security_group_rule.security_group_id +inner join account on security_group.account_id=account.id +inner join domain on security_group.domain_id=domain.id +left join projects on projects.project_account_id = security_group.account_id +left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" +left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; +CREATE VIEW resource_tag_view AS +select +resource_tags.id, +resource_tags.uuid, +resource_tags.key, +resource_tags.value, +resource_tags.resource_id, +resource_tags.resource_uuid, +resource_tags.resource_type, +resource_tags.customer, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from resource_tags +inner join account on resource_tags.account_id=account.id +inner join domain on resource_tags.domain_id=domain.id +left join projects on projects.project_account_id = resource_tags.account_id; + + +DROP VIEW IF EXISTS `cloud`.`event_view`; +CREATE VIEW event_view AS +select +event.id, +event.uuid, +event.type, +event.state, +event.description, +event.created, +event.level, +event.parameters, +event.start_id, +eve.uuid start_uuid, +event.user_id, +user.username user_name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from event +inner join account on event.account_id=account.id +inner join domain on event.domain_id=domain.id +inner join user on event.user_id = user.id +left join projects on projects.project_account_id = event.account_id +left join event eve on event.start_id = eve.id; + +DROP VIEW IF EXISTS `cloud`.`instance_group_view`; +CREATE VIEW instance_group_view AS +select +instance_group.id, +instance_group.uuid, +instance_group.name, +instance_group.removed, +instance_group.created, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from instance_group +inner join account on instance_group.account_id=account.id +inner join domain on account.domain_id=domain.id +left join projects on projects.project_account_id = instance_group.account_id; + +DROP VIEW IF EXISTS `cloud`.`user_view`; +CREATE VIEW user_view AS +select +user.id, +user.uuid, +user.username, +user.password, +user.firstname, +user.lastname, +user.email, +user.state, +user.api_key, +user.secret_key, +user.created, +user.removed, +user.timezone, +user.registration_token, +user.is_registered, +user.incorrect_login_attempts, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user +inner join account on user.account_id = account.id +inner join domain on account.domain_id=domain.id +left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; + + +DROP VIEW IF EXISTS `cloud`.`project_view`; +CREATE VIEW project_view AS +select +projects.id, +projects.uuid, +projects.name, +projects.display_text, +projects.state, +projects.removed, +projects.created, +account.account_name owner, +pacct.account_id, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer +from projects +inner join domain on projects.domain_id=domain.id +inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" +inner join account on account.id = project_account.account_id +left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" +left join project_account pacct on projects.id = pacct.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_account_view`; +CREATE VIEW project_account_view AS +select +project_account.id, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +project_account.account_role, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_account +inner join account on project_account.account_id = account.id +inner join domain on account.domain_id=domain.id +inner join projects on projects.id = project_account.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; +CREATE VIEW project_invitation_view AS +select +project_invitations.id, +project_invitations.uuid, +project_invitations.email, +project_invitations.created, +project_invitations.state, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_invitations +left join account on project_invitations.account_id = account.id +left join domain on project_invitations.domain_id=domain.id +left join projects on projects.id = project_invitations.project_id; + +DROP VIEW IF EXISTS `cloud`.`host_view`; +CREATE VIEW host_view AS +select +host.id, +host.uuid, +host.name, +host.status, +host.disconnected, +host.type, +host.private_ip_address, +host.version, +host.hypervisor_type, +host.hypervisor_version, +host.capabilities, +host.last_ping, +host.created, +host.removed, +host.resource_state, +host.mgmt_server_id, +host.cpus, +host.speed, +host.ram, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +host_tags.tag, +guest_os_category.id guest_os_category_id, +guest_os_category.uuid guest_os_category_uuid, +guest_os_category.name guest_os_category_name, +mem_caps.used_capacity memory_used_capacity, +mem_caps.reserved_capacity memory_reserved_capacity, +cpu_caps.used_capacity cpu_used_capacity, +cpu_caps.reserved_capacity cpu_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from host +left join cluster on host.cluster_id = cluster.id +left join data_center on host.data_center_id = data_center.id +left join host_pod_ref on host.pod_id = host_pod_ref.id +left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" +left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) +left join host_tags on host_tags.host_id = host.id +left join op_host_capacity mem_caps on host.id = mem_caps.host_id and mem_caps.capacity_type = 0 +left join op_host_capacity cpu_caps on host.id = cpu_caps.host_id and cpu_caps.capacity_type = 1 +left join async_job on async_job.instance_id = host.id and async_job.instance_type = "Host" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`volume_view`; +CREATE VIEW volume_view AS +select +volumes.id, +volumes.uuid, +volumes.name, +volumes.device_id, +volumes.volume_type, +volumes.size, +volumes.created, +volumes.state, +volumes.attached, +volumes.removed, +volumes.pod_id, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +vm_instance.id vm_id, +vm_instance.uuid vm_uuid, +vm_instance.name vm_name, +vm_instance.state vm_state, +vm_instance.vm_type, +user_vm.display_name vm_display_name, +volume_host_ref.size volume_host_size, +volume_host_ref.created volume_host_created, +volume_host_ref.format, +volume_host_ref.download_pct, +volume_host_ref.download_state, +volume_host_ref.error_str, +disk_offering.id disk_offering_id, +disk_offering.uuid disk_offering_uuid, +disk_offering.name disk_offering_name, +disk_offering.display_text disk_offering_display_text, +disk_offering.use_local_storage, +disk_offering.system_use, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.name pool_name, +cluster.hypervisor_type, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.extractable, +vm_template.type template_type, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from volumes +inner join account on volumes.account_id=account.id +inner join domain on volumes.domain_id=domain.id +left join projects on projects.project_account_id = account.id +left join data_center on volumes.data_center_id = data_center.id +left join vm_instance on volumes.instance_id = vm_instance.id +left join user_vm on user_vm.id = vm_instance.id +left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id +left join disk_offering on volumes.disk_offering_id = disk_offering.id +left join storage_pool on volumes.pool_id = storage_pool.id +left join cluster on storage_pool.cluster_id = cluster.id +left join vm_template on volumes.template_id = vm_template.id +left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" +left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; +CREATE VIEW account_netstats_view AS +SELECT account_id, +sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, +sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent +FROM user_statistics +group by account_id; + + +DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; +CREATE VIEW account_vmstats_view AS +SELECT account_id, state, count(*) as vmcount +from vm_instance +group by account_id, state; + +DROP VIEW IF EXISTS `cloud`.`free_ip_view`; +CREATE VIEW free_ip_view AS +select count(user_ip_address.id) free_ip +from user_ip_address +inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" +where state = "Free" + +DROP VIEW IF EXISTS `cloud`.`account_view`; +CREATE VIEW account_view AS +select +account.id, +account.uuid, +account.account_name, +account.type, +account.state, +account.removed, +account.cleanup_needed, +account.network_domain, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +account_netstats_view.bytesReceived, +account_netstats_view.bytesSent, +vmlimit.max vmLimit, +vmcount.count vmTotal, +runningvm.vmcount runningVms, +stoppedvm.vmcount stoppedVms, +iplimit.max ipLimit, +ipcount.count ipTotal, +free_ip_view.free_ip ipFree, +volumelimit.max volumeLimit, +volumecount.count volumeTotal, +snapshotlimit.max snapshotLimit, +snapshotcount.count snapshotTotal, +templatelimit.max templateLimit, +templatecount.count templateTotal, +vpclimit.max vpcLimit, +vpccount.count vpcTotal, +projectlimit.max projectLimit, +projectcount.count projectTotal, +networklimit.max networkLimit, +networkcount.count networkTotal, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from free_ip_view, account +inner join domain on account.domain_id=domain.id +left join data_center on account.default_zone_id = data_center.id +left join account_netstats_view on account.id = account_netstats_view.account_id +left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" +left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" +left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" +left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" +left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" +left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" +left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" +left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" +left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" +left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" +left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" +left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" +left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" +left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" +left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" +left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" +left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" +left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" +left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`async_job_view`; +CREATE VIEW async_job_view AS +select +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +user.id user_id, +user.uuid user_uuid, +async_job.id, +async_job.uuid, +async_job.job_cmd, +async_job.job_status, +async_job.job_process_status, +async_job.job_result_code, +async_job.job_result, +async_job.created, +async_job.removed, +async_job.instance_type, +async_job.instance_id, +CASE +WHEN async_job.instance_type = 'Volume' THEN volumes.uuid +WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid +WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid +WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid +WHEN async_job.instance_type = 'Host' THEN host.uuid +WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid +WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid +WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid +WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid +WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid +WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid +WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid +WHEN async_job.instance_type = 'Account' THEN acct.uuid +WHEN async_job.instance_type = 'User' THEN us.uuid +WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid +WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid +WHEN async_job.instance_type = 'Counter' THEN counter.uuid +WHEN async_job.instance_type = 'Condition' THEN conditions.uuid +WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid +WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid +WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid +ELSE null +END instance_uuid +from async_job +left join account on async_job.account_id = account.id +left join domain on domain.id = account.domain_id +left join user on async_job.user_id = user.id +left join volumes on async_job.instance_id = volumes.id +left join vm_template on async_job.instance_id = vm_template.id +left join vm_instance on async_job.instance_id = vm_instance.id +left join snapshots on async_job.instance_id = snapshots.id +left join host on async_job.instance_id = host.id +left join storage_pool on async_job.instance_id = storage_pool.id +left join user_ip_address on async_job.instance_id = user_ip_address.id +left join security_group on async_job.instance_id = security_group.id +left join physical_network on async_job.instance_id = physical_network.id +left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id +left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id +left join firewall_rules on async_job.instance_id = firewall_rules.id +left join account acct on async_job.instance_id = acct.id +left join user us on async_job.instance_id = us.id +left join static_routes on async_job.instance_id = static_routes.id +left join vpc_gateways on async_job.instance_id = vpc_gateways.id +left join counter on async_job.instance_id = counter.id +left join conditions on async_job.instance_id = conditions.id +left join autoscale_policies on async_job.instance_id = autoscale_policies.id +left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id +left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; + +DROP VIEW IF EXISTS `cloud`.`storage_pool_view`; +CREATE VIEW storage_pool_view AS +select +storage_pool.id, +storage_pool.uuid, +storage_pool.name, +storage_pool.status, +storage_pool.path, +storage_pool.pool_type, +storage_pool.host_address, +storage_pool.created, +storage_pool.removed, +storage_pool.capacity_bytes, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +storage_pool_details.name tag, +op_host_capacity.used_capacity disk_used_capacity, +op_host_capacity.reserved_capacity disk_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from storage_pool +left join cluster on storage_pool.cluster_id = cluster.id +left join data_center on storage_pool.data_center_id = data_center.id +left join host_pod_ref on storage_pool.pod_id = host_pod_ref.id +left join storage_pool_details on storage_pool_details.pool_id = storage_pool.id and storage_pool_details.value = 'true' +left join op_host_capacity on storage_pool.id = op_host_capacity.host_id and op_host_capacity.capacity_type = 3 +left join async_job on async_job.instance_id = storage_pool.id and async_job.instance_type = "StoragePool" and async_job.job_status = 0; diff --git a/setup/db/deploy-db-dev.sh b/setup/db/deploy-db-dev.sh index 29ec4db6050..a40e278b002 100755 --- a/setup/db/deploy-db-dev.sh +++ b/setup/db/deploy-db-dev.sh @@ -55,6 +55,11 @@ if [ ! -f create-index-fk.sql ]; then exit 6; fi +if [ ! -f create-schema-view.sql ]; then + printf "Error: Unable to find create-schema-view.sql\n" + exit 7 +fi + PATHSEP=':' if [[ $OSTYPE == "cygwin" ]] ; then export CATALINA_HOME=`cygpath -m $CATALINA_HOME` @@ -100,6 +105,12 @@ if [ $? -ne 0 ]; then exit 11 fi +mysql --user=cloud --password=cloud cloud < create-schema-view.sql +if [ $? -ne 0 ]; then + printf "Error: Cannot execute create-schema-view.sql\n" + exit 11 +fi + CP=./ CP=${CP}$PATHSEP$CATALINA_HOME/conf diff --git a/setup/db/deploy-db-simulator.sh b/setup/db/deploy-db-simulator.sh index 4f8c14ebfe5..c918df43009 100644 --- a/setup/db/deploy-db-simulator.sh +++ b/setup/db/deploy-db-simulator.sh @@ -55,6 +55,12 @@ if [ ! -f create-index-fk.sql ]; then exit 6; fi +if [ ! -f create-schema-view.sql ]; then + printf "Error: Unable to find create-schema-view.sql\n" + exit 7 +fi + + PATHSEP=':' if [[ $OSTYPE == "cygwin" ]] ; then export CATALINA_HOME=`cygpath -m $CATALINA_HOME` @@ -103,6 +109,12 @@ if [ $? -ne 0 ]; then exit 11 fi +mysql --user=cloud --password=cloud cloud < create-schema-view.sql +if [ $? -ne 0 ]; then + printf "Error: Cannot execute create-schema-view.sql\n" + exit 11 +fi + mysql --user=cloud --password=cloud cloud < create-schema-simulator.sql if [ $? -ne 0 ]; then printf "Error: Cannot execute create-schema-simulator.sql\n" diff --git a/setup/db/server-setup.sql b/setup/db/server-setup.sql index 2cbfc162e1f..faab38e33fc 100644 --- a/setup/db/server-setup.sql +++ b/setup/db/server-setup.sql @@ -18,7 +18,7 @@ /* This file specifies default values that go into the database, before the Management Server is run. */ /* Root Domain */ -INSERT INTO `cloud`.`domain` (id, name, parent, path, owner) VALUES (1, 'ROOT', NULL, '/', 2); +INSERT INTO `cloud`.`domain` (id, uuid, name, parent, path, owner) VALUES (1, UUID(), 'ROOT', NULL, '/', 2); /* Configuration Table */ diff --git a/setup/db/templates.kvm.sql b/setup/db/templates.kvm.sql index 7b9502719da..8a5582540af 100644 --- a/setup/db/templates.kvm.sql +++ b/setup/db/templates.kvm.sql @@ -15,56 +15,57 @@ -- specific language governing permissions and limitations -- under the License. -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) - VALUES (1, 'routing', 'DomR Template', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/a88232bf-6a18-38e7-aeee-c1702725079f.qcow2.bz2', 'e39c55e93ae96bd43bfd588ca6ee3269', 'DomR Template', 0, 'QCOW2', 21, 0, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) - VALUES (2, 'centos55-x86_64', 'CentOS 5.5(x86_64) no GUI', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', '1da20ae69b54f761f3f733dce97adcc0', 'CentOS 5.5(x86_64) no GUI', 0, 'QCOW2', 9, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) + VALUES (1, UUID(), 'routing', 'DomR Template', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/a88232bf-6a18-38e7-aeee-c1702725079f.qcow2.bz2', 'e39c55e93ae96bd43bfd588ca6ee3269', 'DomR Template', 0, 'QCOW2', 21, 0, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) + VALUES (2, UUID(), 'centos55-x86_64', 'CentOS 5.5(x86_64) no GUI', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', '1da20ae69b54f761f3f733dce97adcc0', 'CentOS 5.5(x86_64) no GUI', 0, 'QCOW2', 9, 1, 1); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'CentOS'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Ubuntu'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'RedHat'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (7, 'Windows'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (8, 'Other'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (1, UUID(), 'CentOS'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (2, UUID(), 'Ubuntu'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (5, UUID(), 'RedHat'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (7, UUID(), 'Windows'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (8, UUID(), 'Other'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 4.5', 'CentOS 4.5'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 4.6', 'CentOS 4.6'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 4.7', 'CentOS 4.7'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.0', 'CentOS 5.0'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.1', 'CentOS 5.1'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.2', 'CentOS 5.2'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.3', 'CentOS 5.3'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.4', 'CentOS 5.4'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (1, 'CentOS 5.5', 'CentOS 5.5'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 4.5', 'Red Hat Enterprise Linux 4.5'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 4.6', 'Red Hat Enterprise Linux 4.6'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 4.7', 'Red Hat Enterprise Linux 4.7'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.0', 'Red Hat Enterprise Linux 5.0'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.1', 'Red Hat Enterprise Linux 5.1'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.2', 'Red Hat Enterprise Linux 5.2'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.3', 'Red Hat Enterprise Linux 5.3'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.4', 'Red Hat Enterprise Linux 5.4'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 5.5', 'Red Hat Enterprise Linux 5.5'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Red Hat Enterprise Linux 6', 'Red Hat Enterprise Linux 6'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 13', 'Fedora 13'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 12', 'Fedora 12'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 11', 'Fedora 11'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 10', 'Fedora 10'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 9', 'Fedora 9'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (5, 'Fedora 8', 'Fedora 8'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Ubuntu 10.04', 'Ubuntu 10.04'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Ubuntu 9.10', 'Ubuntu 9.10'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Ubuntu 9.04', 'Ubuntu 9.04'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Ubuntu 8.10', 'Ubuntu 8.10'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Ubuntu 8.04', 'Ubuntu 8.04'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Debian Squeeze', 'Debian Squeeze'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Debian Lenny', 'Debian Lenny'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (2, 'Debian Etch', 'Debian Etch'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows 7', 'Windows 7'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows Server 2003', 'Windows Server 2003'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows Server 2008', 'Windows Server 2008'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows 2000 SP4', 'Windows 2000 SP4'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows Vista', 'Windows Vista'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows XP SP2', 'Windows XP SP2'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (7, 'Windows XP SP3', 'Windows XP SP3'); -INSERT INTO `cloud`.`guest_os` (category_id, name, display_name) VALUES (8, 'Other install media', 'Other'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 4.5', 'CentOS 4.5'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 4.6', 'CentOS 4.6'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 4.7', 'CentOS 4.7'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.0', 'CentOS 5.0'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.1', 'CentOS 5.1'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.2', 'CentOS 5.2'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.3', 'CentOS 5.3'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.4', 'CentOS 5.4'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 1, 'CentOS 5.5', 'CentOS 5.5'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 4.5', 'Red Hat Enterprise Linux 4.5'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 4.6', 'Red Hat Enterprise Linux 4.6'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 4.7', 'Red Hat Enterprise Linux 4.7'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.0', 'Red Hat Enterprise Linux 5.0'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.1', 'Red Hat Enterprise Linux 5.1'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.2', 'Red Hat Enterprise Linux 5.2'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.3', 'Red Hat Enterprise Linux 5.3'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.4', 'Red Hat Enterprise Linux 5.4'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 5.5', 'Red Hat Enterprise Linux 5.5'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Red Hat Enterprise Linux 6', 'Red Hat Enterprise Linux 6'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 13', 'Fedora 13'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 12', 'Fedora 12'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 11', 'Fedora 11'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 10', 'Fedora 10'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 9', 'Fedora 9'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 5, 'Fedora 8', 'Fedora 8'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 12.04', 'Ubuntu 12.04'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 10.04', 'Ubuntu 10.04'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 9.10', 'Ubuntu 9.10'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 9.04', 'Ubuntu 9.04'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 8.10', 'Ubuntu 8.10'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 10, 'Ubuntu 8.04', 'Ubuntu 8.04'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 2, 'Debian Squeeze', 'Debian Squeeze'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 2, 'Debian Lenny', 'Debian Lenny'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 2, 'Debian Etch', 'Debian Etch'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows 7', 'Windows 7'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows Server 2003', 'Windows Server 2003'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows Server 2008', 'Windows Server 2008'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows 2000 SP4', 'Windows 2000 SP4'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows Vista', 'Windows Vista'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows XP SP2', 'Windows XP SP2'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 7, 'Windows XP SP3', 'Windows XP SP3'); +INSERT INTO `cloud`.`guest_os` (uuid, category_id, name, display_name) VALUES (UUID(), 8, 'Other install media', 'Other'); diff --git a/setup/db/templates.simulator.sql b/setup/db/templates.simulator.sql index 7e712f54177..437e8f5357e 100755 --- a/setup/db/templates.simulator.sql +++ b/setup/db/templates.simulator.sql @@ -16,7 +16,7 @@ -- under the License. -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (10, 'simulator-domR', 'SystemVM Template (simulator)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/routing/debian/latest/systemvm.vhd.bz2', '', 0, 'SystemVM Template (simulator)', 'VHD', 15, 0, 1, 'Simulator'); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (11, 'simulator-Centos', 'CentOS 5.3(64-bit) no GUI (Simulator)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', '', 0, 'CentOS 5.3(64-bit) no GUI (Simulator)', 'VHD', 11, 1, 1, 'Simulator'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (10, UUID(), 'simulator-domR', 'SystemVM Template (simulator)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/routing/debian/latest/systemvm.vhd.bz2', '', 0, 'SystemVM Template (simulator)', 'VHD', 15, 0, 1, 'Simulator'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (11, UUID(), 'simulator-Centos', 'CentOS 5.3(64-bit) no GUI (Simulator)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', '', 0, 'CentOS 5.3(64-bit) no GUI (Simulator)', 'VHD', 11, 1, 1, 'Simulator'); diff --git a/setup/db/templates.sql b/setup/db/templates.sql index 0c85be47a5f..9980b159630 100755 --- a/setup/db/templates.sql +++ b/setup/db/templates.sql @@ -15,207 +15,209 @@ -- specific language governing permissions and limitations -- under the License. -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (1, 'routing-1', 'SystemVM Template (XenServer)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2', 'f613f38c96bf039f2e5cbf92fa8ad4f8', 0, 'SystemVM Template (XenServer)', 'VHD', 133, 0, 1, 'XenServer'); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, removed, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) - VALUES (2, 'centos53-x86_64', 'CentOS 5.3(64-bit) no GUI (XenServer)', 1, now(), now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/templates/builtin/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'CentOS 5.3(64-bit) no GUI (XenServer)', 'VHD', 12, 1, 1, 'XenServer', 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (1, UUID(), 'routing-1', 'SystemVM Template (XenServer)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2', 'f613f38c96bf039f2e5cbf92fa8ad4f8', 0, 'SystemVM Template (XenServer)', 'VHD', 133, 0, 1, 'XenServer'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, removed, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) + VALUES (2, UUID(), 'centos53-x86_64', 'CentOS 5.3(64-bit) no GUI (XenServer)', 1, now(), now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/templates/builtin/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'CentOS 5.3(64-bit) no GUI (XenServer)', 'VHD', 12, 1, 1, 'XenServer', 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (3, 'routing-3', 'SystemVM Template (KVM)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2', '2755de1f9ef2ce4d6f2bee2efbb4da92', 0, 'SystemVM Template (KVM)', 'QCOW2', 15, 0, 1, 'KVM'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (3, UUID(), 'routing-3', 'SystemVM Template (KVM)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2', '2755de1f9ef2ce4d6f2bee2efbb4da92', 0, 'SystemVM Template (KVM)', 'QCOW2', 15, 0, 1, 'KVM'); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) - VALUES (4, 'centos55-x86_64', 'CentOS 5.5(64-bit) no GUI (KVM)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/releases/2.2.0/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', 'ed0e788280ff2912ea40f7f91ca7a249', 'CentOS 5.5(64-bit) no GUI (KVM)', 0, 'QCOW2', 112, 1, 1, 'KVM', 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) + VALUES (4, UUID(), 'centos55-x86_64', 'CentOS 5.5(64-bit) no GUI (KVM)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/releases/2.2.0/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', 'ed0e788280ff2912ea40f7f91ca7a249', 'CentOS 5.5(64-bit) no GUI (KVM)', 0, 'QCOW2', 112, 1, 1, 'KVM', 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) - VALUES (5, 'centos56-x86_64-xen', 'CentOS 5.6(64-bit) no GUI (XenServer)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/templates/builtin/centos56-x86_64.vhd.bz2', '905cec879afd9c9d22ecc8036131a180', 0, 'CentOS 5.6(64-bit) no GUI (XenServer)', 'VHD', 12, 1, 1, 'XenServer', 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) + VALUES (5, UUID(), 'centos56-x86_64-xen', 'CentOS 5.6(64-bit) no GUI (XenServer)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/templates/builtin/centos56-x86_64.vhd.bz2', '905cec879afd9c9d22ecc8036131a180', 0, 'CentOS 5.6(64-bit) no GUI (XenServer)', 'VHD', 12, 1, 1, 'XenServer', 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) - VALUES (7, 'centos53-x64', 'CentOS 5.3(64-bit) no GUI (vSphere)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/releases/2.2.0/CentOS5.3-x86_64.ova', 'f6f881b7f2292948d8494db837fe0f47', 0, 'CentOS 5.3(64-bit) no GUI (vSphere)', 'OVA', 12, 1, 1, 'VMware', 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type, extractable) + VALUES (7, UUID(), 'centos53-x64', 'CentOS 5.3(64-bit) no GUI (vSphere)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/releases/2.2.0/CentOS5.3-x86_64.ova', 'f6f881b7f2292948d8494db837fe0f47', 0, 'CentOS 5.3(64-bit) no GUI (vSphere)', 'OVA', 12, 1, 1, 'VMware', 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (8, 'routing-8', 'SystemVM Template (vSphere)', 0, now(), 'SYSTEM', 0, 32, 1, 'http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova', '7137e453f950079ea2ba6feaafd939e8', 0, 'SystemVM Template (vSphere)', 'OVA', 15, 0, 1, 'VMware'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (8, UUID(), 'routing-8', 'SystemVM Template (vSphere)', 0, now(), 'SYSTEM', 0, 32, 1, 'http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova', '7137e453f950079ea2ba6feaafd939e8', 0, 'SystemVM Template (vSphere)', 'OVA', 15, 0, 1, 'VMware'); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (9, 'routing-9', 'SystemVM Template (HyperV)', 0, now(), 'SYSTEM', 0, 32, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2', 'f613f38c96bf039f2e5cbf92fa8ad4f8', 0, 'SystemVM Template (HyperV)', 'VHD', 15, 0, 1, 'Hyperv'); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) + VALUES (9, UUID(), 'routing-9', 'SystemVM Template (HyperV)', 0, now(), 'SYSTEM', 0, 32, 1, 'http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2', 'f613f38c96bf039f2e5cbf92fa8ad4f8', 0, 'SystemVM Template (HyperV)', 'VHD', 15, 0, 1, 'Hyperv'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'CentOS'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Debian'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (3, 'Oracle'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (4, 'RedHat'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'SUSE'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (6, 'Windows'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (7, 'Other'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (8, 'Novel'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (9, 'Unix'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (10, 'Ubuntu'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (11, 'None'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (1, UUID(), 'CentOS'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (2, UUID(), 'Debian'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (3, UUID(), 'Oracle'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (4, UUID(), 'RedHat'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (5, UUID(), 'SUSE'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (6, UUID(), 'Windows'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (7, UUID(), 'Other'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (8, UUID(), 'Novel'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (9, UUID(), 'Unix'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (10, UUID(), 'Ubuntu'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (11, UUID(), 'None'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (1, 1, 'CentOS 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (2, 1, 'CentOS 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (3, 1, 'CentOS 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (4, 1, 'CentOS 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (5, 1, 'CentOS 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (6, 1, 'CentOS 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (7, 1, 'CentOS 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (8, 1, 'CentOS 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (9, 1, 'CentOS 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (10, 1, 'CentOS 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (11, 1, 'CentOS 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (12, 1, 'CentOS 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (13, 1, 'CentOS 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (14, 1, 'CentOS 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (15, 2, 'Debian GNU/Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (16, 3, 'Oracle Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (17, 3, 'Oracle Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (18, 3, 'Oracle Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (19, 3, 'Oracle Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (20, 3, 'Oracle Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (21, 3, 'Oracle Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (22, 3, 'Oracle Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (23, 3, 'Oracle Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (24, 3, 'Oracle Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (25, 3, 'Oracle Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (26, 4, 'Red Hat Enterprise Linux 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (27, 4, 'Red Hat Enterprise Linux 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (28, 4, 'Red Hat Enterprise Linux 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (29, 4, 'Red Hat Enterprise Linux 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (30, 4, 'Red Hat Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (31, 4, 'Red Hat Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (32, 4, 'Red Hat Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (33, 4, 'Red Hat Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (34, 4, 'Red Hat Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (35, 4, 'Red Hat Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (36, 4, 'Red Hat Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (37, 4, 'Red Hat Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (38, 4, 'Red Hat Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (39, 4, 'Red Hat Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (40, 5, 'SUSE Linux Enterprise Server 9 SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (41, 5, 'SUSE Linux Enterprise Server 10 SP1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (42, 5, 'SUSE Linux Enterprise Server 10 SP1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (43, 5, 'SUSE Linux Enterprise Server 10 SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (44, 5, 'SUSE Linux Enterprise Server 10 SP2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (45, 5, 'SUSE Linux Enterprise Server 10 SP3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (46, 5, 'SUSE Linux Enterprise Server 11 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (47, 5, 'SUSE Linux Enterprise Server 11 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (48, 6, 'Windows 7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (49, 6, 'Windows 7 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (50, 6, 'Windows Server 2003 Enterprise Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (51, 6, 'Windows Server 2003 Enterprise Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (52, 6, 'Windows Server 2008 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (53, 6, 'Windows Server 2008 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (54, 6, 'Windows Server 2008 R2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (55, 6, 'Windows 2000 Server SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (56, 6, 'Windows Vista (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (57, 6, 'Windows XP SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (58, 6, 'Windows XP SP3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (59, 10, 'Other Ubuntu (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (60, 7, 'Other (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (61, 6, 'Windows 2000 Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (62, 6, 'Windows 98'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (63, 6, 'Windows 95'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (64, 6, 'Windows NT 4'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (65, 6, 'Windows 3.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (66, 4, 'Red Hat Enterprise Linux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (67, 4, 'Red Hat Enterprise Linux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (68, 7, 'Open Enterprise Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (69, 7, 'Asianux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (70, 7, 'Asianux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (72, 2, 'Debian GNU/Linux 5(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (73, 2, 'Debian GNU/Linux 4(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (74, 2, 'Debian GNU/Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (75, 7, 'Other 2.6x Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (76, 7, 'Other 2.6x Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (77, 8, 'Novell Netware 6.x'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (78, 8, 'Novell Netware 5.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (79, 9, 'Sun Solaris 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (80, 9, 'Sun Solaris 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (81, 9, 'Sun Solaris 9(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (82, 9, 'Sun Solaris 8(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (83, 9, 'FreeBSD (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (84, 9, 'FreeBSD (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (85, 9, 'SCO OpenServer 5'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (86, 9, 'SCO UnixWare 7'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (87, 6, 'Windows Server 2003 DataCenter Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (88, 6, 'Windows Server 2003 DataCenter Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (89, 6, 'Windows Server 2003 Standard Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (90, 6, 'Windows Server 2003 Standard Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (91, 6, 'Windows Server 2003 Web Edition'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (92, 6, 'Microsoft Small Bussiness Server 2003'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (93, 6, 'Windows XP (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (94, 6, 'Windows XP (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (95, 6, 'Windows 2000 Advanced Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (96, 5, 'SUSE Linux Enterprise 8(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (97, 5, 'SUSE Linux Enterprise 8(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (98, 7, 'Other Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (99, 7, 'Other Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (100, 10, 'Other Ubuntu (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (101, 6, 'Windows Vista (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (102, 6, 'DOS'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (103, 7, 'Other (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (104, 7, 'OS/2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (105, 6, 'Windows 2000 Professional'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (106, 4, 'Red Hat Enterprise Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (107, 5, 'SUSE Linux Enterprise 9(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (108, 5, 'SUSE Linux Enterprise 9(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (109, 5, 'SUSE Linux Enterprise 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (110, 5, 'SUSE Linux Enterprise 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (111, 1, 'CentOS 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (112, 1, 'CentOS 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (113, 4, 'Red Hat Enterprise Linux 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (114, 4, 'Red Hat Enterprise Linux 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (115, 4, 'Fedora 13'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (116, 4, 'Fedora 12'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (117, 4, 'Fedora 11'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (118, 4, 'Fedora 10'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (119, 4, 'Fedora 9'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (120, 4, 'Fedora 8'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (121, 10, 'Ubuntu 10.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (122, 10, 'Ubuntu 9.10 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (123, 10, 'Ubuntu 9.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (124, 10, 'Ubuntu 8.10 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (125, 10, 'Ubuntu 8.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (126, 10, 'Ubuntu 10.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (127, 10, 'Ubuntu 9.10 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (128, 10, 'Ubuntu 9.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (129, 10, 'Ubuntu 8.10 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (130, 10, 'Ubuntu 8.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (131, 4, 'Red Hat Enterprise Linux 2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (132, 2, 'Debian GNU/Linux 6(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (133, 2, 'Debian GNU/Linux 6(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (134, 3, 'Oracle Enterprise Linux 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (135, 3, 'Oracle Enterprise Linux 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (136, 4, 'Red Hat Enterprise Linux 6.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (137, 4, 'Red Hat Enterprise Linux 6.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (138, 7, 'None'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (139, 7, 'Other PV (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (140, 7, 'Other PV (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (141, 1, 'CentOS 5.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (142, 1, 'CentOS 5.6 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (143, 1, 'CentOS 6.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (144, 1, 'CentOS 6.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (145, 3, 'Oracle Enterprise Linux 5.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (146, 3, 'Oracle Enterprise Linux 5.6 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (147, 3, 'Oracle Enterprise Linux 6.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (148, 3, 'Oracle Enterprise Linux 6.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (149, 4, 'Red Hat Enterprise Linux 5.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (150, 4, 'Red Hat Enterprise Linux 5.6 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (151, 5, 'SUSE Linux Enterprise Server 10 SP3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (152, 5, 'SUSE Linux Enterprise Server 10 SP4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (153, 5, 'SUSE Linux Enterprise Server 10 SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (154, 5, 'SUSE Linux Enterprise Server 11 SP1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (155, 5, 'SUSE Linux Enterprise Server 11 SP1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (156, 10, 'Ubuntu 10.10 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (157, 10, 'Ubuntu 10.10 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (158, 9, 'Sun Solaris 11 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (159, 9, 'Sun Solaris 11 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (160, 6, 'Windows PV'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (161, 1, 'CentOS 5.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (162, 1, 'CentOS 5.7 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (1, UUID(), 1, 'CentOS 4.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (2, UUID(), 1, 'CentOS 4.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (3, UUID(), 1, 'CentOS 4.7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (4, UUID(), 1, 'CentOS 4.8 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (5, UUID(), 1, 'CentOS 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (6, UUID(), 1, 'CentOS 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (7, UUID(), 1, 'CentOS 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (8, UUID(), 1, 'CentOS 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (9, UUID(), 1, 'CentOS 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (10, UUID(), 1, 'CentOS 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (11, UUID(), 1, 'CentOS 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (12, UUID(), 1, 'CentOS 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (13, UUID(), 1, 'CentOS 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (14, UUID(), 1, 'CentOS 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (15, UUID(), 2, 'Debian GNU/Linux 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (16, UUID(), 3, 'Oracle Enterprise Linux 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (17, UUID(), 3, 'Oracle Enterprise Linux 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (18, UUID(), 3, 'Oracle Enterprise Linux 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (19, UUID(), 3, 'Oracle Enterprise Linux 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (20, UUID(), 3, 'Oracle Enterprise Linux 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (21, UUID(), 3, 'Oracle Enterprise Linux 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (22, UUID(), 3, 'Oracle Enterprise Linux 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (23, UUID(), 3, 'Oracle Enterprise Linux 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (24, UUID(), 3, 'Oracle Enterprise Linux 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (25, UUID(), 3, 'Oracle Enterprise Linux 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (26, UUID(), 4, 'Red Hat Enterprise Linux 4.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (27, UUID(), 4, 'Red Hat Enterprise Linux 4.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (28, UUID(), 4, 'Red Hat Enterprise Linux 4.7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (29, UUID(), 4, 'Red Hat Enterprise Linux 4.8 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (30, UUID(), 4, 'Red Hat Enterprise Linux 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (31, UUID(), 4, 'Red Hat Enterprise Linux 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (32, UUID(), 4, 'Red Hat Enterprise Linux 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (33, UUID(), 4, 'Red Hat Enterprise Linux 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (34, UUID(), 4, 'Red Hat Enterprise Linux 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (35, UUID(), 4, 'Red Hat Enterprise Linux 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (36, UUID(), 4, 'Red Hat Enterprise Linux 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (37, UUID(), 4, 'Red Hat Enterprise Linux 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (38, UUID(), 4, 'Red Hat Enterprise Linux 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (39, UUID(), 4, 'Red Hat Enterprise Linux 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (40, UUID(), 5, 'SUSE Linux Enterprise Server 9 SP4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (41, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (42, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (43, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (44, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (45, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (46, UUID(), 5, 'SUSE Linux Enterprise Server 11 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (47, UUID(), 5, 'SUSE Linux Enterprise Server 11 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (48, UUID(), 6, 'Windows 7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (49, UUID(), 6, 'Windows 7 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (50, UUID(), 6, 'Windows Server 2003 Enterprise Edition(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (51, UUID(), 6, 'Windows Server 2003 Enterprise Edition(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (52, UUID(), 6, 'Windows Server 2008 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (53, UUID(), 6, 'Windows Server 2008 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (54, UUID(), 6, 'Windows Server 2008 R2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (55, UUID(), 6, 'Windows 2000 Server SP4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (56, UUID(), 6, 'Windows Vista (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (57, UUID(), 6, 'Windows XP SP2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (58, UUID(), 6, 'Windows XP SP3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (59, UUID(), 10, 'Other Ubuntu (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (60, UUID(), 7, 'Other (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (61, UUID(), 6, 'Windows 2000 Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (62, UUID(), 6, 'Windows 98'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (63, UUID(), 6, 'Windows 95'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (64, UUID(), 6, 'Windows NT 4'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (65, UUID(), 6, 'Windows 3.1'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (66, UUID(), 4, 'Red Hat Enterprise Linux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (67, UUID(), 4, 'Red Hat Enterprise Linux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (68, UUID(), 7, 'Open Enterprise Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (69, UUID(), 7, 'Asianux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (70, UUID(), 7, 'Asianux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (72, UUID(), 2, 'Debian GNU/Linux 5(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (73, UUID(), 2, 'Debian GNU/Linux 4(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (74, UUID(), 2, 'Debian GNU/Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (75, UUID(), 7, 'Other 2.6x Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (76, UUID(), 7, 'Other 2.6x Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (77, UUID(), 8, 'Novell Netware 6.x'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (78, UUID(), 8, 'Novell Netware 5.1'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (79, UUID(), 9, 'Sun Solaris 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (80, UUID(), 9, 'Sun Solaris 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (81, UUID(), 9, 'Sun Solaris 9(Experimental)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (82, UUID(), 9, 'Sun Solaris 8(Experimental)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (83, UUID(), 9, 'FreeBSD (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (84, UUID(), 9, 'FreeBSD (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (85, UUID(), 9, 'SCO OpenServer 5'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (86, UUID(), 9, 'SCO UnixWare 7'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (87, UUID(), 6, 'Windows Server 2003 DataCenter Edition(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (88, UUID(), 6, 'Windows Server 2003 DataCenter Edition(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (89, UUID(), 6, 'Windows Server 2003 Standard Edition(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (90, UUID(), 6, 'Windows Server 2003 Standard Edition(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (91, UUID(), 6, 'Windows Server 2003 Web Edition'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (92, UUID(), 6, 'Microsoft Small Bussiness Server 2003'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (93, UUID(), 6, 'Windows XP (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (94, UUID(), 6, 'Windows XP (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (95, UUID(), 6, 'Windows 2000 Advanced Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (96, UUID(), 5, 'SUSE Linux Enterprise 8(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (97, UUID(), 5, 'SUSE Linux Enterprise 8(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (98, UUID(), 7, 'Other Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (99, UUID(), 7, 'Other Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (100, UUID(), 10, 'Other Ubuntu (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (101, UUID(), 6, 'Windows Vista (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (102, UUID(), 6, 'DOS'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (103, UUID(), 7, 'Other (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (104, UUID(), 7, 'OS/2'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (105, UUID(), 6, 'Windows 2000 Professional'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (106, UUID(), 4, 'Red Hat Enterprise Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (107, UUID(), 5, 'SUSE Linux Enterprise 9(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (108, UUID(), 5, 'SUSE Linux Enterprise 9(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (109, UUID(), 5, 'SUSE Linux Enterprise 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (110, UUID(), 5, 'SUSE Linux Enterprise 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (111, UUID(), 1, 'CentOS 5.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (112, UUID(), 1, 'CentOS 5.5 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (113, UUID(), 4, 'Red Hat Enterprise Linux 5.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (114, UUID(), 4, 'Red Hat Enterprise Linux 5.5 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (115, UUID(), 4, 'Fedora 13'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (116, UUID(), 4, 'Fedora 12'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (117, UUID(), 4, 'Fedora 11'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (118, UUID(), 4, 'Fedora 10'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (119, UUID(), 4, 'Fedora 9'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (120, UUID(), 4, 'Fedora 8'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (121, UUID(), 10, 'Ubuntu 10.04 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (122, UUID(), 10, 'Ubuntu 9.10 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (123, UUID(), 10, 'Ubuntu 9.04 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (124, UUID(), 10, 'Ubuntu 8.10 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (125, UUID(), 10, 'Ubuntu 8.04 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (126, UUID(), 10, 'Ubuntu 10.04 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (127, UUID(), 10, 'Ubuntu 9.10 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (128, UUID(), 10, 'Ubuntu 9.04 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (129, UUID(), 10, 'Ubuntu 8.10 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (130, UUID(), 10, 'Ubuntu 8.04 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (131, UUID(), 4, 'Red Hat Enterprise Linux 2'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (132, UUID(), 2, 'Debian GNU/Linux 6(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (133, UUID(), 2, 'Debian GNU/Linux 6(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (134, UUID(), 3, 'Oracle Enterprise Linux 5.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (135, UUID(), 3, 'Oracle Enterprise Linux 5.5 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (136, UUID(), 4, 'Red Hat Enterprise Linux 6.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (137, UUID(), 4, 'Red Hat Enterprise Linux 6.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (138, UUID(), 7, 'None'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (139, UUID(), 7, 'Other PV (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (140, UUID(), 7, 'Other PV (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (141, UUID(), 1, 'CentOS 5.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (142, UUID(), 1, 'CentOS 5.6 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (143, UUID(), 1, 'CentOS 6.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (144, UUID(), 1, 'CentOS 6.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (145, UUID(), 3, 'Oracle Enterprise Linux 5.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (146, UUID(), 3, 'Oracle Enterprise Linux 5.6 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (147, UUID(), 3, 'Oracle Enterprise Linux 6.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (148, UUID(), 3, 'Oracle Enterprise Linux 6.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (149, UUID(), 4, 'Red Hat Enterprise Linux 5.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (150, UUID(), 4, 'Red Hat Enterprise Linux 5.6 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (151, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (152, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (153, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (154, UUID(), 5, 'SUSE Linux Enterprise Server 11 SP1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (155, UUID(), 5, 'SUSE Linux Enterprise Server 11 SP1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (156, UUID(), 10, 'Ubuntu 10.10 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (157, UUID(), 10, 'Ubuntu 10.10 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (158, UUID(), 9, 'Sun Solaris 11 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (159, UUID(), 9, 'Sun Solaris 11 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (160, UUID(), 6, 'Windows PV'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (161, UUID(), 1, 'CentOS 5.7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (162, UUID(), 1, 'CentOS 5.7 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (163, UUID(), 10, 'Ubuntu 12.04 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (164, UUID(), 10, 'Ubuntu 12.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (200, 1, 'Other CentOS (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (201, 1, 'Other CentOS (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (202, 5, 'Other SUSE Linux(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (203, 5, 'Other SUSE Linux(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (200, UUID(), 1, 'Other CentOS (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (201, UUID(), 1, 'Other CentOS (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (202, UUID(), 5, 'Other SUSE Linux(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, display_name) VALUES (203, UUID(), 5, 'Other SUSE Linux(64-bit)'); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.5 (32-bit)', 1); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.6 (32-bit)', 2); @@ -370,11 +372,13 @@ INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 4(32-bit)', 73); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 4(64-bit)', 74); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 12.04 (32-bit)', 162); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 10.04 (32-bit)', 121); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 9.10 (32-bit)', 122); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 9.04 (32-bit)', 123); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 8.10 (32-bit)', 124); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 8.04 (32-bit)', 125); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 12.04 (64-bit)', 163); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 10.04 (64-bit)', 126); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 9.10 (64-bit)', 127); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu 9.04 (64-bit)', 128); @@ -385,6 +389,7 @@ INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other Ubuntu Linux (32-bit)', 59); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other Ubuntu (64-bit)', 100); + INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other 2.6x Linux (32-bit)', 75); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other 2.6x Linux (64-bit)', 76); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other Linux (32-bit)', 98); @@ -454,6 +459,8 @@ INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 8', 120); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 121); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 126); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 162); +INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 163); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.10', 122); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.10', 127); INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.04', 123); diff --git a/setup/db/templates.vmware.sql b/setup/db/templates.vmware.sql index 02d72986a50..845a720d1c3 100644 --- a/setup/db/templates.vmware.sql +++ b/setup/db/templates.vmware.sql @@ -15,85 +15,85 @@ -- specific language governing permissions and limitations -- under the License. -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (2, 'blank', 'BlankVM', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/blankvm.tar.bz2', '3eff7ce3d25cf9433efde8b245c63fcb', 0, 'BlankVM', 'VMDK', 47, 1, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (3, 'winxpsp3', 'WindowsXP-SP3', 1, now(), 'ntfs', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/winxpsp3.tar.bz2', '385e67d17a2cb3795bd0b0fb7f88dc5e', 0, 'WindowsXP-SP3', 'VMDK', 16, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (2, UUID(), 'blank', 'BlankVM', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/blankvm.tar.bz2', '3eff7ce3d25cf9433efde8b245c63fcb', 0, 'BlankVM', 'VMDK', 47, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (3, UUID(), 'winxpsp3', 'WindowsXP-SP3', 1, now(), 'ntfs', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/winxpsp3.tar.bz2', '385e67d17a2cb3795bd0b0fb7f88dc5e', 0, 'WindowsXP-SP3', 'VMDK', 16, 1, 1); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'Windows'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Linux'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (3, 'Novell Netware'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (4, 'Solaris'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'Other'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (1, UUID(), 'Windows'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (2, UUID(), 'Linux'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (3, UUID(), 'Novell Netware'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (4, UUID(), 'Solaris'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (5, UUID(), 'Other'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (1, 1, 'Microsoft Windows 7(32-bit)', 'Microsoft Windows 7(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (2, 1, 'Microsoft Windows 7(64-bit)', 'Microsoft Windows 7(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (3, 1, 'Microsoft Windows Server 2008 R2(64-bit)', 'Microsoft Windows Server 2008 R2(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (4, 1, 'Microsoft Windows Server 2008(32-bit)', 'Microsoft Windows Server 2008(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (5, 1, 'Microsoft Windows Server 2008(64-bit)', 'Windows Windows Server 2008(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (6, 1, 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (7, 1, 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (8, 1, 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (9, 1, 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (10, 1, 'Microsoft Windows Server 2003, Standard Edition (32-bit)', 'Microsoft Windows Server 2003, Standard Edition (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (11, 1, 'Microsoft Windows Server 2003, Standard Edition (64-bit)', 'Microsoft Windows Server 2003, Standard Edition (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (12, 1, 'Microsoft Windows Server 2003, Web Edition', 'Microsoft Windows Server 2003, Web Edition'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (13, 1, 'Microsoft Small Bussiness Server 2003', 'Microsoft Small Bussiness Server 2003'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (14, 1, 'Microsoft Windows Vista (32-bit)', 'Microsoft Windows Vista (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (15, 1, 'Microsoft Windows Vista (64-bit)', 'Microsoft Windows Vista (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (16, 1, 'Microsoft Windows XP Professional (32-bit)', 'Microsoft Windows XP Professional (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (17, 1, 'Microsoft Windows XP Professional (64-bit)', 'Microsoft Windows XP Professional (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (18, 1, 'Microsoft Windows 2000 Advanced Server', 'Microsoft Windows 2000 Advanced Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (19, 1, 'Microsoft Windows 2000 Server', 'Microsoft Windows 2000 Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (20, 1, 'Microsoft Windows 2000 Professional', 'Microsoft Windows 2000 Professional'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (21, 1, 'Microsoft Windows 98', 'Microsoft Windows 98'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (22, 1, 'Microsoft Windows 95', 'Microsoft Windows 95'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (23, 1, 'Microsoft Windows NT 4', 'Microsoft Windows NT 4'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (24, 1, 'Microsoft Windows 3.1', 'Microsoft Windows 3.1'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (1, UUID(), 1, 'Microsoft Windows 7(32-bit)', 'Microsoft Windows 7(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (2, UUID(), 1, 'Microsoft Windows 7(64-bit)', 'Microsoft Windows 7(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (3, UUID(), 1, 'Microsoft Windows Server 2008 R2(64-bit)', 'Microsoft Windows Server 2008 R2(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (4, UUID(), 1, 'Microsoft Windows Server 2008(32-bit)', 'Microsoft Windows Server 2008(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (5, UUID(), 1, 'Microsoft Windows Server 2008(64-bit)', 'Windows Windows Server 2008(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (6, UUID(), 1, 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (7, UUID(), 1, 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (8, UUID(), 1, 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (9, UUID(), 1, 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (10, UUID(), 1, 'Microsoft Windows Server 2003, Standard Edition (32-bit)', 'Microsoft Windows Server 2003, Standard Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (11, UUID(), 1, 'Microsoft Windows Server 2003, Standard Edition (64-bit)', 'Microsoft Windows Server 2003, Standard Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (12, UUID(), 1, 'Microsoft Windows Server 2003, Web Edition', 'Microsoft Windows Server 2003, Web Edition'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (13, UUID(), 1, 'Microsoft Small Bussiness Server 2003', 'Microsoft Small Bussiness Server 2003'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (14, UUID(), 1, 'Microsoft Windows Vista (32-bit)', 'Microsoft Windows Vista (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (15, UUID(), 1, 'Microsoft Windows Vista (64-bit)', 'Microsoft Windows Vista (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (16, UUID(), 1, 'Microsoft Windows XP Professional (32-bit)', 'Microsoft Windows XP Professional (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (17, UUID(), 1, 'Microsoft Windows XP Professional (64-bit)', 'Microsoft Windows XP Professional (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (18, UUID(), 1, 'Microsoft Windows 2000 Advanced Server', 'Microsoft Windows 2000 Advanced Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (19, UUID(), 1, 'Microsoft Windows 2000 Server', 'Microsoft Windows 2000 Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (20, UUID(), 1, 'Microsoft Windows 2000 Professional', 'Microsoft Windows 2000 Professional'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (21, UUID(), 1, 'Microsoft Windows 98', 'Microsoft Windows 98'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (22, UUID(), 1, 'Microsoft Windows 95', 'Microsoft Windows 95'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (23, UUID(), 1, 'Microsoft Windows NT 4', 'Microsoft Windows NT 4'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (24, UUID(), 1, 'Microsoft Windows 3.1', 'Microsoft Windows 3.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (25, 2, 'Red Hat Enterprise Linux 5(32-bit)', 'Red Hat Enterprise Linux 5(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (26, 2, 'Red Hat Enterprise Linux 5(64-bit)', 'Red Hat Enterprise Linux 5(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (27, 2, 'Red Hat Enterprise Linux 4(32-bit)', 'Red Hat Enterprise Linux 4(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (28, 2, 'Red Hat Enterprise Linux 4(64-bit)', 'Red Hat Enterprise Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (29, 2, 'Red Hat Enterprise Linux 3(32-bit)', 'Red Hat Enterprise Linux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (30, 2, 'Red Hat Enterprise Linux 3(64-bit)', 'Red Hat Enterprise Linux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (31, 2, 'Red Hat Enterprise Linux 2', 'Red Hat Enterprise Linux 2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (32, 2, 'Suse Linux Enterprise 11(32-bit)', 'Suse Linux Enterprise 11(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (33, 2, 'Suse Linux Enterprise 11(64-bit)', 'Suse Linux Enterprise 11(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (34, 2, 'Suse Linux Enterprise 10(32-bit)', 'Suse Linux Enterprise 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (35, 2, 'Suse Linux Enterprise 10(64-bit)', 'Suse Linux Enterprise 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (36, 2, 'Suse Linux Enterprise 8/9(32-bit)', 'Suse Linux Enterprise 8/9(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (37, 2, 'Suse Linux Enterprise 8/9(64-bit)', 'Suse Linux Enterprise 8/9(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (38, 2, 'Open Enterprise Server', 'Open Enterprise Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (39, 2, 'Asianux 3(32-bit)', 'Asianux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (40, 2, 'Asianux 3(64-bit)', 'Asianux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (41, 2, 'Debian GNU/Linux 5(32-bit)', 'Debian GNU/Linux 5(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (42, 2, 'Debian GNU/Linux 5(64-bit)', 'Debian GNU/Linux 5(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (43, 2, 'Debian GNU/Linux 4(32-bit)', 'Debian GNU/Linux 4(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (44, 2, 'Debian GNU/Linux 4(64-bit)', 'Debian GNU/Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (45, 2, 'Ubuntu Linux (32-bit)', 'Ubuntu Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (46, 2, 'Ubuntu Linux (64-bit)', 'Ubuntu Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (47, 2, 'Other 2.6x Linux (32-bit)', 'Other 2.6x Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (48, 2, 'Other 2.6x Linux (64-bit)', 'Other 2.6x Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (49, 2, 'Other Linux (32-bit)', 'Other Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (50, 2, 'Other Linux (64-bit)', 'Other Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (25, UUID(), 2, 'Red Hat Enterprise Linux 5(32-bit)', 'Red Hat Enterprise Linux 5(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (26, UUID(), 2, 'Red Hat Enterprise Linux 5(64-bit)', 'Red Hat Enterprise Linux 5(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (27, UUID(), 2, 'Red Hat Enterprise Linux 4(32-bit)', 'Red Hat Enterprise Linux 4(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (28, UUID(), 2, 'Red Hat Enterprise Linux 4(64-bit)', 'Red Hat Enterprise Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (29, UUID(), 2, 'Red Hat Enterprise Linux 3(32-bit)', 'Red Hat Enterprise Linux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (30, UUID(), 2, 'Red Hat Enterprise Linux 3(64-bit)', 'Red Hat Enterprise Linux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (31, UUID(), 2, 'Red Hat Enterprise Linux 2', 'Red Hat Enterprise Linux 2'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (32, UUID(), 2, 'Suse Linux Enterprise 11(32-bit)', 'Suse Linux Enterprise 11(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (33, UUID(), 2, 'Suse Linux Enterprise 11(64-bit)', 'Suse Linux Enterprise 11(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (34, UUID(), 2, 'Suse Linux Enterprise 10(32-bit)', 'Suse Linux Enterprise 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (35, UUID(), 2, 'Suse Linux Enterprise 10(64-bit)', 'Suse Linux Enterprise 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (36, UUID(), 2, 'Suse Linux Enterprise 8/9(32-bit)', 'Suse Linux Enterprise 8/9(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (37, UUID(), 2, 'Suse Linux Enterprise 8/9(64-bit)', 'Suse Linux Enterprise 8/9(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (38, UUID(), 2, 'Open Enterprise Server', 'Open Enterprise Server'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (39, UUID(), 2, 'Asianux 3(32-bit)', 'Asianux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (40, UUID(), 2, 'Asianux 3(64-bit)', 'Asianux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (41, UUID(), 2, 'Debian GNU/Linux 5(32-bit)', 'Debian GNU/Linux 5(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (42, UUID(), 2, 'Debian GNU/Linux 5(64-bit)', 'Debian GNU/Linux 5(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (43, UUID(), 2, 'Debian GNU/Linux 4(32-bit)', 'Debian GNU/Linux 4(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (44, UUID(), 2, 'Debian GNU/Linux 4(64-bit)', 'Debian GNU/Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (45, UUID(), 2, 'Ubuntu Linux (32-bit)', 'Ubuntu Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (46, UUID(), 2, 'Ubuntu Linux (64-bit)', 'Ubuntu Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (47, UUID(), 2, 'Other 2.6x Linux (32-bit)', 'Other 2.6x Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (48, UUID(), 2, 'Other 2.6x Linux (64-bit)', 'Other 2.6x Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (49, UUID(), 2, 'Other Linux (32-bit)', 'Other Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (50, UUID(), 2, 'Other Linux (64-bit)', 'Other Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (51, 3, 'Novell Netware 6.x', 'Novell Netware 6.x'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (52, 3, 'Novell Netware 5.1', 'Novell Netware 5.1'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (51, UUID(), 3, 'Novell Netware 6.x', 'Novell Netware 6.x'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (52, UUID(), 3, 'Novell Netware 5.1', 'Novell Netware 5.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (53, 4, 'Sun Solaris 10(32-bit)', 'Sun Solaris 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (54, 4, 'Sun Solaris 10(64-bit)', 'Sun Solaris 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (55, 4, 'Sun Solaris 9(Experimental)', 'Sun Solaris 9(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (56, 4, 'Sun Solaris 8(Experimental)', 'Sun Solaris 8(Experimental)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (53, UUID(), 4, 'Sun Solaris 10(32-bit)', 'Sun Solaris 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (54, UUID(), 4, 'Sun Solaris 10(64-bit)', 'Sun Solaris 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (55, UUID(), 4, 'Sun Solaris 9(Experimental)', 'Sun Solaris 9(Experimental)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (56, UUID(), 4, 'Sun Solaris 8(Experimental)', 'Sun Solaris 8(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (57, 5, 'FreeBSD (32-bit)', 'FreeBSD (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (58, 5, 'FreeBSD (64-bit)', 'FreeBSD (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (59, 5, 'OS/2', 'OS/2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (60, 5, 'SCO OpenServer 5', 'SCO OpenServer 5'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (61, 5, 'SCO UnixWare 7', 'SCO UnixWare 7'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (62, 5, 'DOS', 'DOS'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (63, 5, 'Other (32-bit)', 'Other (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (64, 5, 'Other (64-bit)', 'Other (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (57, UUID(), 5, 'FreeBSD (32-bit)', 'FreeBSD (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (58, UUID(), 5, 'FreeBSD (64-bit)', 'FreeBSD (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (59, UUID(), 5, 'OS/2', 'OS/2'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (60, UUID(), 5, 'SCO OpenServer 5', 'SCO OpenServer 5'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (61, UUID(), 5, 'SCO UnixWare 7', 'SCO UnixWare 7'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (62, UUID(), 5, 'DOS', 'DOS'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (63, UUID(), 5, 'Other (32-bit)', 'Other (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (64, UUID(), 5, 'Other (64-bit)', 'Other (64-bit)'); -- temporarily added for vmware, will be moved when vmware support is fully in-place diff --git a/setup/db/templates.xenserver.sql b/setup/db/templates.xenserver.sql index c8b6d6d3718..a44d42bb19a 100644 --- a/setup/db/templates.xenserver.sql +++ b/setup/db/templates.xenserver.sql @@ -15,91 +15,91 @@ -- specific language governing permissions and limitations -- under the License. -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/releases/2.2/systemvm.vhd.bz2', 'bcc7f290f4c27ab4d0fe95d1012829ea', 0, 'SystemVM Template', 'VHD', 15, 0, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (2, 'centos53-x86_64', 'CentOS 5.3(x86_64) no GUI(Xenserver)', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'CentOS 5.3(x86_64) no GUI', 'VHD', 12, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (1, UUID(), 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/releases/2.2/systemvm.vhd.bz2', 'bcc7f290f4c27ab4d0fe95d1012829ea', 0, 'SystemVM Template', 'VHD', 15, 0, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (2, UUID(), 'centos53-x86_64', 'CentOS 5.3(x86_64) no GUI(Xenserver)', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'CentOS 5.3(x86_64) no GUI', 'VHD', 12, 1, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) - VALUES (3, 'routing', 'DomR Template(KVM)', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/a88232bf-6a18-38e7-aeee-c1702725079f.qcow2.bz2', 'e39c55e93ae96bd43bfd588ca6ee3269', 'DomR Template', 0, 'QCOW2', 21, 0, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) - VALUES (4, 'centos55-x86_64', 'CentOS 5.5(x86_64) no GUI(KVM)', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', '1da20ae69b54f761f3f733dce97adcc0', 'CentOS 5.5(x86_64) no GUI', 0, 'QCOW2', 9, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) + VALUES (3, UUID(), 'routing', 'DomR Template(KVM)', 0, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/a88232bf-6a18-38e7-aeee-c1702725079f.qcow2.bz2', 'e39c55e93ae96bd43bfd588ca6ee3269', 'DomR Template', 0, 'QCOW2', 21, 0, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones) + VALUES (4, UUID(), 'centos55-x86_64', 'CentOS 5.5(x86_64) no GUI(KVM)', 1, now(), 'ext3', 0, 64, 1, 'http://download.cloud.com/templates/builtin/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', '1da20ae69b54f761f3f733dce97adcc0', 'CentOS 5.5(x86_64) no GUI', 0, 'QCOW2', 9, 1, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (5, 'blank', 'BlankVM', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/blankvm.tar.bz2', '3eff7ce3d25cf9433efde8b245c63fcb', 0, 'BlankVM', 'VMDK', 47, 1, 1); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) - VALUES (6, 'winxpsp3', 'WindowsXP-SP3', 1, now(), 'ntfs', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/winxpsp3.tar.bz2', '385e67d17a2cb3795bd0b0fb7f88dc5e', 0, 'WindowsXP-SP3', 'VMDK', 16, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (5, UUID(), 'blank', 'BlankVM', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/blankvm.tar.bz2', '3eff7ce3d25cf9433efde8b245c63fcb', 0, 'BlankVM', 'VMDK', 47, 1, 1); +INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones) + VALUES (6, UUID(), 'winxpsp3', 'WindowsXP-SP3', 1, now(), 'ntfs', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/winxpsp3.tar.bz2', '385e67d17a2cb3795bd0b0fb7f88dc5e', 0, 'WindowsXP-SP3', 'VMDK', 16, 1, 1); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'CentOS'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Debian'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (3, 'Oracle'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (4, 'RedHat'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'SUSE'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (6, 'Windows'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (7, 'Other'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (1, UUID(), 'CentOS'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (2, UUID(), 'Debian'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (3, UUID(), 'Oracle'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (4, UUID(), 'RedHat'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (5, UUID(), 'SUSE'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (6, UUID(), 'Windows'); +INSERT INTO `cloud`.`guest_os_category` (id, uuid, name) VALUES (7, UUID(), 'Other'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (1, 1, 'CentOS 4.5 (32-bit)', 'CentOS 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (2, 1, 'CentOS 4.6 (32-bit)', 'CentOS 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (3, 1, 'CentOS 4.7 (32-bit)', 'CentOS 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (4, 1, 'CentOS 4.8 (32-bit)', 'CentOS 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (5, 1, 'CentOS 5.0 (32-bit)', 'CentOS 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (6, 1, 'CentOS 5.0 (64-bit)', 'CentOS 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (7, 1, 'CentOS 5.1 (32-bit)', 'CentOS 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (8, 1, 'CentOS 5.1 (64-bit)', 'CentOS 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (9, 1, 'CentOS 5.2 (32-bit)', 'CentOS 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (10, 1, 'CentOS 5.2 (64-bit)', 'CentOS 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (11, 1, 'CentOS 5.3 (32-bit)', 'CentOS 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (12, 1, 'CentOS 5.3 (64-bit)', 'CentOS 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (13, 1, 'CentOS 5.4 (32-bit)', 'CentOS 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (14, 1, 'CentOS 5.4 (64-bit)', 'CentOS 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (15, 2, 'Debian Lenny 5.0 (32-bit)', 'Debian Lenny 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (16, 3, 'Oracle Enterprise Linux 5.0 (32-bit)', 'Oracle Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (17, 3, 'Oracle Enterprise Linux 5.0 (64-bit)', 'Oracle Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (18, 3, 'Oracle Enterprise Linux 5.1 (32-bit)', 'Oracle Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (19, 3, 'Oracle Enterprise Linux 5.1 (64-bit)', 'Oracle Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (20, 3, 'Oracle Enterprise Linux 5.2 (32-bit)', 'Oracle Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (21, 3, 'Oracle Enterprise Linux 5.2 (64-bit)', 'Oracle Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (22, 3, 'Oracle Enterprise Linux 5.3 (32-bit)', 'Oracle Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (23, 3, 'Oracle Enterprise Linux 5.3 (64-bit)', 'Oracle Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (24, 3, 'Oracle Enterprise Linux 5.4 (32-bit)', 'Oracle Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (25, 3, 'Oracle Enterprise Linux 5.4 (64-bit)', 'Oracle Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (26, 4, 'Red Hat Enterprise Linux 4.5 (32-bit)', 'Red Hat Enterprise Linux 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (27, 4, 'Red Hat Enterprise Linux 4.6 (32-bit)', 'Red Hat Enterprise Linux 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (28, 4, 'Red Hat Enterprise Linux 4.7 (32-bit)', 'Red Hat Enterprise Linux 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (29, 4, 'Red Hat Enterprise Linux 4.8 (32-bit)', 'Red Hat Enterprise Linux 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (30, 4, 'Red Hat Enterprise Linux 5.0 (32-bit)', 'Red Hat Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (31, 4, 'Red Hat Enterprise Linux 5.0 (64-bit)', 'Red Hat Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (32, 4, 'Red Hat Enterprise Linux 5.1 (32-bit)', 'Red Hat Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (33, 4, 'Red Hat Enterprise Linux 5.1 (64-bit)', 'Red Hat Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (34, 4, 'Red Hat Enterprise Linux 5.2 (32-bit)', 'Red Hat Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (35, 4, 'Red Hat Enterprise Linux 5.2 (64-bit)', 'Red Hat Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (36, 4, 'Red Hat Enterprise Linux 5.3 (32-bit)', 'Red Hat Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (37, 4, 'Red Hat Enterprise Linux 5.3 (64-bit)', 'Red Hat Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (38, 4, 'Red Hat Enterprise Linux 5.4 (32-bit)', 'Red Hat Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (39, 4, 'Red Hat Enterprise Linux 5.4 (64-bit)', 'Red Hat Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (40, 5, 'SUSE Linux Enterprise Server 9 SP4 (32-bit)', 'SUSE Linux Enterprise Server 9 SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (41, 5, 'SUSE Linux Enterprise Server 10 SP1 (32-bit)', 'SUSE Linux Enterprise Server 10 SP1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (42, 5, 'SUSE Linux Enterprise Server 10 SP1 (64-bit)', 'SUSE Linux Enterprise Server 10 SP1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (43, 5, 'SUSE Linux Enterprise Server 10 SP2 (32-bit)', 'SUSE Linux Enterprise Server 10 SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (44, 5, 'SUSE Linux Enterprise Server 10 SP2 (64-bit)', 'SUSE Linux Enterprise Server 10 SP2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (45, 5, 'SUSE Linux Enterprise Server 10 SP3 (64-bit)', 'SUSE Linux Enterprise Server 10 SP3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (46, 5, 'SUSE Linux Enterprise Server 11 (32-bit)', 'SUSE Linux Enterprise Server 11 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (47, 5, 'SUSE Linux Enterprise Server 11 (64-bit)', 'SUSE Linux Enterprise Server 11 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (48, 6, 'Windows 7 (32-bit)', 'Windows 7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (49, 6, 'Windows 7 (64-bit)', 'Windows 7 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (50, 6, 'Windows Server 2003 (32-bit)', 'Windows Server 2003 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (51, 6, 'Windows Server 2003 (64-bit)', 'Windows Server 2003 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (52, 6, 'Windows Server 2008 (32-bit)', 'Windows Server 2008 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (53, 6, 'Windows Server 2008 (64-bit)', 'Windows Server 2008 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (54, 6, 'Windows Server 2008 R2 (64-bit)', 'Windows Server 2008 R2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (55, 6, 'Windows 2000 SP4 (32-bit)', 'Windows 2000 SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (56, 6, 'Windows Vista (32-bit)', 'Windows Vista (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (57, 6, 'Windows XP SP2 (32-bit)', 'Windows XP SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (58, 6, 'Windows XP SP3 (32-bit)', 'Windows XP SP3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (59, 7, 'Other install media', 'Ubuntu'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (60, 7, 'Other install media', 'Other'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (61, 2, 'Ubuntu 10.04 (64-bit)', 'Ubuntu 10.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (62, 2, 'Ubuntu 10.04 (32-bit)', 'Ubuntu 10.04 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (1, UUID(), 1, 'CentOS 4.5 (32-bit)', 'CentOS 4.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (2, UUID(), 1, 'CentOS 4.6 (32-bit)', 'CentOS 4.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (3, UUID(), 1, 'CentOS 4.7 (32-bit)', 'CentOS 4.7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (4, UUID(), 1, 'CentOS 4.8 (32-bit)', 'CentOS 4.8 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (5, UUID(), 1, 'CentOS 5.0 (32-bit)', 'CentOS 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (6, UUID(), 1, 'CentOS 5.0 (64-bit)', 'CentOS 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (7, UUID(), 1, 'CentOS 5.1 (32-bit)', 'CentOS 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (8, UUID(), 1, 'CentOS 5.1 (64-bit)', 'CentOS 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (9, UUID(), 1, 'CentOS 5.2 (32-bit)', 'CentOS 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (10, UUID(), 1, 'CentOS 5.2 (64-bit)', 'CentOS 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (11, UUID(), 1, 'CentOS 5.3 (32-bit)', 'CentOS 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (12, UUID(), 1, 'CentOS 5.3 (64-bit)', 'CentOS 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (13, UUID(), 1, 'CentOS 5.4 (32-bit)', 'CentOS 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (14, UUID(), 1, 'CentOS 5.4 (64-bit)', 'CentOS 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (15, UUID(), 2, 'Debian Lenny 5.0 (32-bit)', 'Debian Lenny 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (16, UUID(), 3, 'Oracle Enterprise Linux 5.0 (32-bit)', 'Oracle Enterprise Linux 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (17, UUID(), 3, 'Oracle Enterprise Linux 5.0 (64-bit)', 'Oracle Enterprise Linux 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (18, UUID(), 3, 'Oracle Enterprise Linux 5.1 (32-bit)', 'Oracle Enterprise Linux 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (19, UUID(), 3, 'Oracle Enterprise Linux 5.1 (64-bit)', 'Oracle Enterprise Linux 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (20, UUID(), 3, 'Oracle Enterprise Linux 5.2 (32-bit)', 'Oracle Enterprise Linux 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (21, UUID(), 3, 'Oracle Enterprise Linux 5.2 (64-bit)', 'Oracle Enterprise Linux 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (22, UUID(), 3, 'Oracle Enterprise Linux 5.3 (32-bit)', 'Oracle Enterprise Linux 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (23, UUID(), 3, 'Oracle Enterprise Linux 5.3 (64-bit)', 'Oracle Enterprise Linux 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (24, UUID(), 3, 'Oracle Enterprise Linux 5.4 (32-bit)', 'Oracle Enterprise Linux 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (25, UUID(), 3, 'Oracle Enterprise Linux 5.4 (64-bit)', 'Oracle Enterprise Linux 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (26, UUID(), 4, 'Red Hat Enterprise Linux 4.5 (32-bit)', 'Red Hat Enterprise Linux 4.5 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (27, UUID(), 4, 'Red Hat Enterprise Linux 4.6 (32-bit)', 'Red Hat Enterprise Linux 4.6 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (28, UUID(), 4, 'Red Hat Enterprise Linux 4.7 (32-bit)', 'Red Hat Enterprise Linux 4.7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (29, UUID(), 4, 'Red Hat Enterprise Linux 4.8 (32-bit)', 'Red Hat Enterprise Linux 4.8 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (30, UUID(), 4, 'Red Hat Enterprise Linux 5.0 (32-bit)', 'Red Hat Enterprise Linux 5.0 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (31, UUID(), 4, 'Red Hat Enterprise Linux 5.0 (64-bit)', 'Red Hat Enterprise Linux 5.0 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (32, UUID(), 4, 'Red Hat Enterprise Linux 5.1 (32-bit)', 'Red Hat Enterprise Linux 5.1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (33, UUID(), 4, 'Red Hat Enterprise Linux 5.1 (64-bit)', 'Red Hat Enterprise Linux 5.1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (34, UUID(), 4, 'Red Hat Enterprise Linux 5.2 (32-bit)', 'Red Hat Enterprise Linux 5.2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (35, UUID(), 4, 'Red Hat Enterprise Linux 5.2 (64-bit)', 'Red Hat Enterprise Linux 5.2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (36, UUID(), 4, 'Red Hat Enterprise Linux 5.3 (32-bit)', 'Red Hat Enterprise Linux 5.3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (37, UUID(), 4, 'Red Hat Enterprise Linux 5.3 (64-bit)', 'Red Hat Enterprise Linux 5.3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (38, UUID(), 4, 'Red Hat Enterprise Linux 5.4 (32-bit)', 'Red Hat Enterprise Linux 5.4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (39, UUID(), 4, 'Red Hat Enterprise Linux 5.4 (64-bit)', 'Red Hat Enterprise Linux 5.4 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (40, UUID(), 5, 'SUSE Linux Enterprise Server 9 SP4 (32-bit)', 'SUSE Linux Enterprise Server 9 SP4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (41, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP1 (32-bit)', 'SUSE Linux Enterprise Server 10 SP1 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (42, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP1 (64-bit)', 'SUSE Linux Enterprise Server 10 SP1 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (43, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP2 (32-bit)', 'SUSE Linux Enterprise Server 10 SP2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (44, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP2 (64-bit)', 'SUSE Linux Enterprise Server 10 SP2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (45, UUID(), 5, 'SUSE Linux Enterprise Server 10 SP3 (64-bit)', 'SUSE Linux Enterprise Server 10 SP3 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (46, UUID(), 5, 'SUSE Linux Enterprise Server 11 (32-bit)', 'SUSE Linux Enterprise Server 11 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (47, UUID(), 5, 'SUSE Linux Enterprise Server 11 (64-bit)', 'SUSE Linux Enterprise Server 11 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (48, UUID(), 6, 'Windows 7 (32-bit)', 'Windows 7 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (49, UUID(), 6, 'Windows 7 (64-bit)', 'Windows 7 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (50, UUID(), 6, 'Windows Server 2003 (32-bit)', 'Windows Server 2003 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (51, UUID(), 6, 'Windows Server 2003 (64-bit)', 'Windows Server 2003 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (52, UUID(), 6, 'Windows Server 2008 (32-bit)', 'Windows Server 2008 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (53, UUID(), 6, 'Windows Server 2008 (64-bit)', 'Windows Server 2008 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (54, UUID(), 6, 'Windows Server 2008 R2 (64-bit)', 'Windows Server 2008 R2 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (55, UUID(), 6, 'Windows 2000 SP4 (32-bit)', 'Windows 2000 SP4 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (56, UUID(), 6, 'Windows Vista (32-bit)', 'Windows Vista (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (57, UUID(), 6, 'Windows XP SP2 (32-bit)', 'Windows XP SP2 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (58, UUID(), 6, 'Windows XP SP3 (32-bit)', 'Windows XP SP3 (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (59, UUID(), 7, 'Other install media', 'Ubuntu'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (60, UUID(), 7, 'Other install media', 'Other'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (61, UUID(), 2, 'Ubuntu 10.04 (64-bit)', 'Ubuntu 10.04 (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, uuid, category_id, name, display_name) VALUES (62, UUID(), 2, 'Ubuntu 10.04 (32-bit)', 'Ubuntu 10.04 (32-bit)'); -- temporarily added for vmware, will be moved when vmware support is fully in-place INSERT INTO `cloud`.`host_master`(`type`, `service_address`, `admin`, `password`) VALUES('VSphere', '192.168.90.238', 'Administrator', 'Suite219'); diff --git a/test/integration/smoke/test_iso.py b/test/integration/smoke/test_iso.py index 22d424f86cc..8228a278cc9 100644 --- a/test/integration/smoke/test_iso.py +++ b/test/integration/smoke/test_iso.py @@ -219,14 +219,14 @@ class TestISO(cloudstackTestCase): # Finding the OsTypeId from Ostype ostypes = list_os_types( cls.api_client, - description=self.services["ostype"] + description=cls.services["ostype"] ) if not isinstance(ostypes, list): raise unittest.SkipTest("OSTypeId for given description not found") - self.services["iso_1"]["ostypeid"] = ostypes[0].id - self.services["iso_2"]["ostypeid"] = ostypes[0].id - self.services["ostypeid"] = ostypes[0].id + cls.services["iso_1"]["ostypeid"] = ostypes[0].id + cls.services["iso_2"]["ostypeid"] = ostypes[0].id + cls.services["ostypeid"] = ostypes[0].id cls.iso_1 = Iso.create( cls.api_client, diff --git a/test/integration/smoke/test_routers.py b/test/integration/smoke/test_routers.py index 93dc7606ace..435c7e41a43 100644 --- a/test/integration/smoke/test_routers.py +++ b/test/integration/smoke/test_routers.py @@ -41,7 +41,7 @@ class Services: "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz - "memory": 64, # In MBs + "memory": 128, # In MBs }, "virtual_machine": { diff --git a/test/integration/smoke/test_service_offerings.py b/test/integration/smoke/test_service_offerings.py index 3a8a9e156b9..7f4d130ee80 100644 --- a/test/integration/smoke/test_service_offerings.py +++ b/test/integration/smoke/test_service_offerings.py @@ -39,7 +39,7 @@ class Services: "displaytext": "Service Offering", "cpunumber": 1, "cpuspeed": 100, # MHz - "memory": 64, # in MBs + "memory": 128, # in MBs }, } diff --git a/test/integration/smoke/test_templates.py b/test/integration/smoke/test_templates.py index d450a5d8122..663b174ed78 100644 --- a/test/integration/smoke/test_templates.py +++ b/test/integration/smoke/test_templates.py @@ -52,7 +52,7 @@ class Services: "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz - "memory": 64, # In MBs + "memory": 128, # In MBs }, "disk_offering": { "displaytext": "Small", diff --git a/test/integration/smoke/test_vm_life_cycle.py b/test/integration/smoke/test_vm_life_cycle.py index 1633c538342..0bd4f959bc3 100644 --- a/test/integration/smoke/test_vm_life_cycle.py +++ b/test/integration/smoke/test_vm_life_cycle.py @@ -80,7 +80,7 @@ class Services: "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz - "memory": 64, # In MBs + "memory": 128, # In MBs }, "small": { @@ -227,9 +227,9 @@ class TestDeployVM(cloudstackTestCase): ) self.assertEqual( - vm_response.displayname, - self.virtual_machine.displayname, - "Check virtual machine displayname in listVirtualMachines" + vm_response.name, + self.virtual_machine.name, + "Check virtual machine name in listVirtualMachines" ) return diff --git a/test/integration/smoke/test_volumes.py b/test/integration/smoke/test_volumes.py index 2d0cd491672..36eb5ded263 100644 --- a/test/integration/smoke/test_volumes.py +++ b/test/integration/smoke/test_volumes.py @@ -53,13 +53,21 @@ class Services: "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, # in MHz - "memory": 64, # In MBs + "memory": 128, # In MBs + "storagetype": "local" }, "disk_offering": { "displaytext": "Small", "name": "Small", + "storagetype": "local", "disksize": 1 }, + 'resized_disk_offering': { + "displaytext": "Resized", + "name": "Resized", + "storagetype": "local", + "disksize": 3 + }, "volume_offerings": { 0: { "diskname": "TestDiskServ", @@ -77,8 +85,8 @@ class Services: "diskdevice": "/dev/xvdb", "ostype": 'CentOS 5.3 (64-bit)', "mode": 'basic', - "sleep": 60, - "timeout": 10, + "sleep": 10, + "timeout": 600, } @@ -237,7 +245,7 @@ class TestCreateVolume(cloudstackTestCase): ssh = self.virtual_machine.get_ssh_client( reconnect=True ) - c = "fdisk -l" + c = "/sbin/fdisk -l" res = ssh.execute(c) except Exception as e: @@ -283,6 +291,16 @@ class TestVolumes(cloudstackTestCase): cls.api_client, cls.services["disk_offering"] ) + cls.resized_disk_offering = DiskOffering.create( + cls.api_client, + cls.services["resized_disk_offering"] + ) + cls.custom_resized_disk_offering = DiskOffering.create( + cls.api_client, + cls.services["resized_disk_offering"], + custom=True + ) + template = get_template( cls.api_client, cls.zone.id, @@ -292,6 +310,8 @@ class TestVolumes(cloudstackTestCase): cls.services["zoneid"] = cls.zone.id cls.services["template"] = template.id cls.services["diskofferingid"] = cls.disk_offering.id + cls.services['resizeddiskofferingid'] = cls.resized_disk_offering.id + cls.services['customresizeddiskofferingid'] = cls.custom_resized_disk_offering.id # Create VMs, VMs etc cls.account = Account.create( @@ -321,6 +341,8 @@ class TestVolumes(cloudstackTestCase): domainid=cls.account.account.domainid ) cls._cleanup = [ + cls.resized_disk_offering, + cls.custom_resized_disk_offering, cls.service_offering, cls.disk_offering, cls.account @@ -500,7 +522,102 @@ class TestVolumes(cloudstackTestCase): ) @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_07_delete_detached_volume(self): + def test_07_resize_fail(self): + """Verify invalid options fail to Resize a volume""" + # Verify the size is the new size is what we wanted it to be. + self.debug("Fail Resize Volume ID: %s" % self.volume.id) + + # first, an invalid id + cmd = resizeVolume.resizeVolumeCmd() + cmd.id = "invalid id" + cmd.diskofferingid = self.services['resizeddiskofferingid'] + success = False + try: + response = self.apiClient.resizeVolume(cmd) + except Exception as ex: + if str(ex) == "HTTP Error 431: 431": + success = True + self.assertEqual(success, True, "ResizeVolume - verify invalid id is handled appropriately") + + # Next, we'll try an invalid disk offering id + cmd.id = self.volume.id + cmd.diskofferingid = "invalid id" + success = False + try: + response = self.apiClient.resizeVolume(cmd) + except Exception as ex: + if "need to specify a disk offering" in str(ex): + success = True + self.assertEqual(success, True, "ResizeVolume - verify disk offering is handled appropriately") + + # Ok, now let's try and resize a volume that is not custom. + cmd.id = self.volume.id + cmd.diskofferingid = self.services['diskofferingid'] + cmd.size = 4 + currentSize = self.volume.size + + self.apiClient.resizeVolume(cmd) + count = 0 + success = True + while count < 10: + list_volume_response = list_volumes( + self.apiClient, + id=self.volume.id, + type='DATADISK' + ) + for vol in list_volume_response: + if vol.id == self.volume.id and vol.size != currentSize: + success = False + if success: + break + else: + time.sleep(1) + count += 1 + + self.assertEqual( + success, + True, + "Verify the volume did not resize" + ) + + + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_08_resize_volume(self): + """Resize a volume""" + # Verify the size is the new size is what we wanted it to be. + self.debug("Resize Volume ID: %s" % self.volume.id) + + cmd = resizeVolume.resizeVolumeCmd() + cmd.id = self.volume.id + cmd.diskofferingid = self.services['resizeddiskofferingid'] + + self.apiClient.resizeVolume(cmd) + + count = 0 + success = False + while count < 3: + list_volume_response = list_volumes( + self.apiClient, + id=self.volume.id, + type='DATADISK' + ) + for vol in list_volume_response: + if vol.id == self.volume.id and vol.size == 3221225472L: + success = True + if success: + break + else: + time.sleep(10) + count += 1 + + self.assertEqual( + success, + True, + "Check if the volume resized appropriately" + ) + + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_09_delete_detached_volume(self): """Delete a Volume unattached to an VM """ # Validate the following diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py index abff8d15980..7739aea633f 100644 --- a/tools/apidoc/gen_toc.py +++ b/tools/apidoc/gen_toc.py @@ -128,7 +128,8 @@ known_categories = { 'NiciraNvpDevice': 'Nicira NVP', 'AutoScale': 'AutoScale', 'Counter': 'AutoScale', - 'Condition': 'AutoScale' + 'Condition': 'AutoScale', + 'Api': 'API Discovery', } diff --git a/tools/apidoc/pom.xml b/tools/apidoc/pom.xml index b75ee826372..6b159ff54eb 100644 --- a/tools/apidoc/pom.xml +++ b/tools/apidoc/pom.xml @@ -57,7 +57,7 @@ ${client.config.jars} ./target -f - ${client.config.conf}/commands.properties,${client.config.conf}/commands-ext.properties,${client.config.conf}/virtualrouter_commands.properties,${client.config.conf}/nicira-nvp_commands.properties + ${client.config.conf}/commands.properties diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py index edb62ccc801..339a2014522 100644 --- a/tools/cli/cloudmonkey/cloudmonkey.py +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -84,6 +84,7 @@ class CloudMonkeyShell(cmd.Cmd, object): config = self.write_config() print "Welcome! Using `set` configure the necessary settings:" print " ".join(sorted(self.config_fields.keys())) + print "Config file:", self.config_file print "For debugging, tail -f", self.log_file, "\n" for key in self.config_fields.keys(): @@ -94,7 +95,7 @@ class CloudMonkeyShell(cmd.Cmd, object): print "Please fix `%s` config in %s" % (key, self.config_file) sys.exit() - self.prompt += " " # Cosmetic fix for prompt + self.prompt = self.prompt.strip() + " " # Cosmetic fix for prompt logging.basicConfig(filename=self.log_file, level=logging.DEBUG, format=log_fmt) logger.debug("Loaded config fields:\n%s" % self.config_fields) @@ -160,11 +161,11 @@ class CloudMonkeyShell(cmd.Cmd, object): elif 'type' in arg: print colored.green(arg), elif 'state' in arg or 'count' in arg: - print colored.yellow(arg), - elif 'id =' in arg: - print colored.cyan(arg), - elif 'name =' in arg: print colored.magenta(arg), + elif 'id =' in arg: + print colored.yellow(arg), + elif 'name =' in arg: + print colored.cyan(arg), else: print arg, else: @@ -203,7 +204,8 @@ class CloudMonkeyShell(cmd.Cmd, object): print printer def print_result_as_dict(result, result_filter=None): - for key in result.keys(): + for key in sorted(result.keys(), + key=lambda x: x != 'id' and x != 'count' and x): if not (isinstance(result[key], list) or isinstance(result[key], dict)): self.print_shell("%s = %s" % (key, result[key])) @@ -265,10 +267,18 @@ class CloudMonkeyShell(cmd.Cmd, object): command = "queryAsyncJobResult" requests = {'jobid': jobId} timeout = int(self.timeout) + pollperiod = 3 + progress = 1 while timeout > 0: + print '\r' + '.' * progress, + sys.stdout.flush() response = process_json(conn.make_request_with_auth(command, requests)) - result = response[response.keys()[0]] + responsekeys = filter(lambda x: 'response' in x, + response.keys()) + if len(responsekeys) < 1: + continue + result = response[responsekeys[0]] jobstatus = result['jobstatus'] if jobstatus == 2: jobresult = result["jobresult"] @@ -277,9 +287,11 @@ class CloudMonkeyShell(cmd.Cmd, object): jobresult["errortext"]) return elif jobstatus == 1: + print '\r', return response - time.sleep(4) - timeout = timeout - 4 + time.sleep(pollperiod) + timeout = timeout - pollperiod + progress += 1 logger.debug("job: %s to timeout in %ds" % (jobId, timeout)) self.print_shell("Error:", "Async query timeout for jobid=", jobId) @@ -346,37 +358,13 @@ class CloudMonkeyShell(cmd.Cmd, object): if result is None: return try: - # Response is in the key "apiname+response" (lowercase) - self.print_result(result[api_name.lower() + 'response'], - field_filter) + responsekeys = filter(lambda x: 'response' in x, result.keys()) + for responsekey in responsekeys: + self.print_result(result[responsekey], field_filter) print except Exception as e: self.print_shell("🙈 Error on parsing and printing", e) - def cache_verb_miss(self, verb): - self.print_shell("Oops: Verb %s should have been precached" % verb) - completions_found = filter(lambda x: x.startswith(verb), completions) - self.cache_verbs[verb] = {} - for api_name in completions_found: - api_cmd_str = "%sCmd" % api_name - api_mod = self.get_api_module(api_name, [api_cmd_str]) - if api_mod is None: - continue - try: - api_cmd = getattr(api_mod, api_cmd_str)() - required = api_cmd.required - doc = api_mod.__doc__ - except AttributeError, e: - self.print_shell("Error: API attribute %s not found!" % e) - params = filter(lambda x: '__' not in x and 'required' not in x, - dir(api_cmd)) - if len(required) > 0: - doc += "\nRequired args: %s" % " ".join(required) - doc += "\nArgs: %s" % " ".join(params) - api_name_lower = api_name.replace(verb, '').lower() - self.cache_verbs[verb][api_name_lower] = [api_name, params, doc, - required] - def completedefault(self, text, line, begidx, endidx): partitions = line.partition(" ") verb = partitions[0] @@ -391,9 +379,6 @@ class CloudMonkeyShell(cmd.Cmd, object): autocompletions = [] search_string = "" - if verb not in self.cache_verbs: - self.cache_verb_miss(verb) - if separator != " ": # Complete verb subjects autocompletions = self.cache_verbs[verb].keys() search_string = subject @@ -435,8 +420,8 @@ class CloudMonkeyShell(cmd.Cmd, object): """ args = args.strip().partition(" ") key, value = (args[0], args[2]) - # Note: keys and class attributes should have same names - setattr(self, key, value) + setattr(self, key, value) # keys and attributes should have same names + self.prompt = self.prompt.strip() + " " # prompt fix self.write_config() def complete_set(self, text, line, begidx, endidx): @@ -474,8 +459,6 @@ class CloudMonkeyShell(cmd.Cmd, object): else: verb = fields[0] subject = fields[2].partition(" ")[0] - if verb not in self.cache_verbs: - self.cache_verb_miss(verb) if subject in self.cache_verbs[verb]: self.print_shell(self.cache_verbs[verb][subject][2]) @@ -527,8 +510,6 @@ def main(): prog_name = "python " + prog_name self.do_shell("%s %s %s" % (prog_name, rule, args)) return - if not rule in self.cache_verbs: - self.cache_verb_miss(rule) try: args_partition = args.partition(" ") res = self.cache_verbs[rule][args_partition[0]] diff --git a/tools/devcloud-kvm/README.md b/tools/devcloud-kvm/README.md new file mode 100644 index 00000000000..3261fbe4b8e --- /dev/null +++ b/tools/devcloud-kvm/README.md @@ -0,0 +1,21 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. + +=========================================================== + +This directory hosts configs for setting up the devcloud-kvm +environment. diff --git a/tools/devcloud-kvm/devcloud-kvm-advanced.cfg b/tools/devcloud-kvm/devcloud-kvm-advanced.cfg new file mode 100644 index 00000000000..10cbce00779 --- /dev/null +++ b/tools/devcloud-kvm/devcloud-kvm-advanced.cfg @@ -0,0 +1,134 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + + +{ + "zones": [ + { + "localstorageenabled": "true", + "name": "testzone", + "guestcidraddress": "10.1.1.0/24", + "dns1": "8.8.8.8", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "vlan": "3900-4000", + "name": "eth0", + "traffictypes": [ + { + "kvm": "cloudbr0", + "typ": "Management" + }, + { + "kvm": "cloudbr0", + "typ": "Guest" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "ZONE", + "name": "VpcVirtualRouter" + } + ] + }, + { + "broadcastdomainrange": "Zone", + "name": "eth1", + "traffictypes": [ + { + "kvm": "cloudbr1", + "typ": "Public" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + } + ] + } + ], + "ipranges": [ + { + "startip": "192.168.100.100", + "endip": "192.168.100.199", + "netmask": "255.255.255.0", + "vlan": "untagged", + "gateway": "192.168.100.1" + } + ], + "networktype": "Advanced", + "pods": [ + { + "endip": "172.17.10.199", + "name": "testpod", + "startip": "172.17.10.100", + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "testcluster", + "hypervisor": "KVM", + "hosts": [ + { + "username": "root", + "url": "http://172.17.10.10/", + "password": "password" + } + ], + "clustertype": "CloudManaged" + } + ], + "gateway": "172.17.10.1" + } + ], + "internaldns1": "8.8.4.4", + "secondaryStorages": [ + { + "url": "nfs://172.17.10.10:/nfs/secondary" + } + ] + } + ], + "dbSvr": { + "dbSvr": "127.0.0.1", + "passwd": "cloud", + "db": "cloud", + "port": 3306, + "user": "cloud" + }, + "logger": [ + { + "name": "TestClient", + "file": "/var/log/testclient.log" + }, + { + "name": "TestCase", + "file": "/var/log/testcase.log" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "172.17.10.10", + "port": 8096 + } + ] +} diff --git a/tools/devcloud-kvm/devcloud-kvm.cfg b/tools/devcloud-kvm/devcloud-kvm.cfg new file mode 100644 index 00000000000..b3f048aac97 --- /dev/null +++ b/tools/devcloud-kvm/devcloud-kvm.cfg @@ -0,0 +1,117 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# This is a stock devcloud config converted from the file +# tools/devcloud/devcloud.cfg. + +{ + "zones": [ + { + "name": "DevCloudKVM0", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "name": "test-network", + "traffictypes": [ + { + "typ": "Guest" + }, + { + "typ": "Management" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "Pod", + "name": "SecurityGroupProvider" + } + ] + } + ], + "dns2": "4.4.4.4", + "dns1": "8.8.8.8", + "securitygroupenabled": "true", + "localstorageenabled": "true", + "networktype": "Basic", + "pods": [ + { + "endip": "192.168.100.250", + "name": "test00", + "startip": "192.168.100.200", + "guestIpRanges": [ + { + "startip": "192.168.100.100", + "endip": "192.168.100.199", + "netmask": "255.255.255.0", + "gateway": "192.168.100.1" + } + ], + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "test000", + "hypervisor": "KVM", + "hosts": [ + { + "username": "root", + "url": "http://192.168.100.10/", + "password": "password" + } + ], + "clustertype": "CloudManaged" + } + ], + "gateway": "192.168.100.1" + } + ], + "internaldns1": "192.168.100.10", + "secondaryStorages": [ + { + "url": "nfs://192.168.100.10:/nfs/secondary" + } + ] + } + ], + "logger": [ + { + "name": "TestClient", + "file": "/tmp/testclient.log" + }, + { + "name": "TestCase", + "file": "/tmp/testcase.log" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "127.0.0.1", + "port": 8096 + } + ], + "dbSvr": + { + "dbSvr": "127.0.0.1", + "port": 3306, + "user": "cloud", + "passwd": "cloud", + "db": "cloud" + } +} diff --git a/tools/devcloud-kvm/devcloud-kvm.py b/tools/devcloud-kvm/devcloud-kvm.py new file mode 100644 index 00000000000..dd551b58552 --- /dev/null +++ b/tools/devcloud-kvm/devcloud-kvm.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +''' +############################################################ +# Experimental state of scripts +# * Need to be reviewed +# * Only a sandbox +############################################################ +''' +import random +import marvin +from ConfigParser import SafeConfigParser +from optparse import OptionParser +from marvin.configGenerator import * + + +def getGlobalSettings(config): + for k, v in dict(config.items('globals')).iteritems(): + cfg = configuration() + cfg.name = k + cfg.value = v + yield cfg + + +def describeDevcloudKvmResources(config): + zs = cloudstackConfiguration() + + z = zone() + z.dns1 = config.get('environment', 'dns') + z.internaldns1 = config.get('environment', 'dns') + z.name = 'Devcloud-%s'%(config.get('cloudstack', 'hypervisor')) + z.networktype = 'Advanced' + z.guestcidraddress = '10.1.1.0/24' + z.localstorageenabled = 'true' + + vpcprovider = provider() + vpcprovider.name = 'VpcVirtualRouter' + + pn = physical_network() + pn.name = "eth0" + pn.vlan = config.get('cloudstack', 'pnet.vlan') + pn.tags = ["devcloud-guest"] + pn.traffictypes = [traffictype("Guest", {"kvm" :"kvm-guest" }), traffictype("Management")] + pn.providers.append(vpcprovider) + + pn2 = physical_network() + pn2.name = "eth1" + pn2.vlan = config.get('cloudstack', 'pnet2.vlan') + pn2.tags = ["devcloud-public"] + pn2.traffictypes = [traffictype("Public", {"kvm" : "kvm-public"})] + pn2.providers.append(vpcprovider) + + z.physical_networks.append(pn) + z.physical_networks.append(pn2) + + p = pod() + p.name = 'POD0' + p.gateway = config.get('cloudstack', 'private.gateway') + p.startip = config.get('cloudstack', 'private.pod.startip') + p.endip = config.get('cloudstack', 'private.pod.endip') + p.netmask = config.get('cloudstack', 'private.netmask') + + v = iprange() + v.gateway = config.get('cloudstack', 'public.gateway') + v.startip = config.get('cloudstack', 'public.vlan.startip') + v.endip = config.get('cloudstack', 'public.vlan.endip') + v.netmask = config.get('cloudstack', 'public.netmask') + v.vlan = config.get('cloudstack', 'public.vlan') + z.ipranges.append(v) + + c = cluster() + c.clustername = 'C0' + c.hypervisor = config.get('cloudstack', 'hypervisor') + c.clustertype = 'CloudManaged' + + h = host() + h.username = 'root' + h.password = config.get('cloudstack', 'host.password') + h.url = 'http://%s'%(config.get('cloudstack', 'host')) + c.hosts.append(h) + + ps = primaryStorage() + ps.name = 'PS0' + ps.url = config.get('cloudstack', 'primary.pool') + c.primaryStorages.append(ps) + + p.clusters.append(c) + z.pods.append(p) + + secondary = secondaryStorage() + secondary.url = config.get('cloudstack', 'secondary.pool') + z.secondaryStorages.append(secondary) + + '''Add zone''' + zs.zones.append(z) + + '''Add mgt server''' + mgt = managementServer() + mgt.mgtSvrIp = config.get('environment', 'mshost') + mgt.user = config.get('environment', 'mshost.user') + mgt.passwd = config.get('environment', 'mshost.passwd') + zs.mgtSvr.append(mgt) + + '''Add a database''' + db = dbServer() + db.dbSvr = config.get('environment', 'mysql.host') + db.user = config.get('environment', 'mysql.cloud.user') + db.passwd = config.get('environment', 'mysql.cloud.passwd') + zs.dbSvr = db + + '''Add some configuration''' + [zs.globalConfig.append(cfg) for cfg in getGlobalSettings(config)] + + ''''add loggers''' + testClientLogger = logger() + testClientLogger.name = 'TestClient' + testClientLogger.file = 'testclient.log' + + testCaseLogger = logger() + testCaseLogger.name = 'TestCase' + testCaseLogger.file = 'testcase.log' + + zs.logger.append(testClientLogger) + zs.logger.append(testCaseLogger) + return zs + + +if __name__ == '__main__': + parser = OptionParser() + parser.add_option('-i', '--input', action='store', default='setup.properties', \ + dest='input', help='file containing environment setup information') + parser.add_option('-o', '--output', action='store', default='./devcloud-kvm-advanced.cfg', \ + dest='output', help='path where environment json will be generated') + + + (opts, args) = parser.parse_args() + + cfg_parser = SafeConfigParser() + cfg_parser.read(opts.input) + + cfg = describeDevcloudKvmResources(cfg_parser) + generate_setup_config(cfg, opts.output) diff --git a/tools/devcloud-kvm/devcloud-kvm.sql b/tools/devcloud-kvm/devcloud-kvm.sql new file mode 100644 index 00000000000..6d559a9c91a --- /dev/null +++ b/tools/devcloud-kvm/devcloud-kvm.sql @@ -0,0 +1,41 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you under the Apache License, Version 2.0 (the +-- "License"); you may not use this file except in compliance +-- with the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. + + +INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, use_local_storage, type, disk_size) VALUES (17, 'tinyOffering', UUID(), 'tinyOffering', NOW(), 1, 'Service', 0); +INSERT INTO `cloud`.`service_offering` (id, cpu, speed, ram_size) VALUES (17, 1, 100, 128); +INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, type, disk_size) VALUES (18, 'tinyDiskOffering', UUID(), 'tinyDiskOffering', NOW(), 'Disk', 1073741824); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.ram.size', '100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.cpu.mhz','100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.ram.size','100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.cpu.mhz', '100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.ram.size','100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','ssvm.cpu.mhz','100'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'system.vm.use.local.storage', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.workers', '3'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.delay', '60'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'expunge.interval', '60'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.ec2.api', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'enable.s3.api', 'true'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'host', '192.168.100.10'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'management.network.cidr', '192.168.100.0/24'); +INSERT INTO `cloud`.`configuration` (instance, name, value) VALUE('DEFAULT', 'secstorage.allowed.internal.sites', '192.168.0.0/8'); +UPDATE `cloud`.`configuration` SET value='10' where name = 'storage.overprovisioning.factor'; +UPDATE `cloud`.`configuration` SET value='10' where name = 'cpu.overprovisioning.factor'; +UPDATE `cloud`.`configuration` SET value='10' where name = 'mem.overprovisioning.factor'; +UPDATE `cloud`.`vm_template` SET unique_name="tiny CentOS 6.3",name="tiny CentOS 6.3",url="http://marcus.mlsorensen.com/cloudstack-extras/tiny-centos-63.qcow2",checksum="4bbb806aa8570f4dfac13b4c38ea1603",display_text="tiny CentOS 6.3",format='QCOW2',hypervisor_type='KVM' where id=5; +UPDATE `cloud`.`vm_template` SET url="http://dontdownloadthistemplate" where id=4; diff --git a/tools/devcloud-kvm/kvm.properties b/tools/devcloud-kvm/kvm.properties new file mode 100644 index 00000000000..79afcd4a8ea --- /dev/null +++ b/tools/devcloud-kvm/kvm.properties @@ -0,0 +1,62 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +[globals] +#global settings in cloudstack +expunge.delay=60 +expunge.interval=60 +storage.cleanup.interval=300 +account.cleanup.interval=600 +expunge.workers=3 +workers=10 +vm.allocation.algorithm=random +vm.op.wait.interval=5 +guest.domain.suffix=devcloud.kvm +instance.name=vm +check.pod.cidrs=true +secstorage.allowed.internal.sites=10.147.28.0/24 +[environment] +dns=8.8.8.8 +mshost=127.0.0.1 +mshost.user=root +mshost.passwd=password +mysql.host=127.0.0.1 +mysql.cloud.user=cloud +mysql.cloud.passwd=cloud +[cloudstack] +#guest VLAN +pnet.vlan=3900-3919 +pnet2.vlan=3920-3939 +#management network +private.gateway=192.168.56.1 +private.pod.startip=192.168.56.200 +private.pod.endip=192.168.56.249 +private.netmask=255.255.255.0 +#public network +public.gateway=10.0.3.2 +public.vlan=31 +public.vlan.startip=10.0.3.100 +public.vlan.endip=10.0.3.199 +public.netmask=255.255.255.0 +#hypervisor host information +hypervisor=KVM +host=192.168.56.10 +host.password=password +#storage pools +primary.pool=nfs://192.168.56.10/opt/storage/primary +secondary.pool=nfs://192.168.56.10/opt/storage/secondary diff --git a/tools/devcloud-kvm/pom.xml b/tools/devcloud-kvm/pom.xml new file mode 100644 index 00000000000..c9af192bee3 --- /dev/null +++ b/tools/devcloud-kvm/pom.xml @@ -0,0 +1,138 @@ + + + 4.0.0 + cloud-devcloud-kvm + Apache CloudStack Developer Tools + pom + + org.apache.cloudstack + cloudstack + 4.1.0-SNAPSHOT + ../../pom.xml + + + + mysql + mysql-connector-java + 5.1.21 + runtime + + + + + install + + + + deploydb + + + deploydb + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${project.parent.basedir}/utils/conf/db.properties + ${project.parent.basedir}/utils/conf/db.properties.override + + true + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + + mysql + mysql-connector-java + ${cs.mysql.version} + + + + org.gjt.mm.mysql.Driver + jdbc:mysql://${db.cloud.host}:${db.cloud.port}/cloud + ${db.cloud.username} + ${db.cloud.password} + + ${maven.test.skip} + true + + + + create-schema + process-test-resources + + execute + + + + ${basedir}/devcloud-kvm.sql + + + + + + + + + + deploysvr + + + deploysvr + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + package + + exec + + + + + python + + ../marvin/marvin/deployDataCenter.py + -i + devcloud-kvm.cfg + + + + + + + + diff --git a/tools/devcloud/devcloud-advanced.cfg b/tools/devcloud/devcloud-advanced.cfg new file mode 100644 index 00000000000..75c3a4f7147 --- /dev/null +++ b/tools/devcloud/devcloud-advanced.cfg @@ -0,0 +1,135 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# This configuration is meant for running advanced networking, with management server on the laptop. +# It requires that the user run a DNS resolver within devcloud via 'apt-get install dnsmasq' + +{ + "zones": [ + { + "localstorageenabled": "true", + "name": "testzone", + "guestcidraddress": "10.1.1.0/24", + "dns1": "8.8.8.8", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "vlan": "3900-4000", + "name": "eth0", + "traffictypes": [ + { + "xen": "Pool-wide network associated with eth0", + "typ": "Management" + }, + { + "xen": "Pool-wide network associated with eth0", + "typ": "Guest" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "ZONE", + "name": "VpcVirtualRouter" + } + ] + }, + { + "broadcastdomainrange": "Zone", + "name": "eth1", + "traffictypes": [ + { + "xen": "Pool-wide network associated with eth1", + "typ": "Public" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + } + ] + } + ], + "ipranges": [ + { + "startip": "10.0.3.100", + "endip": "10.0.3.199", + "netmask": "255.255.255.0", + "vlan": "untagged", + "gateway": "10.0.3.2" + } + ], + "networktype": "Advanced", + "pods": [ + { + "endip": "192.168.56.249", + "name": "testpod", + "startip": "192.168.56.200", + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "testcluster", + "hypervisor": "XenServer", + "hosts": [ + { + "username": "root", + "url": "http://192.168.56.10/", + "password": "password" + } + ], + "clustertype": "CloudManaged" + } + ], + "gateway": "192.168.56.1" + } + ], + "internaldns1": "192.168.56.10", + "secondaryStorages": [ + { + "url": "nfs://192.168.56.10:/opt/storage/secondary" + } + ] + } + ], + "dbSvr": { + "dbSvr": "127.0.0.1", + "passwd": "cloud", + "db": "cloud", + "port": 3306, + "user": "cloud" + }, + "logger": [ + { + "name": "TestClient", + "file": "/var/log/testclient.log" + }, + { + "name": "TestCase", + "file": "/var/log/testcase.log" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "192.168.56.10", + "port": 8096 + } + ] +} diff --git a/tools/devcloud/devcloud-advanced_internal-mgt.cfg b/tools/devcloud/devcloud-advanced_internal-mgt.cfg new file mode 100644 index 00000000000..a1a8cb54722 --- /dev/null +++ b/tools/devcloud/devcloud-advanced_internal-mgt.cfg @@ -0,0 +1,141 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# This config is designed to run as an advanced network, with management server in devcloud +# It also requires an 'apt-get install dnsmasq' to run a resolver in devcloud for internal dns + +{ + "zones": [ + { + "localstorageenabled": "true", + "name": "testzone", + "guestcidraddress": "10.1.1.0/24", + "dns1": "8.8.8.8", + "physical_networks": [ + { + "broadcastdomainrange": "Zone", + "vlan": "3900-4000", + "name": "eth0", + "traffictypes": [ + { + "xen": "Pool-wide network associated with eth0", + "typ": "Management" + }, + { + "xen": "Pool-wide network associated with eth0", + "typ": "Guest" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + }, + { + "broadcastdomainrange": "ZONE", + "name": "VpcVirtualRouter" + } + ] + }, + { + "broadcastdomainrange": "Zone", + "name": "eth1", + "traffictypes": [ + { + "xen": "Pool-wide network associated with eth1", + "typ": "Public" + } + ], + "providers": [ + { + "broadcastdomainrange": "ZONE", + "name": "VirtualRouter" + } + ] + } + ], + "ipranges": [ + { + "startip": "10.0.3.100", + "endip": "10.0.3.199", + "netmask": "255.255.255.0", + "vlan": "untagged", + "gateway": "10.0.3.2" + } + ], + "networktype": "Advanced", + "pods": [ + { + "endip": "192.168.56.249", + "name": "testpod", + "startip": "192.168.56.200", + "netmask": "255.255.255.0", + "clusters": [ + { + "clustername": "testcluster", + "hypervisor": "XenServer", + "hosts": [ + { + "username": "root", + "url": "http://192.168.56.10/", + "password": "password" + } + ], + "clustertype": "CloudManaged" + } + ], + "gateway": "192.168.56.1" + } + ], + "internaldns1": "192.168.56.10", + "secondaryStorages": [ + { + "url": "nfs://192.168.56.10:/opt/storage/secondary" + } + ] + } + ], + "dbSvr": { + "dbSvr": "127.0.0.1", + "passwd": "cloud", + "db": "cloud", + "port": 3306, + "user": "cloud" + }, + "logger": [ + { + "name": "TestClient", + "file": "/var/log/testclient.log" + }, + { + "name": "TestCase", + "file": "/var/log/testcase.log" + } + ], + "mgtSvr": [ + { + "mgtSvrIp": "192.168.56.10", + "port": 8096 + } + ], + "globalConfig": [ + { + "name": "host", + "value": "192.168.56.10" + } + ] +} diff --git a/tools/devcloud/devcloud.cfg b/tools/devcloud/devcloud.cfg index 8d296eb7b98..c41f8bcef58 100644 --- a/tools/devcloud/devcloud.cfg +++ b/tools/devcloud/devcloud.cfg @@ -1,3 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + { "zones": [ { diff --git a/tools/marvin/marvin/configGenerator.py b/tools/marvin/marvin/configGenerator.py index d494beb6444..e2a6a24d69f 100644 --- a/tools/marvin/marvin/configGenerator.py +++ b/tools/marvin/marvin/configGenerator.py @@ -65,8 +65,6 @@ class zone(): self.internaldns2 = None self.securitygroupenabled = None self.localstorageenabled = None - ''' Guest Vlan range - only advanced zone''' - self.vlan = None '''default public network, in advanced mode''' self.ipranges = [] self.physical_networks = [] @@ -80,6 +78,7 @@ class traffictype(): self.xen = labeldict['xen'] if 'xen' in labeldict.keys() else None self.kvm = labeldict['kvm'] if 'kvm' in labeldict.keys() else None self.vmware = labeldict['vmware'] if 'vmware' in labeldict.keys() else None + self.simulator = labeldict['simulator'] if 'simulator' in labeldict.keys() else None #{ # 'xen' : 'cloud-xen', # 'kvm' : 'cloud-kvm', diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py index 0d5f3bdc659..e4f7eace9bd 100644 --- a/tools/marvin/marvin/deployDataCenter.py +++ b/tools/marvin/marvin/deployDataCenter.py @@ -258,10 +258,10 @@ class deployDataCenters(): traffic_type = addTrafficType.addTrafficTypeCmd() traffic_type.physicalnetworkid = physical_network_id traffic_type.traffictype = traffictype.typ - if traffictype.labeldict is not None: - traffic_type.kvmnetworklabel = traffictype.labeldict.kvm - traffic_type.xennetworklabel = traffictype.labeldict.xen - traffic_type.vmwarenetworklabel = traffictype.labeldict.vmware + traffic_type.kvmnetworklabel = traffictype.kvm if traffictype.kvm is not None else None + traffic_type.xennetworklabel = traffictype.xen if traffictype.xen is not None else None + traffic_type.vmwarenetworklabel = traffictype.vmware if traffictype.vmware is not None else None + traffic_type.simulatorlabel = traffictype.simulator if traffictype.simulator is not None else None return self.apiClient.addTrafficType(traffic_type) def enableZone(self, zoneid, allocation_state="Enabled"): @@ -289,7 +289,7 @@ class deployDataCenters(): for pnet in zone.physical_networks: phynetwrk = self.createPhysicalNetwork(pnet, zoneId) self.configureProviders(phynetwrk, pnet.providers) - self.updatePhysicalNetwork(phynetwrk.id, "Enabled", vlan=zone.vlan) + self.updatePhysicalNetwork(phynetwrk.id, "Enabled", vlan=pnet.vlan) if zone.networktype == "Basic": listnetworkoffering = listNetworkOfferings.listNetworkOfferingsCmd() diff --git a/tools/marvin/marvin/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py index 0daea5dd579..87b0bbb7bbc 100644 --- a/tools/marvin/marvin/integration/lib/base.py +++ b/tools/marvin/marvin/integration/lib/base.py @@ -509,6 +509,12 @@ class Volume: [setattr(cmd, k, v) for k, v in kwargs.items()] return(apiclient.listVolumes(cmd)) + def resize(cls, apiclient, **kwargs): + """Resize a volume""" + cmd = resizeVolume.resizeVolumeCmd() + cmd.id = self.id + [setattr(cmd, k, v) for k, v in kwargs.items()] + return(apiclient.resizeVolume(cmd)) class Snapshot: """Manage Snapshot Lifecycle @@ -1109,6 +1115,9 @@ class DiskOffering: if domainid: cmd.domainid = domainid + if services["storagetype"]: + cmd.storagetype = services["storagetype"] + return DiskOffering(apiclient.createDiskOffering(cmd).__dict__) def delete(self, apiclient): diff --git a/tools/marvin/marvin/sandbox/advanced/advanced_env.py b/tools/marvin/marvin/sandbox/advanced/advanced_env.py index 1873f31d50f..db78a84b33b 100644 --- a/tools/marvin/marvin/sandbox/advanced/advanced_env.py +++ b/tools/marvin/marvin/sandbox/advanced/advanced_env.py @@ -52,10 +52,22 @@ def describeResources(config): pn = physical_network() pn.name = "Sandbox-pnet" - pn.traffictypes = [traffictype("Guest"), traffictype("Management"), traffictype("Public")] + pn.vlan = config.get('cloudstack', 'pnet.vlan') + pn.tags = ["cloud-simulator-public"] + pn.traffictypes = [traffictype("Guest"), + traffictype("Management", {"simulator" : "cloud-simulator-mgmt"}), + traffictype("Public", {"simulator":"cloud-simulator-public"})] pn.providers.append(vpcprovider) + + pn2 = physical_network() + pn2.name = "Sandbox-pnet2" + pn2.vlan = config.get('cloudstack', 'pnet2.vlan') + pn2.tags = ["cloud-simulator-guest"] + pn2.traffictypes = [traffictype('Guest', {'simulator': 'cloud-simulator-guest'})] + pn2.providers.append(vpcprovider) z.physical_networks.append(pn) + z.physical_networks.append(pn2) p = pod() p.name = 'POD0' @@ -118,11 +130,11 @@ def describeResources(config): ''''add loggers''' testClientLogger = logger() testClientLogger.name = 'TestClient' - testClientLogger.file = '/var/log/testclient.log' + testClientLogger.file = 'testclient.log' testCaseLogger = logger() testCaseLogger.name = 'TestCase' - testCaseLogger.file = '/var/log/testcase.log' + testCaseLogger.file = 'testcase.log' zs.logger.append(testClientLogger) zs.logger.append(testCaseLogger) diff --git a/tools/marvin/marvin/sandbox/advanced/setup.properties b/tools/marvin/marvin/sandbox/advanced/setup.properties index ba44d5146b6..73eacc938d4 100644 --- a/tools/marvin/marvin/sandbox/advanced/setup.properties +++ b/tools/marvin/marvin/sandbox/advanced/setup.properties @@ -24,10 +24,9 @@ storage.cleanup.interval=300 account.cleanup.interval=600 expunge.workers=3 workers=10 -use.user.concentrated.pod.allocation=false vm.allocation.algorithm=random vm.op.wait.interval=5 -guest.domain.suffix=sandbox.kvm +guest.domain.suffix=sandbox.simulator instance.name=QA direct.agent.load.size=1000 default.page.size=10000 @@ -35,15 +34,16 @@ check.pod.cidrs=true secstorage.allowed.internal.sites=10.147.28.0/24 [environment] dns=10.147.28.6 -mshost=10.147.29.111 +mshost=localhost mshost.user=root mshost.passwd=password -mysql.host=10.147.29.111 +mysql.host=localhost mysql.cloud.user=cloud mysql.cloud.passwd=cloud [cloudstack] #guest VLAN -zone.vlan=675-679 +pnet.vlan=675-679 +pnet2.vlan=800-1000 #management network private.gateway=10.147.29.1 private.pod.startip=10.147.29.150 @@ -56,9 +56,9 @@ public.vlan.startip=10.147.31.150 public.vlan.endip=10.147.31.159 public.netmask=255.255.255.0 #hypervisor host information -hypervisor=XenServer -host=10.147.29.58 +hypervisor=Simulator +host=simulator0 host.password=password #storage pools -primary.pool=nfs://10.147.28.6:/export/home/sandbox/kamakura +primary.pool=nfs://10.147.28.6:/export/home/sandbox/primary secondary.pool=nfs://10.147.28.6:/export/home/sandbox/sstor diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index 6156f47be3a..58563a6711a 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -452,11 +452,6 @@ div.list-view table tbody td span { white-space: nowrap; } -div.list-view table tbody td span:hover { - overflow: auto; - margin-top: 4px; -} - div.list-view div.toolbar div.section-switcher div.section-select label { margin: 0 9px 0 0; } @@ -2062,7 +2057,6 @@ div.detail-group.actions td { float: right; margin-top: 8px; display: inline-block; - background: url(../images/citrix-logo-darkbg.png) no-repeat 97% 8px; padding: 0 96px 0 0; } diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js index de8149fe877..59e9d8bbd15 100644 --- a/ui/scripts/accounts.js +++ b/ui/scripts/accounts.js @@ -229,6 +229,7 @@ $.ajax({ url: createURL('createAccount'), + type: "POST", data: data, success: function(json) { var item = json.createaccountresponse.account; @@ -920,6 +921,7 @@ $.ajax({ url: createURL('createUser'), + type: "POST", data: data, success: function(json) { var item = json.createuserresponse.user; diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js index 89ca1d63361..e4b1f31d427 100644 --- a/ui/scripts/instanceWizard.js +++ b/ui/scripts/instanceWizard.js @@ -545,7 +545,8 @@ if(checkedSecurityGroupIdArray.length > 0) array1.push("&securitygroupids=" + checkedSecurityGroupIdArray.join(",")); - + + /* if(selectedZoneObj.networktype == "Advanced" && selectedZoneObj.securitygroupsenabled == true) { // Advanced SG-enabled zone var networkData = { zoneId: selectedZoneObj.id, @@ -577,6 +578,8 @@ return; } } + */ + } else if (step5ContainerType == 'nothing-to-select') { if(args.context.networks != null) { //from VPC tier diff --git a/ui/scripts/network.js b/ui/scripts/network.js index c8979d05c48..f3308bb5ba7 100755 --- a/ui/scripts/network.js +++ b/ui/scripts/network.js @@ -867,9 +867,9 @@ hiddenTabs.push("addloadBalancer"); } - if (isVPC || isAdvancedSGZone || hasSRXFirewall) { + // if (isVPC || isAdvancedSGZone || hasSRXFirewall) { hiddenTabs.push('egressRules'); - } + // } return hiddenTabs; }, @@ -1259,12 +1259,16 @@ data.listvirtualmachinesresponse.virtualmachine : [], function(instance) { var nonAutoScale=0; + if(instance.displayname == null) + nonAutoScale = 1; + else{ if( instance.displayname.match(/AutoScale-LB-/)==null) nonAutoScale =1; else { if(instance.displayname.match(/AutoScale-LB-/).length) nonAutoScale =0; } + } var isActiveState= $.inArray(instance.state, ['Destroyed','Expunging']) == -1; return nonAutoScale && isActiveState; } @@ -2623,12 +2627,16 @@ function(instance) { //Hiding the autoScale VMs var nonAutoScale =0; + if(instance.displayname == null) + nonAutoScale = 1 + else { if(instance.displayname.match(/AutoScale-LB-/) == null) nonAutoScale = 1; else { if( instance.displayname.match(/AutoScale-LB-/).length) nonAutoScale =0; - } + } + } var isActiveState = $.inArray(instance.state, ['Destroyed','Expunging']) == -1; var notExisting = !$.grep(itemData, function(item) { return item.id == instance.id; diff --git a/ui/scripts/sharedFunctions.js b/ui/scripts/sharedFunctions.js index eb78ad15da0..51c4fdb5902 100644 --- a/ui/scripts/sharedFunctions.js +++ b/ui/scripts/sharedFunctions.js @@ -208,12 +208,13 @@ function parseXMLHttpResponse(XMLHttpResponse) { var json = JSON.parse(XMLHttpResponse.responseText); if (json != null) { var property; - for(property in json) {} + for(property in json) { var errorObj = json[property]; if(errorObj.errorcode == 401 && errorObj.errortext == "unable to verify user credentials and/or request signature") return _l('label.session.expired'); else return _s(errorObj.errortext); + } } else { return ""; diff --git a/ui/scripts/system.js b/ui/scripts/system.js index 6733da1e2b9..bd8d3316103 100644 --- a/ui/scripts/system.js +++ b/ui/scripts/system.js @@ -1148,6 +1148,7 @@ var array1 = []; if(args.context.zones[0].networktype == "Advanced" && args.context.zones[0].securitygroupsenabled == true) { array1.push({id: 'account-specific', description: 'Account'}); + array1.push({id: 'zone-wide', description: 'All'}); } else { array1.push({id: 'zone-wide', description: 'All'}); diff --git a/ui/scripts/ui/widgets/listView.js b/ui/scripts/ui/widgets/listView.js index 85523ea5e7a..9e16ec2ae54 100644 --- a/ui/scripts/ui/widgets/listView.js +++ b/ui/scripts/ui/widgets/listView.js @@ -560,8 +560,8 @@ return $(this).index() == index; }); - if ($target.index() > $tr.index()) $target.after($tr); - else $target.before($tr); + // if ($target.index() > $tr.index()) $target.after($tr); + // else $target.before($tr); $tr.closest('.list-view').scrollTop($tr.position().top - $tr.height() * 2); diff --git a/utils/pom.xml b/utils/pom.xml index 1ee8b7e50e3..87c078a7a61 100644 --- a/utils/pom.xml +++ b/utils/pom.xml @@ -72,6 +72,11 @@ commons-discovery ${cs.discovery.version} + + com.google.guava + guava + ${cs.guava.version} + commons-logging commons-logging @@ -132,6 +137,7 @@ mysql mysql-connector-java + ${cs.mysql.version} test @@ -140,6 +146,11 @@ ${cs.commons-io.version} provided + + org.reflections + reflections + ${cs.reflections.version} + install diff --git a/utils/src/com/cloud/utils/IdentityProxy.java b/utils/src/com/cloud/utils/IdentityProxy.java deleted file mode 100644 index 7e385fbf05a..00000000000 --- a/utils/src/com/cloud/utils/IdentityProxy.java +++ /dev/null @@ -1,60 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.utils; - -public class IdentityProxy { - private String _tableName; - private Long _value; - private String _idFieldName; - - public IdentityProxy() { - } - - public IdentityProxy(String tableName) { - _tableName = tableName; - } - - public IdentityProxy(String tableName, Long id, String fieldName) { - _tableName = tableName; - _value = id; - _idFieldName = fieldName; - } - - public String getTableName() { - return _tableName; - } - - public void setTableName(String tableName) { - _tableName = tableName; - } - - public Long getValue() { - return _value; - } - - public void setValue(Long value) { - _value = value; - } - - public void setidFieldName(String value) { - _idFieldName = value; - } - - public String getidFieldName() { - return _idFieldName; - } -} diff --git a/utils/src/com/cloud/utils/PropertiesUtil.java b/utils/src/com/cloud/utils/PropertiesUtil.java index 3909ca876b6..90f8af8b33f 100755 --- a/utils/src/com/cloud/utils/PropertiesUtil.java +++ b/utils/src/com/cloud/utils/PropertiesUtil.java @@ -17,6 +17,8 @@ package com.cloud.utils; import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -28,6 +30,7 @@ import java.util.Set; import org.apache.log4j.Logger; public class PropertiesUtil { + private static final Logger s_logger = Logger.getLogger(PropertiesUtil.class); /** * Searches the class path and local paths to find the config file. * @param path path to find. if it starts with / then it's absolute path. @@ -116,4 +119,41 @@ public class PropertiesUtil { } return null; } + + // Returns key=value pairs by parsing a commands.properties/config file + // with syntax; key=cmd;value (with this syntax cmd is stripped) and key=value + public static Map processConfigFile(String[] configFiles) { + Map configMap = new HashMap(); + Properties preProcessedCommands = new Properties(); + for (String configFile : configFiles) { + File commandsFile = findConfigFile(configFile); + if (commandsFile != null) { + try { + preProcessedCommands.load(new FileInputStream(commandsFile)); + } catch (FileNotFoundException fnfex) { + // in case of a file within a jar in classpath, try to open stream using url + InputStream stream = PropertiesUtil.openStreamFromURL(configFile); + if (stream != null) { + try { + preProcessedCommands.load(stream); + } catch (IOException e) { + s_logger.error("IO Exception, unable to find properties file:", fnfex); + } + } else { + s_logger.error("Unable to find properites file", fnfex); + } + } catch (IOException ioe) { + s_logger.error("IO Exception loading properties file", ioe); + } + } + } + + for (Object key : preProcessedCommands.keySet()) { + String preProcessedCommand = preProcessedCommands.getProperty((String) key); + int splitIndex = preProcessedCommand.lastIndexOf(";"); + String value = preProcessedCommand.substring(splitIndex+1); + configMap.put((String)key, value); + } + return configMap; + } } diff --git a/utils/src/com/cloud/utils/ReflectUtil.java b/utils/src/com/cloud/utils/ReflectUtil.java index f1d1409ee7d..09447059fe6 100755 --- a/utils/src/com/cloud/utils/ReflectUtil.java +++ b/utils/src/com/cloud/utils/ReflectUtil.java @@ -16,10 +16,14 @@ // under the License. package com.cloud.utils; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; import com.cloud.utils.exception.CloudRuntimeException; +import org.reflections.Reflections; public class ReflectUtil { public static Pair, Field> getAnyField(Class clazz, String fieldName) { @@ -50,4 +54,63 @@ public class ReflectUtil { return null; } + // Gets all classes with some annotation from a package + public static Set> getClassesWithAnnotation(Class annotation, + String[] packageNames) { + Reflections reflections; + Set> classes = new HashSet>(); + for(String packageName: packageNames) { + reflections = new Reflections(packageName); + classes.addAll(reflections.getTypesAnnotatedWith(annotation)); + } + return classes; + } + + // Checks against posted search classes if cmd is async + public static boolean isCmdClassAsync(Class cmdClass, + Class[] searchClasses) { + boolean isAsync = false; + Class superClass = cmdClass; + + while (superClass != null && superClass != Object.class) { + String superName = superClass.getName(); + for (Class baseClass: searchClasses) { + if (superName.equals(baseClass.getName())) { + isAsync = true; + break; + } + } + if (isAsync) + break; + superClass = superClass.getSuperclass(); + } + return isAsync; + } + + // Returns all fields across the base class for a cmd + public static Field[] getAllFieldsForClass(Class cmdClass, + Class[] searchClasses) { + Field[] fields = cmdClass.getDeclaredFields(); + Class superClass = cmdClass.getSuperclass(); + + while (superClass != null && superClass != Object.class) { + String superName = superClass.getName(); + for (Class baseClass: searchClasses) { + if(!baseClass.isAssignableFrom(superClass)) + continue; + if (!superName.equals(baseClass.getName())) { + Field[] superClassFields = superClass.getDeclaredFields(); + if (superClassFields != null) { + Field[] tmpFields = new Field[fields.length + superClassFields.length]; + System.arraycopy(fields, 0, tmpFields, 0, fields.length); + System.arraycopy(superClassFields, 0, tmpFields, fields.length, superClassFields.length); + fields = tmpFields; + } + } + } + superClass = superClass.getSuperclass(); + } + return fields; + } + } diff --git a/utils/src/com/cloud/utils/component/PluggableService.java b/utils/src/com/cloud/utils/component/PluggableService.java index 9c946284eea..5e0e4dfff16 100644 --- a/utils/src/com/cloud/utils/component/PluggableService.java +++ b/utils/src/com/cloud/utils/component/PluggableService.java @@ -16,16 +16,12 @@ // under the License. package com.cloud.utils.component; +import java.util.List; +import java.util.Map; - -/** - * This interface defines methods for pluggable code within the Cloud Stack. - */ +// This interface defines methods for pluggable code within the Cloud Stack. public interface PluggableService { - - /** - * The config file name that lists API commands supported by this pluggable service - */ - String getPropertiesFile(); - + // The config command properties filenames that lists allowed API commands + // and role masks supported by this pluggable service + List> getCommands(); } diff --git a/utils/src/com/cloud/utils/db/GenericDao.java b/utils/src/com/cloud/utils/db/GenericDao.java index f36c4d80164..15d04b76a1c 100755 --- a/utils/src/com/cloud/utils/db/GenericDao.java +++ b/utils/src/com/cloud/utils/db/GenericDao.java @@ -54,6 +54,9 @@ public interface GenericDao { T findByIdIncludingRemoved(ID id); T findById(ID id, boolean fresh); + + // Finds one unique VO using uuid + T findByUuid(String uuid); /** * @return VO object ready to be used for update. It won't have any fields filled in. diff --git a/utils/src/com/cloud/utils/db/GenericDaoBase.java b/utils/src/com/cloud/utils/db/GenericDaoBase.java index 8d5cb96abc9..880e9de22a8 100755 --- a/utils/src/com/cloud/utils/db/GenericDaoBase.java +++ b/utils/src/com/cloud/utils/db/GenericDaoBase.java @@ -50,6 +50,7 @@ import javax.persistence.EmbeddedId; import javax.persistence.EntityExistsException; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.Table; import javax.persistence.TableGenerator; import net.sf.cglib.proxy.Callback; @@ -912,6 +913,14 @@ public abstract class GenericDaoBase implements Gene } } + @Override @DB(txn=false) + @SuppressWarnings("unchecked") + public T findByUuid(final String uuid) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("uuid", SearchCriteria.Op.EQ, uuid); + return findOneBy(sc); + } + @Override @DB(txn=false) public T findByIdIncludingRemoved(ID id) { return findById(id, true, null); @@ -1653,6 +1662,13 @@ public abstract class GenericDaoBase implements Gene @DB(txn=false) protected void setField(final Object entity, final ResultSet rs, ResultSetMetaData meta, final int index) throws SQLException { Attribute attr = _allColumns.get(new Pair(meta.getTableName(index), meta.getColumnName(index))); + if ( attr == null ){ + // work around for mysql bug to return original table name instead of view name in db view case + Table tbl = entity.getClass().getSuperclass().getAnnotation(Table.class); + if ( tbl != null ){ + attr = _allColumns.get(new Pair(tbl.name(), meta.getColumnLabel(index))); + } + } assert (attr != null) : "How come I can't find " + meta.getCatalogName(index) + "." + meta.getColumnName(index); setField(entity, attr.field, rs, index); } @@ -1798,7 +1814,8 @@ public abstract class GenericDaoBase implements Gene } } - List groupByValues = addGroupBy(str, sc); + // we have to disable group by in getting count, since count for groupBy clause will be different. + //List groupByValues = addGroupBy(str, sc); final Transaction txn = Transaction.currentTxn(); final String sql = str.toString(); @@ -1816,11 +1833,13 @@ public abstract class GenericDaoBase implements Gene i = addJoinAttributes(i, pstmt, joins); } + /* if (groupByValues != null) { for (Object value : groupByValues) { pstmt.setObject(i++, value); } } + */ final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { diff --git a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java index ab8d4b1a875..303e0d681fa 100755 --- a/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java +++ b/utils/src/com/cloud/utils/exception/CSExceptionErrorCode.java @@ -14,115 +14,114 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. - - -package com.cloud.utils.exception; - + + +package com.cloud.utils.exception; import java.util.HashMap; import org.apache.log4j.Logger; - -/** - * CSExceptionErrorCode lists the CloudStack error codes that correspond - * to a each exception thrown by the CloudStack API. - */ - -public class CSExceptionErrorCode { - - public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName()); - - // Declare a hashmap of CloudStack Error Codes for Exceptions. - protected static final HashMap ExceptionErrorCodeMap; - - static { - try { - ExceptionErrorCodeMap = new HashMap(); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265); - ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275); - ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280); - ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295); - ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300); - ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305); - ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310); - ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340); - ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345); - ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350); - ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355); - ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360); - ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380); - ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385); - ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390); - ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395); - - ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400); - ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415); - ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420); - ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425); - ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430); - ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435); - ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440); - ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445); - ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475); - ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480); - ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485); - ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490); - ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495); - ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500); - ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515); - ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520); - ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525); - ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530); - ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535); - ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540); - - // Have a special error code for ServerApiException when it is - // thrown in a standalone manner when failing to detect any of the above - // standard exceptions. - ExceptionErrorCodeMap.put("com.cloud.api.ServerApiException", 9999); - } catch (Exception e) { - e.printStackTrace(); - throw new ExceptionInInitializerError(e); - } - } - - public static HashMap getErrCodeList() { - return ExceptionErrorCodeMap; - } - - public static int getCSErrCode(String exceptionName) { - if (ExceptionErrorCodeMap.containsKey(exceptionName)) { - return ExceptionErrorCodeMap.get(exceptionName); - } else { - s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions"); - return -1; - } - } - - public static String getCurMethodName() { - StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace(); - return stackTraceCalls[1].toString(); - } -} + +/** + * CSExceptionErrorCode lists the CloudStack error codes that correspond + * to a each exception thrown by the CloudStack API. + */ + +public class CSExceptionErrorCode { + + public static final Logger s_logger = Logger.getLogger(CSExceptionErrorCode.class.getName()); + + // Declare a hashmap of CloudStack Error Codes for Exceptions. + protected static final HashMap ExceptionErrorCodeMap; + + static { + try { + ExceptionErrorCodeMap = new HashMap(); + ExceptionErrorCodeMap.put("com.cloud.utils.exception.CloudRuntimeException", 4250); + ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExceptionUtil", 4255); + ExceptionErrorCodeMap.put("com.cloud.utils.exception.ExecutionException", 4260); + ExceptionErrorCodeMap.put("com.cloud.utils.exception.HypervisorVersionChangedException", 4265); + ExceptionErrorCodeMap.put("com.cloud.utils.exception.RuntimeCloudException", 4270); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4275); + ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4280); + ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4285); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4290); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4295); + ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4300); + ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4305); + ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4310); + ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4315); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4320); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4325); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4330); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4335); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4340); + ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4345); + ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4350); + ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4355); + ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4360); + ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4365); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4370); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4375); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4380); + ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4385); + ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4390); + ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4395); + + ExceptionErrorCodeMap.put("com.cloud.exception.AccountLimitException", 4400); + ExceptionErrorCodeMap.put("com.cloud.exception.AgentUnavailableException", 4405); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudAuthenticationException", 4410); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudException", 4415); + ExceptionErrorCodeMap.put("com.cloud.exception.CloudExecutionException", 4420); + ExceptionErrorCodeMap.put("com.cloud.exception.ConcurrentOperationException", 4425); + ExceptionErrorCodeMap.put("com.cloud.exception.ConflictingNetworkSettingsException", 4430); + ExceptionErrorCodeMap.put("com.cloud.exception.ConnectionException", 4435); + ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveredWithErrorException", 4440); + ExceptionErrorCodeMap.put("com.cloud.exception.DiscoveryException", 4445); + ExceptionErrorCodeMap.put("com.cloud.exception.HAStateException", 4450); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientAddressCapacityException", 4455); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientCapacityException", 4460); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientNetworkCapacityException", 4465); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientServerCapacityException", 4470); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientStorageCapacityException", 4475); + ExceptionErrorCodeMap.put("com.cloud.exception.InsufficientVirtualNetworkCapcityException", 4480); + ExceptionErrorCodeMap.put("com.cloud.exception.InternalErrorException", 4485); + ExceptionErrorCodeMap.put("com.cloud.exception.InvalidParameterValueException", 4490); + ExceptionErrorCodeMap.put("com.cloud.exception.ManagementServerException", 4495); + ExceptionErrorCodeMap.put("com.cloud.exception.NetworkRuleConflictException", 4500); + ExceptionErrorCodeMap.put("com.cloud.exception.PermissionDeniedException", 4505); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceAllocationException", 4510); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceInUseException", 4515); + ExceptionErrorCodeMap.put("com.cloud.exception.ResourceUnavailableException", 4520); + ExceptionErrorCodeMap.put("com.cloud.exception.StorageUnavailableException", 4525); + ExceptionErrorCodeMap.put("com.cloud.exception.UnsupportedServiceException", 4530); + ExceptionErrorCodeMap.put("com.cloud.exception.VirtualMachineMigrationException", 4535); + ExceptionErrorCodeMap.put("com.cloud.async.AsyncCommandQueued", 4540); + + // Have a special error code for ServerApiException when it is + // thrown in a standalone manner when failing to detect any of the above + // standard exceptions. + ExceptionErrorCodeMap.put("org.apache.cloudstack.api.ServerApiException", 9999); + } catch (Exception e) { + e.printStackTrace(); + throw new ExceptionInInitializerError(e); + } + } + + public static HashMap getErrCodeList() { + return ExceptionErrorCodeMap; + } + + public static int getCSErrCode(String exceptionName) { + if (ExceptionErrorCodeMap.containsKey(exceptionName)) { + return ExceptionErrorCodeMap.get(exceptionName); + } else { + s_logger.info("Could not find exception: " + exceptionName + " in error code list for exceptions"); + return -1; + } + } + + public static String getCurMethodName() { + StackTraceElement stackTraceCalls[] = (new Throwable()).getStackTrace(); + return stackTraceCalls[1].toString(); + } +} diff --git a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java index 78075947d3f..3862e2223d6 100755 --- a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java +++ b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java @@ -16,24 +16,62 @@ // under the License. package com.cloud.utils.exception; +import java.util.ArrayList; + +import com.cloud.utils.AnnotationHelper; import com.cloud.utils.SerialVersionUID; /** * wrap exceptions that you know there's no point in dealing with. */ -public class CloudRuntimeException extends RuntimeCloudException { +public class CloudRuntimeException extends RuntimeException { private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException; - + + // This holds a list of uuids and their names. Add uuid:fieldname pairs + protected ArrayList idList = new ArrayList(); + + protected int csErrorCode; + + public CloudRuntimeException(String message) { super(message); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - + public CloudRuntimeException(String message, Throwable th) { super(message, th); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - - protected CloudRuntimeException() { + + public CloudRuntimeException() { super(); + setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); + } + + public void addProxyObject(String uuid) { + idList.add(uuid); + return; + } + + public void addProxyObject(Object voObj, Long id, String idFieldName) { + // Get the VO object's table name. + String tablename = AnnotationHelper.getTableName(voObj); + if (tablename != null) { + addProxyObject(tablename, id, idFieldName); + } + return; + } + + public ArrayList getIdProxyList() { + return idList; + } + + public void setCSErrorCode(int cserrcode) { + this.csErrorCode = cserrcode; + } + + public int getCSErrorCode() { + return this.csErrorCode; } } diff --git a/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java b/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java index 4f637cb46be..2c0c1ccd68b 100755 --- a/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java +++ b/utils/src/com/cloud/utils/exception/HypervisorVersionChangedException.java @@ -18,10 +18,10 @@ package com.cloud.utils.exception; import com.cloud.utils.SerialVersionUID; -public class HypervisorVersionChangedException extends RuntimeCloudException { +public class HypervisorVersionChangedException extends CloudRuntimeException { private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException; - + public HypervisorVersionChangedException(String message) { super(message); } diff --git a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java b/utils/src/com/cloud/utils/exception/RuntimeCloudException.java deleted file mode 100644 index f2e9845de8c..00000000000 --- a/utils/src/com/cloud/utils/exception/RuntimeCloudException.java +++ /dev/null @@ -1,76 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.utils.exception; - -import com.cloud.utils.AnnotationHelper; -import com.cloud.utils.IdentityProxy; -import java.util.ArrayList; - -/** - * by the API response serializer. Any exceptions that are thrown by - * class, which extends Exception instead of RuntimeException like this - * class does. - */ - -public class RuntimeCloudException extends RuntimeException { - - // This holds a list of uuids and their names. Add uuid:fieldname pairs - protected ArrayList idList = new ArrayList(); - - protected int csErrorCode; - - public void addProxyObject(String tableName, Long id, String idFieldName) { - idList.add(new IdentityProxy(tableName, id, idFieldName)); - return; - } - - public RuntimeCloudException(String message) { - super(message); - setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); - } - - public RuntimeCloudException(String message, Throwable cause) { - super(message, cause); - setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); - } - - public void addProxyObject(Object voObj, Long id, String idFieldName) { - // Get the VO object's table name. - String tablename = AnnotationHelper.getTableName(voObj); - if (tablename != null) { - addProxyObject(tablename, id, idFieldName); - } - return; - } - - public RuntimeCloudException() { - super(); - setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); - } - - public ArrayList getIdProxyList() { - return idList; - } - - public void setCSErrorCode(int cserrcode) { - this.csErrorCode = cserrcode; - } - - public int getCSErrorCode() { - return this.csErrorCode; - } -} diff --git a/utils/src/com/cloud/utils/script/Script.java b/utils/src/com/cloud/utils/script/Script.java index a0f9e8e3e88..1444f83f425 100755 --- a/utils/src/com/cloud/utils/script/Script.java +++ b/utils/src/com/cloud/utils/script/Script.java @@ -350,7 +350,12 @@ public class Script implements Callable { * Look in WEB-INF/classes of the webapp * URI workaround the URL encoding of url.getFile */ - url = Script.class.getClassLoader().getResource(path + script); + if (path.endsWith(File.separator)) { + url = Script.class.getClassLoader().getResource(path + script); + } + else { + url = Script.class.getClassLoader().getResource(path + File.separator + script); + } s_logger.debug("Classpath resource: " + url); if (url != null) { try { diff --git a/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java b/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java index 5a9501dcc9c..c1cd81ef08a 100644 --- a/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java +++ b/utils/test/com/cloud/utils/log/CglibThrowableRendererTest.java @@ -18,14 +18,21 @@ package com.cloud.utils.log; import junit.framework.TestCase; -import org.apache.log4j.Logger; +import org.apache.log4j.*; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.log4j.spi.RootLogger; +import org.apache.log4j.spi.ThrowableRenderer; + +import java.io.CharArrayWriter; +import java.io.Writer; public class CglibThrowableRendererTest extends TestCase { + static Logger another = Logger.getLogger("TEST"); + private final static Logger s_logger = Logger.getLogger(CglibThrowableRendererTest.class); public static class Test { @DB @@ -48,13 +55,40 @@ public class CglibThrowableRendererTest extends TestCase { } } } + + private Logger getAlternateLogger(Writer writer, ThrowableRenderer renderer) { + Hierarchy hierarchy = new Hierarchy(new RootLogger(Level.INFO)); + if (renderer != null) { + hierarchy.setThrowableRenderer(renderer); + } + Logger alternateRoot = hierarchy.getRootLogger(); + alternateRoot.addAppender(new WriterAppender(new SimpleLayout(), writer)); + return alternateRoot; + } public void testException() { + Writer w = new CharArrayWriter(); + Logger alt = getAlternateLogger(w, null); + Test test = ComponentLocator.inject(Test.class); try { test.exception(); } catch (Exception e) { - s_logger.warn("exception caught", e); + alt.warn("exception caught", e); } + // first check that we actually have some call traces containing "" + assertTrue(w.toString().contains("")); + + w = new CharArrayWriter(); + alt = getAlternateLogger(w, new CglibThrowableRenderer()); + + try { + test.exception(); + } catch (Exception e) { + alt.warn("exception caught", e); + } + // then we check that CglibThrowableRenderer indeed remove those occurrences + assertFalse(w.toString().contains("")); + } } diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java index 35570481d41..a765b42fd78 100755 --- a/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java +++ b/vmware-base/src/com/cloud/hypervisor/vmware/mo/HostMO.java @@ -840,11 +840,9 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { VmwareHypervisorHostResourceSummary summary = new VmwareHypervisorHostResourceSummary(); - HostConnectInfo hostInfo = _context.getService().queryHostConnectionInfo(_mor); - HostHardwareSummary hardwareSummary = hostInfo.getHost().getHardware(); - + HostHardwareSummary hardwareSummary = getHostHardwareSummary(); // TODO: not sure how hyper-thread is counted in VMware resource pool - summary.setCpuCount(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); + summary.setCpuCount(hardwareSummary.getNumCpuCores()); summary.setMemoryBytes(hardwareSummary.getMemorySize()); summary.setCpuSpeed(hardwareSummary.getCpuMhz()); @@ -922,14 +920,13 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost { ComputeResourceSummary resourceSummary = new ComputeResourceSummary(); // TODO: not sure how hyper-threading is counted in VMware - short totalCores = (short)(hardwareSummary.getNumCpuCores()*hardwareSummary.getNumCpuPkgs()); - resourceSummary.setNumCpuCores(totalCores); + resourceSummary.setNumCpuCores(hardwareSummary.getNumCpuCores()); // Note: memory here is in Byte unit resourceSummary.setTotalMemory(hardwareSummary.getMemorySize()); - // Total CPU is based on socket x core x Mhz - int totalCpu = hardwareSummary.getCpuMhz() * totalCores; + // Total CPU is based on (# of cores) x Mhz + int totalCpu = hardwareSummary.getCpuMhz() * hardwareSummary.getNumCpuCores(); resourceSummary.setTotalCpu(totalCpu); HostListSummaryQuickStats stats = getHostQuickStats();