removed import of componentlocator and inject from all files

This commit is contained in:
Alex Huang 2013-01-10 11:44:47 -08:00
parent 395de6f2b3
commit 56e5fbdee2
157 changed files with 2856 additions and 3431 deletions

View File

@ -141,7 +141,7 @@ public abstract class BaseCmd {
public static QueryService _queryService; public static QueryService _queryService;
static void setComponents(ResponseGenerator generator) { public static void setComponents(ResponseGenerator generator) {
_mgr = ComponentContext.getComponent(ManagementService.class); _mgr = ComponentContext.getComponent(ManagementService.class);
_accountService = ComponentContext.getComponent(AccountService.class); _accountService = ComponentContext.getComponent(AccountService.class);
_configService = ComponentContext.getComponent(ConfigurationService.class); _configService = ComponentContext.getComponent(ConfigurationService.class);

View File

@ -21,6 +21,7 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -46,15 +47,13 @@ import com.cloud.storage.resource.SecondaryStorageResource;
import com.cloud.storage.template.TemplateUploader.Status; import com.cloud.storage.template.TemplateUploader.Status;
import com.cloud.storage.template.TemplateUploader.UploadCompleteCallback; import com.cloud.storage.template.TemplateUploader.UploadCompleteCallback;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
public class UploadManagerImpl implements UploadManager { public class UploadManagerImpl implements UploadManager {
public class Completion implements UploadCompleteCallback { public class Completion implements UploadCompleteCallback {
private final String jobId; private final String jobId;
public Completion(String jobId) { public Completion(String jobId) {
@ -66,180 +65,180 @@ public class UploadManagerImpl implements UploadManager {
setUploadStatus(jobId, status); setUploadStatus(jobId, status);
} }
} }
private static class UploadJob {
private final TemplateUploader tu;
private final String jobId;
private final String name;
private final ImageFormat format;
private String tmpltPath;
private String description;
private String checksum;
private Long accountId;
private String installPathPrefix;
private long templatesize;
private long id;
public UploadJob(TemplateUploader tu, String jobId, long id, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum, String installPathPrefix) { private static class UploadJob {
super(); private final TemplateUploader tu;
this.tu = tu; private final String jobId;
this.jobId = jobId; private final String name;
this.name = name; private final ImageFormat format;
this.format = format; private String tmpltPath;
this.accountId = accountId; private String description;
this.description = descr; private String checksum;
this.checksum = cksum; private Long accountId;
this.installPathPrefix = installPathPrefix; private String installPathPrefix;
this.templatesize = 0; private long templatesize;
this.id = id; private long id;
}
public TemplateUploader getTd() { public UploadJob(TemplateUploader tu, String jobId, long id, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum, String installPathPrefix) {
return tu; super();
} this.tu = tu;
this.jobId = jobId;
this.name = name;
this.format = format;
this.accountId = accountId;
this.description = descr;
this.checksum = cksum;
this.installPathPrefix = installPathPrefix;
this.templatesize = 0;
this.id = id;
}
public String getDescription() { public TemplateUploader getTd() {
return description; return tu;
} }
public String getChecksum() { public String getDescription() {
return checksum; return description;
} }
public UploadJob(TemplateUploader td, String jobId, UploadCommand cmd) { public String getChecksum() {
this.tu = td; return checksum;
this.jobId = jobId; }
this.name = cmd.getName();
this.format = cmd.getFormat();
}
public TemplateUploader getTemplateUploader() { public UploadJob(TemplateUploader td, String jobId, UploadCommand cmd) {
return tu; this.tu = td;
} this.jobId = jobId;
this.name = cmd.getName();
this.format = cmd.getFormat();
}
public String getJobId() { public TemplateUploader getTemplateUploader() {
return jobId; return tu;
} }
public String getTmpltName() { public String getJobId() {
return name; return jobId;
} }
public ImageFormat getFormat() { public String getTmpltName() {
return format; return name;
} }
public Long getAccountId() { public ImageFormat getFormat() {
return accountId; return format;
} }
public long getId() { public Long getAccountId() {
return id; return accountId;
} }
public void setTmpltPath(String tmpltPath) { public long getId() {
this.tmpltPath = tmpltPath; return id;
} }
public String getTmpltPath() { public void setTmpltPath(String tmpltPath) {
return tmpltPath; this.tmpltPath = tmpltPath;
} }
public String getInstallPathPrefix() { public String getTmpltPath() {
return installPathPrefix; return tmpltPath;
} }
public void cleanup() { public String getInstallPathPrefix() {
if (tu != null) { return installPathPrefix;
String upldPath = tu.getUploadLocalPath(); }
if (upldPath != null) {
File f = new File(upldPath);
f.delete();
}
}
}
public void setTemplatesize(long templatesize) { public void cleanup() {
this.templatesize = templatesize; if (tu != null) {
} String upldPath = tu.getUploadLocalPath();
if (upldPath != null) {
File f = new File(upldPath);
f.delete();
}
}
}
public void setTemplatesize(long templatesize) {
this.templatesize = templatesize;
}
public long getTemplatesize() {
return templatesize;
}
}
public static final Logger s_logger = Logger.getLogger(UploadManagerImpl.class);
private ExecutorService threadPool;
private final Map<String, UploadJob> jobs = new ConcurrentHashMap<String, UploadJob>();
private String parentDir;
private List<Processor> _processors;
private String publicTemplateRepo;
private final String extractMountPoint = "/mnt/SecStorage/extractmnt";
private StorageLayer _storage;
private int installTimeoutPerGig;
private boolean _sslCopy;
private String _name;
private boolean hvm;
@Override
public String uploadPublicTemplate(long id, String url, String name,
ImageFormat format, Long accountId, String descr,
String cksum, String installPathPrefix, String userName,
String passwd, long templateSizeInBytes) {
public long getTemplatesize() {
return templatesize;
}
}
public static final Logger s_logger = Logger.getLogger(UploadManagerImpl.class);
private ExecutorService threadPool;
private final Map<String, UploadJob> jobs = new ConcurrentHashMap<String, UploadJob>();
private String parentDir;
private Adapters<Processor> _processors;
private String publicTemplateRepo;
private String extractMountPoint = "/mnt/SecStorage/extractmnt";
private StorageLayer _storage;
private int installTimeoutPerGig;
private boolean _sslCopy;
private String _name;
private boolean hvm;
@Override
public String uploadPublicTemplate(long id, String url, String name,
ImageFormat format, Long accountId, String descr,
String cksum, String installPathPrefix, String userName,
String passwd, long templateSizeInBytes) {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
String jobId = uuid.toString(); String jobId = uuid.toString();
String completePath = parentDir + File.separator + installPathPrefix; String completePath = parentDir + File.separator + installPathPrefix;
s_logger.debug("Starting upload from " + completePath); s_logger.debug("Starting upload from " + completePath);
URI uri; URI uri;
try { try {
uri = new URI(url); uri = new URI(url);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
s_logger.error("URI is incorrect: " + url); s_logger.error("URI is incorrect: " + url);
throw new CloudRuntimeException("URI is incorrect: " + url); throw new CloudRuntimeException("URI is incorrect: " + url);
} }
TemplateUploader tu; TemplateUploader tu;
if ((uri != null) && (uri.getScheme() != null)) { if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getScheme().equalsIgnoreCase("ftp")) { if (uri.getScheme().equalsIgnoreCase("ftp")) {
tu = new FtpTemplateUploader(completePath, url, new Completion(jobId), templateSizeInBytes); tu = new FtpTemplateUploader(completePath, url, new Completion(jobId), templateSizeInBytes);
} else { } else {
s_logger.error("Scheme is not supported " + url); s_logger.error("Scheme is not supported " + url);
throw new CloudRuntimeException("Scheme is not supported " + url); throw new CloudRuntimeException("Scheme is not supported " + url);
} }
} else { } else {
s_logger.error("Unable to download from URL: " + url); s_logger.error("Unable to download from URL: " + url);
throw new CloudRuntimeException("Unable to download from URL: " + url); throw new CloudRuntimeException("Unable to download from URL: " + url);
} }
UploadJob uj = new UploadJob(tu, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix); UploadJob uj = new UploadJob(tu, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix);
jobs.put(jobId, uj); jobs.put(jobId, uj);
threadPool.execute(tu); threadPool.execute(tu);
return jobId; return jobId;
}
@Override }
public String getUploadError(String jobId) {
@Override
public String getUploadError(String jobId) {
UploadJob uj = jobs.get(jobId); UploadJob uj = jobs.get(jobId);
if (uj != null) { if (uj != null) {
return uj.getTemplateUploader().getUploadError(); return uj.getTemplateUploader().getUploadError();
} }
return null; return null;
} }
@Override @Override
public int getUploadPct(String jobId) { public int getUploadPct(String jobId) {
UploadJob uj = jobs.get(jobId); UploadJob uj = jobs.get(jobId);
if (uj != null) { if (uj != null) {
return uj.getTemplateUploader().getUploadPercent(); return uj.getTemplateUploader().getUploadPercent();
} }
return 0; return 0;
} }
@Override @Override
public Status getUploadStatus(String jobId) { public Status getUploadStatus(String jobId) {
UploadJob job = jobs.get(jobId); UploadJob job = jobs.get(jobId);
if (job != null) { if (job != null) {
TemplateUploader tu = job.getTemplateUploader(); TemplateUploader tu = job.getTemplateUploader();
@ -248,8 +247,8 @@ public class UploadManagerImpl implements UploadManager {
} }
} }
return Status.UNKNOWN; return Status.UNKNOWN;
} }
public static UploadVO.Status convertStatus(Status tds) { public static UploadVO.Status convertStatus(Status tds) {
switch (tds) { switch (tds) {
case ABORTED: case ABORTED:
@ -277,11 +276,11 @@ public class UploadManagerImpl implements UploadManager {
public com.cloud.storage.UploadVO.Status getUploadStatus2(String jobId) { public com.cloud.storage.UploadVO.Status getUploadStatus2(String jobId) {
return convertStatus(getUploadStatus(jobId)); return convertStatus(getUploadStatus(jobId));
} }
@Override @Override
public String getPublicTemplateRepo() { public String getPublicTemplateRepo() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
private UploadAnswer handleUploadProgressCmd(UploadProgressCommand cmd) { private UploadAnswer handleUploadProgressCmd(UploadProgressCommand cmd) {
String jobId = cmd.getJobId(); String jobId = cmd.getJobId();
@ -290,7 +289,7 @@ public class UploadManagerImpl implements UploadManager {
if (jobId != null) if (jobId != null)
uj = jobs.get(jobId); uj = jobs.get(jobId);
if (uj == null) { if (uj == null) {
return new UploadAnswer(null, 0, "Cannot find job", com.cloud.storage.UploadVO.Status.UNKNOWN, "", "", 0); return new UploadAnswer(null, 0, "Cannot find job", com.cloud.storage.UploadVO.Status.UNKNOWN, "", "", 0);
} }
TemplateUploader td = uj.getTemplateUploader(); TemplateUploader td = uj.getTemplateUploader();
switch (cmd.getRequest()) { switch (cmd.getRequest()) {
@ -300,7 +299,7 @@ public class UploadManagerImpl implements UploadManager {
td.stopUpload(); td.stopUpload();
sleep(); sleep();
break; break;
/*case RESTART: /*case RESTART:
td.stopUpload(); td.stopUpload();
sleep(); sleep();
threadPool.execute(td); threadPool.execute(td);
@ -316,10 +315,10 @@ public class UploadManagerImpl implements UploadManager {
return new UploadAnswer(jobId, getUploadPct(jobId), getUploadError(jobId), getUploadStatus2(jobId), getUploadLocalPath(jobId), getInstallPath(jobId), return new UploadAnswer(jobId, getUploadPct(jobId), getUploadError(jobId), getUploadStatus2(jobId), getUploadLocalPath(jobId), getInstallPath(jobId),
getUploadTemplateSize(jobId)); getUploadTemplateSize(jobId));
} }
@Override @Override
public UploadAnswer handleUploadCommand(SecondaryStorageResource resource, UploadCommand cmd) { public UploadAnswer handleUploadCommand(SecondaryStorageResource resource, UploadCommand cmd) {
s_logger.warn("Handling the upload " +cmd.getInstallPath() + " " + cmd.getId()); s_logger.warn("Handling the upload " +cmd.getInstallPath() + " " + cmd.getId());
if (cmd instanceof UploadProgressCommand) { if (cmd instanceof UploadProgressCommand) {
return handleUploadProgressCmd((UploadProgressCommand) cmd); return handleUploadProgressCmd((UploadProgressCommand) cmd);
} }
@ -327,9 +326,9 @@ public class UploadManagerImpl implements UploadManager {
String user = null; String user = null;
String password = null; String password = null;
String jobId = uploadPublicTemplate(cmd.getId(), cmd.getUrl(), cmd.getName(), String jobId = uploadPublicTemplate(cmd.getId(), cmd.getUrl(), cmd.getName(),
cmd.getFormat(), cmd.getAccountId(), cmd.getDescription(), cmd.getFormat(), cmd.getAccountId(), cmd.getDescription(),
cmd.getChecksum(), cmd.getInstallPath(), user, password, cmd.getChecksum(), cmd.getInstallPath(), user, password,
cmd.getTemplateSizeInBytes()); cmd.getTemplateSizeInBytes());
sleep(); sleep();
if (jobId == null) { if (jobId == null) {
return new UploadAnswer(null, 0, "Internal Error", com.cloud.storage.UploadVO.Status.UPLOAD_ERROR, "", "", 0); return new UploadAnswer(null, 0, "Internal Error", com.cloud.storage.UploadVO.Status.UPLOAD_ERROR, "", "", 0);
@ -337,18 +336,18 @@ public class UploadManagerImpl implements UploadManager {
return new UploadAnswer(jobId, getUploadPct(jobId), getUploadError(jobId), getUploadStatus2(jobId), getUploadLocalPath(jobId), getInstallPath(jobId), return new UploadAnswer(jobId, getUploadPct(jobId), getUploadError(jobId), getUploadStatus2(jobId), getUploadLocalPath(jobId), getInstallPath(jobId),
getUploadTemplateSize(jobId)); getUploadTemplateSize(jobId));
} }
@Override @Override
public CreateEntityDownloadURLAnswer handleCreateEntityURLCommand(CreateEntityDownloadURLCommand cmd){ public CreateEntityDownloadURLAnswer handleCreateEntityURLCommand(CreateEntityDownloadURLCommand cmd){
boolean isApacheUp = checkAndStartApache(); boolean isApacheUp = checkAndStartApache();
if (!isApacheUp){ if (!isApacheUp){
String errorString = "Error in starting Apache server "; String errorString = "Error in starting Apache server ";
s_logger.error(errorString); s_logger.error(errorString);
return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
// Create the directory structure so that its visible under apache server root // Create the directory structure so that its visible under apache server root
String extractDir = "/var/www/html/userdata/"; String extractDir = "/var/www/html/userdata/";
Script command = new Script("mkdir", s_logger); Script command = new Script("mkdir", s_logger);
command.add("-p"); command.add("-p");
command.add(extractDir); command.add(extractDir);
@ -358,19 +357,19 @@ public class UploadManagerImpl implements UploadManager {
s_logger.error(errorString); s_logger.error(errorString);
return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
// Create a random file under the directory for security reasons. // Create a random file under the directory for security reasons.
String uuid = cmd.getExtractLinkUUID(); String uuid = cmd.getExtractLinkUUID();
command = new Script("touch", s_logger); command = new Script("touch", s_logger);
command.add(extractDir + uuid); command.add(extractDir + uuid);
result = command.execute(); result = command.execute();
if (result != null) { if (result != null) {
String errorString = "Error in creating file " +uuid+ " ,error: " + result; String errorString = "Error in creating file " +uuid+ " ,error: " + result;
s_logger.warn(errorString); s_logger.warn(errorString);
return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
// Create a symbolic link from the actual directory to the template location. The entity would be directly visible under /var/www/html/userdata/cmd.getInstallPath(); // Create a symbolic link from the actual directory to the template location. The entity would be directly visible under /var/www/html/userdata/cmd.getInstallPath();
command = new Script("/bin/bash", s_logger); command = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
@ -381,11 +380,11 @@ public class UploadManagerImpl implements UploadManager {
s_logger.error(errorString); s_logger.error(errorString);
return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new CreateEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
return new CreateEntityDownloadURLAnswer("", CreateEntityDownloadURLAnswer.RESULT_SUCCESS); return new CreateEntityDownloadURLAnswer("", CreateEntityDownloadURLAnswer.RESULT_SUCCESS);
} }
@Override @Override
public DeleteEntityDownloadURLAnswer handleDeleteEntityDownloadURLCommand(DeleteEntityDownloadURLCommand cmd){ public DeleteEntityDownloadURLAnswer handleDeleteEntityDownloadURLCommand(DeleteEntityDownloadURLCommand cmd){
@ -394,8 +393,8 @@ public class UploadManagerImpl implements UploadManager {
String path = cmd.getPath(); String path = cmd.getPath();
Script command = new Script("/bin/bash", s_logger); Script command = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
//We just need to remove the UUID.vhd //We just need to remove the UUID.vhd
String extractUrl = cmd.getExtractUrl(); String extractUrl = cmd.getExtractUrl();
command.add("unlink /var/www/html/userdata/" +extractUrl.substring(extractUrl.lastIndexOf(File.separator) + 1)); command.add("unlink /var/www/html/userdata/" +extractUrl.substring(extractUrl.lastIndexOf(File.separator) + 1));
String result = command.execute(); String result = command.execute();
@ -404,7 +403,7 @@ public class UploadManagerImpl implements UploadManager {
s_logger.warn(errorString); s_logger.warn(errorString);
return new DeleteEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new DeleteEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
// If its a volume also delete the Hard link since it was created only for the purpose of download. // If its a volume also delete the Hard link since it was created only for the purpose of download.
if(cmd.getType() == Upload.Type.VOLUME){ if(cmd.getType() == Upload.Type.VOLUME){
command = new Script("/bin/bash", s_logger); command = new Script("/bin/bash", s_logger);
@ -418,31 +417,31 @@ public class UploadManagerImpl implements UploadManager {
return new DeleteEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE); return new DeleteEntityDownloadURLAnswer(errorString, CreateEntityDownloadURLAnswer.RESULT_FAILURE);
} }
} }
return new DeleteEntityDownloadURLAnswer("", CreateEntityDownloadURLAnswer.RESULT_SUCCESS); return new DeleteEntityDownloadURLAnswer("", CreateEntityDownloadURLAnswer.RESULT_SUCCESS);
} }
private String getInstallPath(String jobId) { private String getInstallPath(String jobId) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
private String getUploadLocalPath(String jobId) { private String getUploadLocalPath(String jobId) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
private long getUploadTemplateSize(String jobId){ private long getUploadTemplateSize(String jobId){
UploadJob uj = jobs.get(jobId); UploadJob uj = jobs.get(jobId);
if (uj != null) { if (uj != null) {
return uj.getTemplatesize(); return uj.getTemplatesize();
} }
return 0; return 0;
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException { throws ConfigurationException {
_name = name; _name = name;
String value = null; String value = null;
@ -457,21 +456,25 @@ public class UploadManagerImpl implements UploadManager {
Class<StorageLayer> clazz; Class<StorageLayer> clazz;
try { try {
clazz = (Class<StorageLayer>) Class.forName(value); clazz = (Class<StorageLayer>) Class.forName(value);
_storage = clazz.newInstance();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to instantiate " + value); throw new ConfigurationException("Unable to instantiate " + value);
} catch (InstantiationException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} }
_storage = ComponentLocator.inject(clazz);
} }
String useSsl = (String)params.get("sslcopy"); String useSsl = (String)params.get("sslcopy");
if (useSsl != null) { if (useSsl != null) {
_sslCopy = Boolean.parseBoolean(useSsl); _sslCopy = Boolean.parseBoolean(useSsl);
} }
String inSystemVM = (String)params.get("secondary.storage.vm"); String inSystemVM = (String)params.get("secondary.storage.vm");
if (inSystemVM != null && "true".equalsIgnoreCase(inSystemVM)) { if (inSystemVM != null && "true".equalsIgnoreCase(inSystemVM)) {
s_logger.info("UploadManager: starting additional services since we are inside system vm"); s_logger.info("UploadManager: starting additional services since we are inside system vm");
startAdditionalServices(); startAdditionalServices();
//blockOutgoingOnPrivate(); //blockOutgoingOnPrivate();
} }
value = (String) params.get("install.timeout.pergig"); value = (String) params.get("install.timeout.pergig");
@ -489,53 +492,53 @@ public class UploadManagerImpl implements UploadManager {
threadPool = Executors.newFixedThreadPool(numInstallThreads); threadPool = Executors.newFixedThreadPool(numInstallThreads);
return true; return true;
} }
private void startAdditionalServices() {
Script command = new Script("rm", s_logger);
command.add("-rf");
command.add(extractMountPoint);
String result = command.execute();
if (result != null) {
s_logger.warn("Error in creating file " +extractMountPoint+ " ,error: " + result );
return;
}
command = new Script("touch", s_logger);
command.add(extractMountPoint);
result = command.execute();
if (result != null) {
s_logger.warn("Error in creating file " +extractMountPoint+ " ,error: " + result );
return;
}
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("ln -sf " + parentDir + " " +extractMountPoint);
result = command.execute();
if (result != null) {
s_logger.warn("Error in linking err=" + result );
return;
}
}
@Override private void startAdditionalServices() {
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override Script command = new Script("rm", s_logger);
public boolean stop() { command.add("-rf");
return true; command.add(extractMountPoint);
} String result = command.execute();
if (result != null) {
s_logger.warn("Error in creating file " +extractMountPoint+ " ,error: " + result );
return;
}
command = new Script("touch", s_logger);
command.add(extractMountPoint);
result = command.execute();
if (result != null) {
s_logger.warn("Error in creating file " +extractMountPoint+ " ,error: " + result );
return;
}
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("ln -sf " + parentDir + " " +extractMountPoint);
result = command.execute();
if (result != null) {
s_logger.warn("Error in linking err=" + result );
return;
}
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
/** /**
* Get notified of change of job status. Executed in context of uploader thread * Get notified of change of job status. Executed in context of uploader thread
@ -582,7 +585,7 @@ public class UploadManagerImpl implements UploadManager {
tu.setStatus(Status.UNRECOVERABLE_ERROR); tu.setStatus(Status.UNRECOVERABLE_ERROR);
tu.setUploadError("Failed post upload script: " + result); tu.setUploadError("Failed post upload script: " + result);
} else { } else {
s_logger.warn("Upload completed successfully at " + new SimpleDateFormat().format(new Date())); s_logger.warn("Upload completed successfully at " + new SimpleDateFormat().format(new Date()));
tu.setStatus(Status.POST_UPLOAD_FINISHED); tu.setStatus(Status.POST_UPLOAD_FINISHED);
tu.setUploadError("Upload completed successfully at " + new SimpleDateFormat().format(new Date())); tu.setUploadError("Upload completed successfully at " + new SimpleDateFormat().format(new Date()));
} }
@ -596,9 +599,9 @@ public class UploadManagerImpl implements UploadManager {
} }
} }
private String postUpload(String jobId) { private String postUpload(String jobId) {
return null; return null;
} }
private void sleep() { private void sleep() {
try { try {
@ -608,21 +611,21 @@ public class UploadManagerImpl implements UploadManager {
} }
} }
private boolean checkAndStartApache() { private boolean checkAndStartApache() {
//Check whether the Apache server is running //Check whether the Apache server is running
Script command = new Script("/bin/bash", s_logger); Script command = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 status | grep pid; else service httpd status | grep pid; fi "); command.add("if [ -d /etc/apache2 ] ; then service apache2 status | grep pid; else service httpd status | grep pid; fi ");
String result = command.execute(); String result = command.execute();
//Apache Server is not running. Try to start it. //Apache Server is not running. Try to start it.
if (result != null) { if (result != null) {
/*s_logger.warn("Apache server not running, trying to start it"); /*s_logger.warn("Apache server not running, trying to start it");
String port = Integer.toString(TemplateConstants.DEFAULT_TMPLT_COPY_PORT); String port = Integer.toString(TemplateConstants.DEFAULT_TMPLT_COPY_PORT);
String intf = TemplateConstants.DEFAULT_TMPLT_COPY_INTF; String intf = TemplateConstants.DEFAULT_TMPLT_COPY_INTF;
command = new Script("/bin/bash", s_logger); command = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
command.add("iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" + command.add("iptables -D INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j DROP;" +
@ -636,23 +639,23 @@ public class UploadManagerImpl implements UploadManager {
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" + "iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j DROP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" + "iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j HTTP;" +
"iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;"); "iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j HTTP;");
result = command.execute(); result = command.execute();
if (result != null) { if (result != null) {
s_logger.warn("Error in opening up httpd port err=" + result ); s_logger.warn("Error in opening up httpd port err=" + result );
return false; return false;
}*/ }*/
command = new Script("/bin/bash", s_logger); command = new Script("/bin/bash", s_logger);
command.add("-c"); command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 start; else service httpd start; fi "); command.add("if [ -d /etc/apache2 ] ; then service apache2 start; else service httpd start; fi ");
result = command.execute(); result = command.execute();
if (result != null) { if (result != null) {
s_logger.warn("Error in starting httpd service err=" + result ); s_logger.warn("Error in starting httpd service err=" + result );
return false; return false;
} }
} }
return true; return true;
} }
} }

View File

@ -8,7 +8,7 @@ import org.apache.cloudstack.storage.snapshot.SnapshotInfo;
import org.apache.cloudstack.storage.volume.ObjectInDataStoreStateMachine.Event; import org.apache.cloudstack.storage.volume.ObjectInDataStoreStateMachine.Event;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.utils.component.Inject;
@Component @Component
public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager { public class ObjectInDataStoreManagerImpl implements ObjectInDataStoreManager {

View File

@ -38,7 +38,7 @@ import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Volume; import com.cloud.storage.Volume;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -29,7 +29,7 @@ import com.cloud.exception.InvalidParameterValueException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.AssociateLunCmdResponse; import com.cloud.server.api.response.netapp.AssociateLunCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "associateLun", 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 class AssociateLunCmd extends BaseCmd {

View File

@ -33,7 +33,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.CreateLunCmdResponse; import com.cloud.server.api.response.netapp.CreateLunCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "createLunOnFiler", 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 class CreateLunCmd extends BaseCmd {

View File

@ -32,7 +32,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.CreateVolumeOnFilerCmdResponse; import com.cloud.server.api.response.netapp.CreateVolumeOnFilerCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "createVolumeOnFiler", description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class) @APICommand(name = "createVolumeOnFiler", description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class)
public class CreateVolumeOnFilerCmd extends BaseCmd { public class CreateVolumeOnFilerCmd extends BaseCmd {

View File

@ -31,7 +31,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.CreateVolumePoolCmdResponse; import com.cloud.server.api.response.netapp.CreateVolumePoolCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "createPool", description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class) @APICommand(name = "createPool", description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class)
public class CreateVolumePoolCmd extends BaseCmd { public class CreateVolumePoolCmd extends BaseCmd {

View File

@ -33,7 +33,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.DeleteVolumePoolCmdResponse; import com.cloud.server.api.response.netapp.DeleteVolumePoolCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "deletePool", description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class) @APICommand(name = "deletePool", description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class)
public class DeleteVolumePoolCmd extends BaseCmd { public class DeleteVolumePoolCmd extends BaseCmd {

View File

@ -33,7 +33,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.DeleteLUNCmdResponse; import com.cloud.server.api.response.netapp.DeleteLUNCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "destroyLunOnFiler", description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) @APICommand(name = "destroyLunOnFiler", description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class)
public class DestroyLunCmd extends BaseCmd { public class DestroyLunCmd extends BaseCmd {

View File

@ -31,7 +31,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.DeleteVolumeOnFilerCmdResponse; import com.cloud.server.api.response.netapp.DeleteVolumeOnFilerCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "destroyVolumeOnFiler", description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class) @APICommand(name = "destroyVolumeOnFiler", description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class)
public class DestroyVolumeOnFilerCmd extends BaseCmd { public class DestroyVolumeOnFilerCmd extends BaseCmd {

View File

@ -30,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.DissociateLunCmdResponse; import com.cloud.server.api.response.netapp.DissociateLunCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "dissociateLun", description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class) @APICommand(name = "dissociateLun", description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class)
public class DissociateLunCmd extends BaseCmd { public class DissociateLunCmd extends BaseCmd {

View File

@ -36,7 +36,7 @@ import com.cloud.netapp.LunVO;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.ListLunsCmdResponse; import com.cloud.server.api.response.netapp.ListLunsCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "listLunsOnFiler", description="List LUN", responseObject = ListLunsCmdResponse.class) @APICommand(name = "listLunsOnFiler", description="List LUN", responseObject = ListLunsCmdResponse.class)
public class ListLunsCmd extends BaseCmd public class ListLunsCmd extends BaseCmd

View File

@ -34,7 +34,7 @@ import com.cloud.netapp.NetappManager;
import com.cloud.netapp.PoolVO; import com.cloud.netapp.PoolVO;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.ListVolumePoolsCmdResponse; import com.cloud.server.api.response.netapp.ListVolumePoolsCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "listPools", description="List Pool", responseObject = ListVolumePoolsCmdResponse.class) @APICommand(name = "listPools", description="List Pool", responseObject = ListVolumePoolsCmdResponse.class)
public class ListVolumePoolsCmd extends BaseCmd { public class ListVolumePoolsCmd extends BaseCmd {

View File

@ -33,7 +33,7 @@ import com.cloud.netapp.NetappManager;
import com.cloud.netapp.NetappVolumeVO; import com.cloud.netapp.NetappVolumeVO;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.ListVolumesOnFilerCmdResponse; import com.cloud.server.api.response.netapp.ListVolumesOnFilerCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "listVolumesOnFiler", description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class) @APICommand(name = "listVolumesOnFiler", description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class)
public class ListVolumesOnFilerCmd extends BaseCmd { public class ListVolumesOnFilerCmd extends BaseCmd {

View File

@ -31,7 +31,7 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.netapp.NetappManager; import com.cloud.netapp.NetappManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.server.api.response.netapp.ModifyVolumePoolCmdResponse; import com.cloud.server.api.response.netapp.ModifyVolumePoolCmdResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "modifyPool", description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class) @APICommand(name = "modifyPool", description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class)
public class ModifyVolumePoolCmd extends BaseCmd { public class ModifyVolumePoolCmd extends BaseCmd {

View File

@ -36,7 +36,6 @@ import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.offering.ServiceOffering; import com.cloud.offering.ServiceOffering;
import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceManager;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;
@ -53,39 +52,39 @@ public class RandomAllocator implements HostAllocator {
ExcludeList avoid, int returnUpTo) { ExcludeList avoid, int returnUpTo) {
return allocateTo(vmProfile, plan, type, avoid, returnUpTo, true); return allocateTo(vmProfile, plan, type, avoid, returnUpTo, true);
} }
@Override @Override
public List<Host> allocateTo(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, Type type, public List<Host> allocateTo(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, Type type,
ExcludeList avoid, int returnUpTo, boolean considerReservedCapacity) { ExcludeList avoid, int returnUpTo, boolean considerReservedCapacity) {
long dcId = plan.getDataCenterId();
Long podId = plan.getPodId();
Long clusterId = plan.getClusterId();
ServiceOffering offering = vmProfile.getServiceOffering();
List<Host> suitableHosts = new ArrayList<Host>();
long dcId = plan.getDataCenterId();
Long podId = plan.getPodId();
Long clusterId = plan.getClusterId();
ServiceOffering offering = vmProfile.getServiceOffering();
List<Host> suitableHosts = new ArrayList<Host>();
if (type == Host.Type.Storage) { if (type == Host.Type.Storage) {
return suitableHosts; return suitableHosts;
} }
String hostTag = offering.getHostTag(); String hostTag = offering.getHostTag();
if(hostTag != null){ if(hostTag != null){
s_logger.debug("Looking for hosts in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId + " having host tag:" + hostTag); s_logger.debug("Looking for hosts in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId + " having host tag:" + hostTag);
}else{ }else{
s_logger.debug("Looking for hosts in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId); s_logger.debug("Looking for hosts in dc: " + dcId + " pod:" + podId + " cluster:" + clusterId);
} }
// list all computing hosts, regardless of whether they support routing...it's random after all // list all computing hosts, regardless of whether they support routing...it's random after all
List<? extends Host> hosts = new ArrayList<HostVO>(); List<? extends Host> hosts = new ArrayList<HostVO>();
if(hostTag != null){ if(hostTag != null){
hosts = _hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag); hosts = _hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag);
}else{ }else{
hosts = _resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId); hosts = _resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId);
} }
s_logger.debug("Random Allocator found " + hosts.size() + " hosts"); s_logger.debug("Random Allocator found " + hosts.size() + " hosts");
if (hosts.size() == 0) { if (hosts.size() == 0) {
return suitableHosts; return suitableHosts;
} }
@ -93,12 +92,12 @@ public class RandomAllocator implements HostAllocator {
Collections.shuffle(hosts); Collections.shuffle(hosts);
for (Host host : hosts) { for (Host host : hosts) {
if(suitableHosts.size() == returnUpTo){ if(suitableHosts.size() == returnUpTo){
break; break;
} }
if (!avoid.shouldAvoid(host)) { if (!avoid.shouldAvoid(host)) {
suitableHosts.add(host); suitableHosts.add(host);
}else{ }else{
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Host name: " + host.getName() + ", hostId: "+ host.getId() +" is in avoid set, skipping this and trying other available hosts"); s_logger.debug("Host name: " + host.getName() + ", hostId: "+ host.getId() +" is in avoid set, skipping this and trying other available hosts");
@ -121,7 +120,7 @@ public class RandomAllocator implements HostAllocator {
@Override @Override
public boolean configure(String name, Map<String, Object> params) { public boolean configure(String name, Map<String, Object> params) {
_name=name; _name=name;
return true; return true;
} }

View File

@ -212,7 +212,7 @@ import com.cloud.storage.template.TemplateLocation;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.OutputInterpreter;

View File

@ -58,7 +58,7 @@ import com.cloud.simulator.MockVMVO;
import com.cloud.simulator.dao.MockHostDao; import com.cloud.simulator.dao.MockHostDao;
import com.cloud.simulator.dao.MockVMDao; import com.cloud.simulator.dao.MockVMDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;

View File

@ -77,7 +77,7 @@ import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.template.TemplateInfo; import com.cloud.storage.template.TemplateInfo;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DiskProfile; import com.cloud.vm.DiskProfile;

View File

@ -46,7 +46,7 @@ import com.cloud.simulator.dao.MockSecurityRulesDao;
import com.cloud.simulator.dao.MockVMDao; import com.cloud.simulator.dao.MockVMDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachine.State;

View File

@ -28,7 +28,7 @@ import com.cloud.simulator.MockVMVO;
import com.cloud.simulator.dao.MockConfigurationDao; import com.cloud.simulator.dao.MockConfigurationDao;
import com.cloud.simulator.dao.MockHostDao; import com.cloud.simulator.dao.MockHostDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.ConnectionConcierge; import com.cloud.utils.db.ConnectionConcierge;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;

View File

@ -31,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "configureSimulator", description="configure simulator", responseObject=SuccessResponse.class) @APICommand(name = "configureSimulator", description="configure simulator", responseObject=SuccessResponse.class)
public class ConfigureSimulator extends BaseCmd { public class ConfigureSimulator extends BaseCmd {

View File

@ -43,7 +43,7 @@ import com.cloud.agent.manager.SimulatorManager.AgentType;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.host.Host.Type; import com.cloud.host.Host.Type;
import com.cloud.simulator.MockHost; import com.cloud.simulator.MockHost;
import com.cloud.utils.component.ComponentLocator;
public class AgentResourceBase implements ServerResource { public class AgentResourceBase implements ServerResource {
private static final Logger s_logger = Logger private static final Logger s_logger = Logger

View File

@ -54,7 +54,7 @@ import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao; import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VMTemplateZoneDao; import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.utils.component.Inject;
@Local(value = Discoverer.class) @Local(value = Discoverer.class)
public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter { public class SimulatorDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter {

View File

@ -38,7 +38,7 @@ import com.cloud.host.Status;
import com.cloud.storage.SnapshotVO; import com.cloud.storage.SnapshotVO;
import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.secondary.SecondaryStorageDiscoverer; import com.cloud.storage.secondary.SecondaryStorageDiscoverer;
import com.cloud.utils.component.Inject;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;

View File

@ -24,7 +24,7 @@ import com.cloud.hypervisor.HypervisorGuruBase;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.GuestOSVO; import com.cloud.storage.GuestOSVO;
import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.GuestOSDao;
import com.cloud.utils.component.Inject;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfile;

View File

@ -25,7 +25,7 @@ import javax.naming.ConfigurationException;
import com.cloud.simulator.MockHostVO; import com.cloud.simulator.MockHostVO;
import com.cloud.simulator.MockVMVO; import com.cloud.simulator.MockVMVO;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;

View File

@ -66,7 +66,7 @@ import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao; import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.UriUtils; import com.cloud.utils.UriUtils;
import com.cloud.utils.component.ComponentLocator;
import com.vmware.vim25.ClusterDasConfigInfo; import com.vmware.vim25.ClusterDasConfigInfo;
import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ManagedObjectReference;

View File

@ -86,7 +86,7 @@ import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.utils.FileUtil; import com.cloud.utils.FileUtil;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;

View File

@ -21,7 +21,7 @@ import org.apache.log4j.Logger;
import com.cloud.hypervisor.vmware.manager.VmwareManager; import com.cloud.hypervisor.vmware.manager.VmwareManager;
import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentLocator;
import com.vmware.apputils.version.ExtendedAppUtil; import com.vmware.apputils.version.ExtendedAppUtil;
public class VmwareContextFactory { public class VmwareContextFactory {

View File

@ -200,7 +200,7 @@ import com.cloud.storage.template.TemplateInfo;
import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExceptionUtil; import com.cloud.utils.exception.ExceptionUtil;

View File

@ -30,7 +30,7 @@ import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.LoadBalancerDaoImpl; import com.cloud.network.dao.LoadBalancerDaoImpl;
import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.network.router.VirtualRouter.Role; import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;

View File

@ -30,7 +30,7 @@ import org.springframework.stereotype.Component;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
/** /**

View File

@ -30,7 +30,7 @@ import org.springframework.stereotype.Component;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;

View File

@ -32,8 +32,8 @@ import com.cloud.server.ManagementServer;
import com.cloud.servlet.CloudStartupServlet; import com.cloud.servlet.CloudStartupServlet;
import com.cloud.user.UserAccount; import com.cloud.user.UserAccount;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@Local(value={UserAuthenticator.class}) @Local(value={UserAuthenticator.class})

View File

@ -66,7 +66,6 @@ import com.cloud.agent.transport.Response;
import com.cloud.alert.AlertManager; import com.cloud.alert.AlertManager;
import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ManagementServerNode; import com.cloud.cluster.ManagementServerNode;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterDetailsDao;
@ -977,8 +976,6 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager {
} }
} catch (final Exception e) { } catch (final Exception e) {
s_logger.error("Exception caught while handling disconnect: ", e); s_logger.error("Exception caught while handling disconnect: ", e);
} finally {
StackMaid.current().exitCleanup();
} }
} }
} }
@ -1150,7 +1147,6 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager {
if (actionDelegate != null) { if (actionDelegate != null) {
actionDelegate.action(new Long(id)); actionDelegate.action(new Long(id));
} }
StackMaid.current().exitCleanup();
} }
} }
} }
@ -1381,7 +1377,6 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager {
} }
} }
} finally { } finally {
StackMaid.current().exitCleanup();
txn.close(); txn.close();
} }
} }

View File

@ -62,7 +62,6 @@ import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ClusteredAgentRebalanceService; import com.cloud.cluster.ClusteredAgentRebalanceService;
import com.cloud.cluster.ManagementServerHost; import com.cloud.cluster.ManagementServerHost;
import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.cluster.StackMaid;
import com.cloud.cluster.agentlb.AgentLoadBalancerPlanner; import com.cloud.cluster.agentlb.AgentLoadBalancerPlanner;
import com.cloud.cluster.agentlb.HostTransferMapVO; import com.cloud.cluster.agentlb.HostTransferMapVO;
import com.cloud.cluster.agentlb.HostTransferMapVO.HostTransferState; import com.cloud.cluster.agentlb.HostTransferMapVO.HostTransferState;
@ -1120,8 +1119,6 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust
rebalanceHost(hostId, currentOwnerId, futureOwnerId); rebalanceHost(hostId, currentOwnerId, futureOwnerId);
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Unable to rebalance host id=" + hostId, e); s_logger.warn("Unable to rebalance host id=" + hostId, e);
} finally {
StackMaid.current().exitCleanup();
} }
} }
} }

View File

@ -104,12 +104,12 @@ import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.ResponseServer;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.response.ApiResponseSerializer; import com.cloud.api.response.ApiResponseSerializer;
import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJob;
import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO; import com.cloud.async.AsyncJobVO;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
@ -136,19 +136,20 @@ import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CSExceptionErrorCode;
import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDao;
@Component
public class ApiServer implements HttpRequestHandler { public class ApiServer implements HttpRequestHandler {
private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
public static boolean encodeApiResponse = false; public static boolean encodeApiResponse = false;
public static String jsonContentType = "text/javascript"; public static String jsonContentType = "text/javascript";
private ApiDispatcher _dispatcher; @Inject ApiDispatcher _dispatcher;
@Inject private final AccountManager _accountMgr = null; @Inject AccountManager _accountMgr;
@Inject private final DomainManager _domainMgr = null; @Inject DomainManager _domainMgr;
@Inject private final AsyncJobManager _asyncMgr = null; @Inject AsyncJobManager _asyncMgr;
@Inject private ConfigurationDao _configDao; @Inject ConfigurationDao _configDao;
@Inject protected List<APIAccessChecker> _apiAccessCheckers; @Inject List<APIAccessChecker> _apiAccessCheckers;
@Inject List<PluggableService> _pluggableServices; @Inject List<PluggableService> _pluggableServices;
@Inject IdentityDao _identityDao; @Inject IdentityDao _identityDao;
@ -190,7 +191,6 @@ public class ApiServer implements HttpRequestHandler {
_systemAccount = _accountMgr.getSystemAccount(); _systemAccount = _accountMgr.getSystemAccount();
_systemUser = _accountMgr.getSystemUser(); _systemUser = _accountMgr.getSystemUser();
_dispatcher = ApiDispatcher.getInstance();
Integer apiPort = null; // api port, null by default Integer apiPort = null; // api port, null by default
SearchCriteria<ConfigurationVO> sc = _configDao.createSearchCriteria(); SearchCriteria<ConfigurationVO> sc = _configDao.createSearchCriteria();
@ -907,12 +907,8 @@ public class ApiServer implements HttpRequestHandler {
HttpContext context = new BasicHttpContext(null); HttpContext context = new BasicHttpContext(null);
try { try {
while (!Thread.interrupted() && _conn.isOpen()) { while (!Thread.interrupted() && _conn.isOpen()) {
try { _httpService.handleRequest(_conn, context);
_httpService.handleRequest(_conn, context); _conn.close();
_conn.close();
} finally {
StackMaid.current().exitCleanup();
}
} }
} catch (ConnectionClosedException ex) { } catch (ConnectionClosedException ex) {
if (s_logger.isTraceEnabled()) { if (s_logger.isTraceEnabled()) {

View File

@ -23,6 +23,7 @@ import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -32,14 +33,11 @@ import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.cluster.StackMaid;
import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.CloudAuthenticationException;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountService; import com.cloud.user.AccountService;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@SuppressWarnings("serial") @SuppressWarnings("serial")
@ -47,8 +45,8 @@ public class ApiServlet extends HttpServlet {
public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName()); public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
private ApiServer _apiServer = null; ApiServer _apiServer;
private AccountService _accountMgr = null; @Inject AccountService _accountMgr;
public ApiServlet() { public ApiServlet() {
super(); super();
@ -56,26 +54,16 @@ public class ApiServlet extends HttpServlet {
if (_apiServer == null) { if (_apiServer == null) {
throw new CloudRuntimeException("ApiServer not initialized"); throw new CloudRuntimeException("ApiServer not initialized");
} }
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_accountMgr = locator.getManager(AccountService.class);
} }
@Override @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) { protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try { processRequest(req, resp);
processRequest(req, resp);
} finally {
StackMaid.current().exitCleanup();
}
} }
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { processRequest(req, resp);
processRequest(req, resp);
} finally {
StackMaid.current().exitCleanup();
}
} }
private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) { private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
@ -128,7 +116,7 @@ public class ApiServlet extends HttpServlet {
reqStr = auditTrailSb.toString() + " " + req.getQueryString(); reqStr = auditTrailSb.toString() + " " + req.getQueryString();
s_logger.debug("===START=== " + StringUtils.cleanString(reqStr)); s_logger.debug("===START=== " + StringUtils.cleanString(reqStr));
} }
try { try {
HttpSession session = req.getSession(false); HttpSession session = req.getSession(false);
Object[] responseTypeParam = params.get("response"); Object[] responseTypeParam = params.get("response");
@ -305,7 +293,7 @@ public class ApiServlet extends HttpServlet {
auditTrailSb.insert(0, auditTrailSb.insert(0,
"(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null) "(userId=" + UserContext.current().getCallerUserId() + " accountId=" + UserContext.current().getCaller().getId() + " sessionId=" + (session != null ? session.getId() : null)
+ ")"); + ")");
try { try {
String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb); String response = _apiServer.handleRequest(params, false, responseType, auditTrailSb);
@ -386,7 +374,7 @@ public class ApiServlet extends HttpServlet {
private String getLoginSuccessResponse(HttpSession session, String responseType) { private String getLoginSuccessResponse(HttpSession session, String responseType) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
int inactiveInterval = session.getMaxInactiveInterval(); int inactiveInterval = session.getMaxInactiveInterval();
String user_UUID = (String)session.getAttribute("user_UUID"); String user_UUID = (String)session.getAttribute("user_UUID");
session.removeAttribute("user_UUID"); session.removeAttribute("user_UUID");

View File

@ -16,91 +16,93 @@
// under the License. // under the License.
package com.cloud.api.commands; package com.cloud.api.commands;
import org.apache.cloudstack.api.*; import javax.inject.Inject;
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.ServerApiException;
import org.apache.cloudstack.api.response.TrafficMonitorResponse;
import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.network.NetworkUsageManager; import com.cloud.network.NetworkUsageManager;
import com.cloud.server.ManagementService;
import org.apache.cloudstack.api.response.TrafficMonitorResponse;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@APICommand(name = "addTrafficMonitor", description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class) @APICommand(name = "addTrafficMonitor", description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class)
public class AddTrafficMonitorCmd extends BaseCmd { public class AddTrafficMonitorCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName());
private static final String s_name = "addtrafficmonitorresponse"; private static final String s_name = "addtrafficmonitorresponse";
@Inject NetworkUsageManager networkUsageMgr;
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class,
required = true, description="Zone in which to add the external firewall appliance.") required = true, description="Zone in which to add the external firewall appliance.")
private Long zoneId; private Long zoneId;
@Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host")
private String url;
@Parameter(name=ApiConstants.INCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will be metered") @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the traffic monitor Host")
private String inclZones; private String url;
@Parameter(name=ApiConstants.EXCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will not be metered")
private String exclZones;
///////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getInclZones() {
return inclZones;
}
public String getExclZones() {
return exclZones;
}
public Long getZoneId() { @Parameter(name=ApiConstants.INCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will be metered")
return zoneId; private String inclZones;
}
public String getUrl() { @Parameter(name=ApiConstants.EXCL_ZONES, type=CommandType.STRING, description="Traffic going into the listed zones will not be metered")
return url; private String exclZones;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override ///////////////////////////////////////////////////
public String getCommandName() { /////////////////// Accessors ///////////////////////
return s_name; /////////////////////////////////////////////////////
}
public String getInclZones() {
@Override return inclZones;
}
public String getExclZones() {
return exclZones;
}
public Long getZoneId() {
return zoneId;
}
public String getUrl() {
return url;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
@Override @Override
public void execute(){ public void execute(){
try { try {
ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this);
NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class); TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor);
Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this); response.setObjectName("trafficmonitor");
TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor); response.setResponseName(getCommandName());
response.setObjectName("trafficmonitor"); this.setResponseObject(response);
response.setResponseName(getCommandName()); } catch (InvalidParameterValueException ipve) {
this.setResponseObject(response); throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage());
} catch (InvalidParameterValueException ipve) { } catch (CloudRuntimeException cre) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
} catch (CloudRuntimeException cre) { }
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage());
}
} }
} }

View File

@ -16,71 +16,70 @@
// under the License. // under the License.
package com.cloud.api.commands; package com.cloud.api.commands;
import org.apache.cloudstack.api.response.HostResponse; import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.log4j.Logger;
import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.NetworkUsageManager; import com.cloud.network.NetworkUsageManager;
import com.cloud.server.ManagementService;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "deleteTrafficMonitor", 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 class DeleteTrafficMonitorCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName());
private static final String s_name = "deletetrafficmonitorresponse"; private static final String s_name = "deletetrafficmonitorresponse";
@Inject NetworkUsageManager _networkUsageMgr;
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////////////// API parameters ///////////////////// //////////////// API parameters /////////////////////
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class,
required = true, description="Id of the Traffic Monitor Host.")
private Long id;
///////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class,
public String getCommandName() { required = true, description="Id of the Traffic Monitor Host.")
return s_name; private Long id;
}
///////////////////////////////////////////////////
@Override /////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getId() {
return id;
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() { public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM; return Account.ACCOUNT_ID_SYSTEM;
} }
@Override @Override
public void execute(){ public void execute(){
try { try {
ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); boolean result = _networkUsageMgr.deleteTrafficMonitor(this);
NetworkUsageManager _networkUsageMgr = locator.getManager(NetworkUsageManager.class); if (result) {
boolean result = _networkUsageMgr.deleteTrafficMonitor(this); SuccessResponse response = new SuccessResponse(getCommandName());
if (result) { response.setResponseName(getCommandName());
SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response);
response.setResponseName(getCommandName()); } else {
this.setResponseObject(response); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor.");
} else { }
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete traffic monitor."); } catch (InvalidParameterValueException e) {
} throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
} catch (InvalidParameterValueException e) { }
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to delete traffic monitor.");
}
} }
} }

View File

@ -32,7 +32,7 @@ import com.cloud.host.Host;
import com.cloud.network.NetworkUsageManager; import com.cloud.network.NetworkUsageManager;
import com.cloud.server.ManagementService; import com.cloud.server.ManagementService;
import org.apache.cloudstack.api.response.TrafficMonitorResponse; import org.apache.cloudstack.api.response.TrafficMonitorResponse;
import com.cloud.utils.component.ComponentLocator;
@APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class) @APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class)
public class ListTrafficMonitorsCmd extends BaseListCmd { public class ListTrafficMonitorsCmd extends BaseListCmd {

View File

@ -20,21 +20,19 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.DomainRouterResponse;
import org.apache.cloudstack.api.response.NicResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiResponseHelper;
import com.cloud.api.query.vo.DomainRouterJoinVO; import com.cloud.api.query.vo.DomainRouterJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.DomainRouterResponse;
import org.apache.cloudstack.api.response.NicResponse;
import org.springframework.stereotype.Component;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.router.VirtualRouter; import com.cloud.network.router.VirtualRouter;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -47,9 +45,9 @@ public class DomainRouterJoinDaoImpl extends GenericDaoBase<DomainRouterJoinVO,
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<DomainRouterJoinVO> vrSearch; private final SearchBuilder<DomainRouterJoinVO> vrSearch;
private SearchBuilder<DomainRouterJoinVO> vrIdSearch; private final SearchBuilder<DomainRouterJoinVO> vrIdSearch;
protected DomainRouterJoinDaoImpl() { protected DomainRouterJoinDaoImpl() {

View File

@ -25,21 +25,19 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.ApiConstants.HostDetails;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.vo.HostJoinVO; import com.cloud.api.query.vo.HostJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.host.Host; import com.cloud.host.Host;
import com.cloud.host.HostStats; import com.cloud.host.HostStats;
import org.apache.cloudstack.api.ApiConstants.HostDetails;
import org.apache.cloudstack.api.response.HostResponse;
import org.springframework.stereotype.Component;
import com.cloud.storage.StorageStats; import com.cloud.storage.StorageStats;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -52,9 +50,9 @@ public class HostJoinDaoImpl extends GenericDaoBase<HostJoinVO, Long> implements
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<HostJoinVO> hostSearch; private final SearchBuilder<HostJoinVO> hostSearch;
private SearchBuilder<HostJoinVO> hostIdSearch; private final SearchBuilder<HostJoinVO> hostIdSearch;
protected HostJoinDaoImpl() { protected HostJoinDaoImpl() {
@ -97,14 +95,14 @@ public class HostJoinDaoImpl extends GenericDaoBase<HostJoinVO, Long> implements
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)
|| details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
hostResponse.setOsCategoryId(host.getOsCategoryUuid()); hostResponse.setOsCategoryId(host.getOsCategoryUuid());
hostResponse.setOsCategoryName(host.getOsCategoryName()); hostResponse.setOsCategoryName(host.getOsCategoryName());
hostResponse.setZoneName(host.getZoneName()); hostResponse.setZoneName(host.getZoneName());
hostResponse.setPodName(host.getPodName()); hostResponse.setPodName(host.getPodName());
if ( host.getClusterId() > 0) { if ( host.getClusterId() > 0) {
hostResponse.setClusterName(host.getClusterName()); hostResponse.setClusterName(host.getClusterName());
hostResponse.setClusterType(host.getClusterType().toString()); hostResponse.setClusterType(host.getClusterType().toString());
} }
} }
DecimalFormat decimalFormat = new DecimalFormat("#.##"); DecimalFormat decimalFormat = new DecimalFormat("#.##");

View File

@ -20,19 +20,17 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.api.query.vo.ProjectJoinVO;
import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.springframework.stereotype.Component;
import com.cloud.projects.Project; import com.cloud.projects.Project;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -45,9 +43,9 @@ public class ProjectJoinDaoImpl extends GenericDaoBase<ProjectJoinVO, Long> impl
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<ProjectJoinVO> prjSearch; private final SearchBuilder<ProjectJoinVO> prjSearch;
private SearchBuilder<ProjectJoinVO> prjIdSearch; private final SearchBuilder<ProjectJoinVO> prjIdSearch;
protected ProjectJoinDaoImpl() { protected ProjectJoinDaoImpl() {

View File

@ -20,18 +20,16 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.ResourceTagResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiResponseHelper;
import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.ResourceTagResponse;
import org.springframework.stereotype.Component;
import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -44,9 +42,9 @@ public class ResourceTagJoinDaoImpl extends GenericDaoBase<ResourceTagJoinVO, Lo
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<ResourceTagJoinVO> tagSearch; private final SearchBuilder<ResourceTagJoinVO> tagSearch;
private SearchBuilder<ResourceTagJoinVO> tagIdSearch; private final SearchBuilder<ResourceTagJoinVO> tagIdSearch;
protected ResourceTagJoinDaoImpl() { protected ResourceTagJoinDaoImpl() {

View File

@ -20,23 +20,21 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.SecurityGroupResponse;
import org.apache.cloudstack.api.response.SecurityGroupRuleResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiResponseHelper;
import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.SecurityGroupJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.SecurityGroupResponse;
import org.apache.cloudstack.api.response.SecurityGroupRuleResponse;
import org.springframework.stereotype.Component;
import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroup;
import com.cloud.network.security.SecurityRule.SecurityRuleType; import com.cloud.network.security.SecurityRule.SecurityRuleType;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -49,9 +47,9 @@ public class SecurityGroupJoinDaoImpl extends GenericDaoBase<SecurityGroupJoinVO
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<SecurityGroupJoinVO> sgSearch; private final SearchBuilder<SecurityGroupJoinVO> sgSearch;
private SearchBuilder<SecurityGroupJoinVO> sgIdSearch; private final SearchBuilder<SecurityGroupJoinVO> sgIdSearch;
protected SecurityGroupJoinDaoImpl() { protected SecurityGroupJoinDaoImpl() {

View File

@ -18,19 +18,19 @@ package com.cloud.api.query.dao;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.vo.StoragePoolJoinVO; import com.cloud.api.query.vo.StoragePoolJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.springframework.stereotype.Component;
import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePool;
import com.cloud.storage.StorageStats; import com.cloud.storage.StorageStats;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -44,9 +44,9 @@ public class StoragePoolJoinDaoImpl extends GenericDaoBase<StoragePoolJoinVO, Lo
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<StoragePoolJoinVO> spSearch; private final SearchBuilder<StoragePoolJoinVO> spSearch;
private SearchBuilder<StoragePoolJoinVO> spIdSearch; private final SearchBuilder<StoragePoolJoinVO> spIdSearch;
protected StoragePoolJoinDaoImpl() { protected StoragePoolJoinDaoImpl() {

View File

@ -24,23 +24,21 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
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.ApiConstants.VMDetails;
import org.apache.cloudstack.api.response.NicResponse; import org.apache.cloudstack.api.response.NicResponse;
import org.apache.cloudstack.api.response.SecurityGroupResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse;
import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
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 com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.uservm.UserVm; import com.cloud.uservm.UserVm;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -55,7 +53,7 @@ public class UserVmJoinDaoImpl extends GenericDaoBase<UserVmJoinVO, Long> implem
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<UserVmJoinVO> VmDetailSearch; private final SearchBuilder<UserVmJoinVO> VmDetailSearch;
protected UserVmJoinDaoImpl() { protected UserVmJoinDaoImpl() {
@ -68,6 +66,7 @@ public class UserVmJoinDaoImpl extends GenericDaoBase<UserVmJoinVO, Long> implem
} }
@Override
public UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet<VMDetails> details, Account caller) { public UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet<VMDetails> details, Account caller) {
UserVmResponse userVmResponse = new UserVmResponse(); UserVmResponse userVmResponse = new UserVmResponse();
@ -216,8 +215,9 @@ public class UserVmJoinDaoImpl extends GenericDaoBase<UserVmJoinVO, Long> implem
userVmResponse.setObjectName(objectName); userVmResponse.setObjectName(objectName);
return userVmResponse; return userVmResponse;
} }
@Override
public UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo) { public UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo) {
Long securityGroupId = uvo.getSecurityGroupId(); Long securityGroupId = uvo.getSecurityGroupId();
if (securityGroupId != null && securityGroupId.longValue() != 0) { if (securityGroupId != null && securityGroupId.longValue() != 0) {

View File

@ -20,26 +20,24 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.api.response.VolumeResponse;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiResponseHelper;
import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.VolumeJoinVO; import com.cloud.api.query.vo.VolumeJoinVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import org.apache.cloudstack.api.response.VolumeResponse;
import org.springframework.stereotype.Component;
import com.cloud.offering.ServiceOffering; import com.cloud.offering.ServiceOffering;
import com.cloud.storage.Storage; import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.Volume;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.UserContext; import com.cloud.user.UserContext;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -53,9 +51,9 @@ public class VolumeJoinDaoImpl extends GenericDaoBase<VolumeJoinVO, Long> implem
@Inject @Inject
private ConfigurationDao _configDao; private ConfigurationDao _configDao;
private SearchBuilder<VolumeJoinVO> volSearch; private final SearchBuilder<VolumeJoinVO> volSearch;
private SearchBuilder<VolumeJoinVO> volIdSearch; private final SearchBuilder<VolumeJoinVO> volIdSearch;
protected VolumeJoinDaoImpl() { protected VolumeJoinDaoImpl() {
@ -176,12 +174,12 @@ public class VolumeJoinDaoImpl extends GenericDaoBase<VolumeJoinVO, Long> implem
volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); volResponse.setDestroyed(volume.getState() == Volume.State.Destroy);
boolean isExtractable = true; boolean isExtractable = true;
if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont
// have any // have any
// template // template
// dependence. // dependence.
if (volume.getTemplateId() > 0) { // For ISO based volumes template if (volume.getTemplateId() > 0) { // For ISO based volumes template
// = null and we allow extraction // = null and we allow extraction
// of all ISO based volumes // of all ISO based volumes
isExtractable = volume.isExtractable() && volume.getTemplateType() != Storage.TemplateType.SYSTEM; isExtractable = volume.isExtractable() && volume.getTemplateType() != Storage.TemplateType.SYSTEM;
} }
} }

View File

@ -36,7 +36,6 @@ import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmManager;
import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
@ -45,8 +44,8 @@ import com.cloud.vm.dao.UserVmDao;
@Component @Component
@Local(value={AsyncJobExecutorContext.class}) @Local(value={AsyncJobExecutorContext.class})
public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext { public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
private String _name; private String _name;
@Inject private AgentManager _agentMgr; @Inject private AgentManager _agentMgr;
@Inject private NetworkManager _networkMgr; @Inject private NetworkManager _networkMgr;
@Inject private UserVmManager _vmMgr; @Inject private UserVmManager _vmMgr;
@ -62,98 +61,98 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
@Inject private AsyncJobDao _jobDao; @Inject private AsyncJobDao _jobDao;
@Inject private UserDao _userDao; @Inject private UserDao _userDao;
@Inject private VirtualMachineManager _itMgr; @Inject private VirtualMachineManager _itMgr;
@Inject private ManagementServer _managementServer;
@Override
public ManagementServer getManagementServer() {
return _managementServer;
}
@Override @Inject private ManagementServer _managementServer;
public AgentManager getAgentMgr() {
return _agentMgr; @Override
} public ManagementServer getManagementServer() {
return _managementServer;
@Override }
public NetworkManager getNetworkMgr() {
return _networkMgr; @Override
} public AgentManager getAgentMgr() {
return _agentMgr;
@Override }
public UserVmManager getVmMgr() {
return _vmMgr; @Override
} public NetworkManager getNetworkMgr() {
return _networkMgr;
@Override }
public StorageManager getStorageMgr() {
return _storageMgr; @Override
} public UserVmManager getVmMgr() {
return _vmMgr;
/**server/src/com/cloud/async/AsyncJobExecutorContext.java }
@Override
public StorageManager getStorageMgr() {
return _storageMgr;
}
/**server/src/com/cloud/async/AsyncJobExecutorContext.java
* @return the _snapMgr * @return the _snapMgr
*/ */
@Override @Override
public SnapshotManager getSnapshotMgr() { public SnapshotManager getSnapshotMgr() {
return _snapMgr; return _snapMgr;
} }
@Override @Override
public AccountManager getAccountMgr() { public AccountManager getAccountMgr() {
return _accountMgr; return _accountMgr;
} }
@Override
public EventDao getEventDao() {
return _eventDao;
}
@Override
public UserVmDao getVmDao() {
return _vmDao;
}
@Override
public AccountDao getAccountDao() {
return _accountDao;
}
@Override
public VolumeDao getVolumeDao() {
return _volumeDao;
}
@Override @Override
public EventDao getEventDao() {
return _eventDao;
}
@Override
public UserVmDao getVmDao() {
return _vmDao;
}
@Override
public AccountDao getAccountDao() {
return _accountDao;
}
@Override
public VolumeDao getVolumeDao() {
return _volumeDao;
}
@Override
public DomainRouterDao getRouterDao() { public DomainRouterDao getRouterDao() {
return _routerDao; return _routerDao;
} }
@Override @Override
public IPAddressDao getIpAddressDao() { public IPAddressDao getIpAddressDao() {
return _ipAddressDao; return _ipAddressDao;
} }
@Override @Override
public AsyncJobDao getJobDao() { public AsyncJobDao getJobDao() {
return _jobDao; return _jobDao;
} }
@Override @Override
public UserDao getUserDao() { public UserDao getUserDao() {
return _userDao; return _userDao;
} }
@Override @Override
public VirtualMachineManager getItMgr() { public VirtualMachineManager getItMgr() {
return _itMgr; return _itMgr;
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
@ -163,9 +162,9 @@ public class AsyncJobExecutorContextImpl implements AsyncJobExecutorContext {
public boolean stop() { public boolean stop() {
return true; return true;
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -31,7 +31,6 @@ import org.springframework.stereotype.Component;
import com.cloud.async.dao.SyncQueueDao; import com.cloud.async.dao.SyncQueueDao;
import com.cloud.async.dao.SyncQueueItemDao; import com.cloud.async.dao.SyncQueueItemDao;
import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@ -40,9 +39,9 @@ import com.cloud.utils.exception.CloudRuntimeException;
@Local(value={SyncQueueManager.class}) @Local(value={SyncQueueManager.class})
public class SyncQueueManagerImpl implements SyncQueueManager { public class SyncQueueManagerImpl implements SyncQueueManager {
public static final Logger s_logger = Logger.getLogger(SyncQueueManagerImpl.class.getName()); public static final Logger s_logger = Logger.getLogger(SyncQueueManagerImpl.class.getName());
private String _name; private String _name;
@Inject private SyncQueueDao _syncQueueDao; @Inject private SyncQueueDao _syncQueueDao;
@Inject private SyncQueueItemDao _syncQueueItemDao; @Inject private SyncQueueItemDao _syncQueueItemDao;
@ -50,203 +49,203 @@ public class SyncQueueManagerImpl implements SyncQueueManager {
@DB @DB
public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId, long queueSizeLimit) { public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId, long queueSizeLimit) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
txn.start(); txn.start();
_syncQueueDao.ensureQueue(syncObjType, syncObjId);
SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId);
if(queueVO == null)
throw new CloudRuntimeException("Unable to queue item into DB, DB is full?");
queueVO.setQueueSizeLimit(queueSizeLimit); _syncQueueDao.ensureQueue(syncObjType, syncObjId);
_syncQueueDao.update(queueVO.getId(), queueVO); SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId);
if(queueVO == null)
Date dt = DateUtil.currentGMTTime(); throw new CloudRuntimeException("Unable to queue item into DB, DB is full?");
SyncQueueItemVO item = new SyncQueueItemVO();
item.setQueueId(queueVO.getId()); queueVO.setQueueSizeLimit(queueSizeLimit);
item.setContentType(itemType); _syncQueueDao.update(queueVO.getId(), queueVO);
item.setContentId(itemId);
item.setCreated(dt); Date dt = DateUtil.currentGMTTime();
SyncQueueItemVO item = new SyncQueueItemVO();
_syncQueueItemDao.persist(item); item.setQueueId(queueVO.getId());
txn.commit(); item.setContentType(itemType);
item.setContentId(itemId);
return queueVO; item.setCreated(dt);
} catch(Exception e) {
s_logger.error("Unexpected exception: ", e); _syncQueueItemDao.persist(item);
txn.rollback(); txn.commit();
}
return null; return queueVO;
} catch(Exception e) {
s_logger.error("Unexpected exception: ", e);
txn.rollback();
}
return null;
} }
@Override @Override
@DB @DB
public SyncQueueItemVO dequeueFromOne(long queueId, Long msid) { public SyncQueueItemVO dequeueFromOne(long queueId, Long msid) {
Transaction txt = Transaction.currentTxn(); Transaction txt = Transaction.currentTxn();
try { try {
txt.start(); txt.start();
SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true); SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true);
if(queueVO == null) { if(queueVO == null) {
s_logger.error("Sync queue(id: " + queueId + ") does not exist"); s_logger.error("Sync queue(id: " + queueId + ") does not exist");
txt.commit(); txt.commit();
return null; return null;
} }
if(queueReadyToProcess(queueVO)) { if(queueReadyToProcess(queueVO)) {
SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId()); SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId());
if(itemVO != null) { if(itemVO != null) {
Long processNumber = queueVO.getLastProcessNumber(); Long processNumber = queueVO.getLastProcessNumber();
if(processNumber == null) if(processNumber == null)
processNumber = new Long(1); processNumber = new Long(1);
else else
processNumber = processNumber + 1; processNumber = processNumber + 1;
Date dt = DateUtil.currentGMTTime(); Date dt = DateUtil.currentGMTTime();
queueVO.setLastProcessNumber(processNumber); queueVO.setLastProcessNumber(processNumber);
queueVO.setLastUpdated(dt); queueVO.setLastUpdated(dt);
queueVO.setQueueSize(queueVO.getQueueSize() + 1); queueVO.setQueueSize(queueVO.getQueueSize() + 1);
_syncQueueDao.update(queueVO.getId(), queueVO); _syncQueueDao.update(queueVO.getId(), queueVO);
itemVO.setLastProcessMsid(msid); itemVO.setLastProcessMsid(msid);
itemVO.setLastProcessNumber(processNumber); itemVO.setLastProcessNumber(processNumber);
itemVO.setLastProcessTime(dt); itemVO.setLastProcessTime(dt);
_syncQueueItemDao.update(itemVO.getId(), itemVO); _syncQueueItemDao.update(itemVO.getId(), itemVO);
txt.commit(); txt.commit();
return itemVO; return itemVO;
} else { } else {
if(s_logger.isDebugEnabled()) if(s_logger.isDebugEnabled())
s_logger.debug("Sync queue (" + queueId + ") is currently empty"); s_logger.debug("Sync queue (" + queueId + ") is currently empty");
} }
} else { } else {
if(s_logger.isDebugEnabled()) if(s_logger.isDebugEnabled())
s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")"); s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")");
} }
txt.commit(); txt.commit();
} catch(Exception e) { } catch(Exception e) {
s_logger.error("Unexpected exception: ", e); s_logger.error("Unexpected exception: ", e);
txt.rollback(); txt.rollback();
} }
return null; return null;
} }
@Override @Override
@DB @DB
public List<SyncQueueItemVO> dequeueFromAny(Long msid, int maxItems) { public List<SyncQueueItemVO> dequeueFromAny(Long msid, int maxItems) {
List<SyncQueueItemVO> resultList = new ArrayList<SyncQueueItemVO>(); List<SyncQueueItemVO> resultList = new ArrayList<SyncQueueItemVO>();
Transaction txt = Transaction.currentTxn(); Transaction txt = Transaction.currentTxn();
try { try {
txt.start(); txt.start();
List<SyncQueueItemVO> l = _syncQueueItemDao.getNextQueueItems(maxItems); List<SyncQueueItemVO> l = _syncQueueItemDao.getNextQueueItems(maxItems);
if(l != null && l.size() > 0) { if(l != null && l.size() > 0) {
for(SyncQueueItemVO item : l) { for(SyncQueueItemVO item : l) {
SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true); SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true);
SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true); SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true);
if(queueReadyToProcess(queueVO) && itemVO.getLastProcessNumber() == null) { if(queueReadyToProcess(queueVO) && itemVO.getLastProcessNumber() == null) {
Long processNumber = queueVO.getLastProcessNumber(); Long processNumber = queueVO.getLastProcessNumber();
if(processNumber == null) if(processNumber == null)
processNumber = new Long(1); processNumber = new Long(1);
else else
processNumber = processNumber + 1; processNumber = processNumber + 1;
Date dt = DateUtil.currentGMTTime(); Date dt = DateUtil.currentGMTTime();
queueVO.setLastProcessNumber(processNumber); queueVO.setLastProcessNumber(processNumber);
queueVO.setLastUpdated(dt); queueVO.setLastUpdated(dt);
queueVO.setQueueSize(queueVO.getQueueSize() + 1); queueVO.setQueueSize(queueVO.getQueueSize() + 1);
_syncQueueDao.update(queueVO.getId(), queueVO); _syncQueueDao.update(queueVO.getId(), queueVO);
itemVO.setLastProcessMsid(msid); itemVO.setLastProcessMsid(msid);
itemVO.setLastProcessNumber(processNumber); itemVO.setLastProcessNumber(processNumber);
itemVO.setLastProcessTime(dt); itemVO.setLastProcessTime(dt);
_syncQueueItemDao.update(item.getId(), itemVO); _syncQueueItemDao.update(item.getId(), itemVO);
resultList.add(item); resultList.add(item);
} }
} }
} }
txt.commit(); txt.commit();
return resultList; return resultList;
} catch(Exception e) { } catch(Exception e) {
s_logger.error("Unexpected exception: ", e); s_logger.error("Unexpected exception: ", e);
txt.rollback(); txt.rollback();
} }
return null; return null;
} }
@Override @Override
@DB @DB
public void purgeItem(long queueItemId) { public void purgeItem(long queueItemId) {
Transaction txt = Transaction.currentTxn(); Transaction txt = Transaction.currentTxn();
try { try {
txt.start(); txt.start();
SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId); SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
if(itemVO != null) { if(itemVO != null) {
SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true); SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
_syncQueueItemDao.expunge(itemVO.getId()); _syncQueueItemDao.expunge(itemVO.getId());
//if item is active, reset queue information //if item is active, reset queue information
if (itemVO.getLastProcessMsid() != null) { if (itemVO.getLastProcessMsid() != null) {
queueVO.setLastUpdated(DateUtil.currentGMTTime()); queueVO.setLastUpdated(DateUtil.currentGMTTime());
//decrement the count //decrement the count
assert (queueVO.getQueueSize() > 0) : "Count reduce happens when it's already <= 0!"; assert (queueVO.getQueueSize() > 0) : "Count reduce happens when it's already <= 0!";
queueVO.setQueueSize(queueVO.getQueueSize() - 1); queueVO.setQueueSize(queueVO.getQueueSize() - 1);
_syncQueueDao.update(queueVO.getId(), queueVO); _syncQueueDao.update(queueVO.getId(), queueVO);
} }
} }
txt.commit(); txt.commit();
} catch(Exception e) { } catch(Exception e) {
s_logger.error("Unexpected exception: ", e); s_logger.error("Unexpected exception: ", e);
txt.rollback(); txt.rollback();
} }
} }
@Override @Override
@DB @DB
public void returnItem(long queueItemId) { public void returnItem(long queueItemId) {
Transaction txt = Transaction.currentTxn(); Transaction txt = Transaction.currentTxn();
try { try {
txt.start(); txt.start();
SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId); SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
if(itemVO != null) { if(itemVO != null) {
SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true); SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
itemVO.setLastProcessMsid(null); itemVO.setLastProcessMsid(null);
itemVO.setLastProcessNumber(null); itemVO.setLastProcessNumber(null);
itemVO.setLastProcessTime(null); itemVO.setLastProcessTime(null);
_syncQueueItemDao.update(queueItemId, itemVO); _syncQueueItemDao.update(queueItemId, itemVO);
queueVO.setLastUpdated(DateUtil.currentGMTTime()); queueVO.setLastUpdated(DateUtil.currentGMTTime());
_syncQueueDao.update(queueVO.getId(), queueVO); _syncQueueDao.update(queueVO.getId(), queueVO);
} }
txt.commit(); txt.commit();
} catch(Exception e) { } catch(Exception e) {
s_logger.error("Unexpected exception: ", e); s_logger.error("Unexpected exception: ", e);
txt.rollback(); txt.rollback();
} }
} }
@Override @Override
public List<SyncQueueItemVO> getActiveQueueItems(Long msid, boolean exclusive) { public List<SyncQueueItemVO> getActiveQueueItems(Long msid, boolean exclusive) {
return _syncQueueItemDao.getActiveQueueItems(msid, exclusive); return _syncQueueItemDao.getActiveQueueItems(msid, exclusive);
} }
@Override @Override
public List<SyncQueueItemVO> getBlockedQueueItems(long thresholdMs, boolean exclusive) { public List<SyncQueueItemVO> getBlockedQueueItems(long thresholdMs, boolean exclusive) {
return _syncQueueItemDao.getBlockedQueueItems(thresholdMs, exclusive); return _syncQueueItemDao.getBlockedQueueItems(thresholdMs, exclusive);
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
@ -256,16 +255,16 @@ public class SyncQueueManagerImpl implements SyncQueueManager {
public boolean stop() { public boolean stop() {
return true; return true;
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;
} }
private boolean queueReadyToProcess(SyncQueueVO queueVO) { private boolean queueReadyToProcess(SyncQueueVO queueVO) {
return queueVO.getQueueSize() < queueVO.getQueueSizeLimit(); return queueVO.getQueueSize() < queueVO.getQueueSizeLimit();
} }
@Override @Override
public void purgeAsyncJobQueueItemId(long asyncJobId) { public void purgeAsyncJobQueueItemId(long asyncJobId) {
Long itemId = _syncQueueItemDao.getQueueItemIdByContentIdAndType(asyncJobId, SyncQueueItem.AsyncJobContentType); Long itemId = _syncQueueItemDao.getQueueItemIdByContentIdAndType(asyncJobId, SyncQueueItem.AsyncJobContentType);

View File

@ -35,10 +35,7 @@ import com.cloud.capacity.CapacityVO;
import com.cloud.storage.Storage; import com.cloud.storage.Storage;
import com.cloud.storage.StoragePoolVO; import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolDaoImpl;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;
@ -60,116 +57,116 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART1 = "SELECT DISTINCT capacity.cluster_id FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster` cluster on (cluster.id = capacity.cluster_id AND cluster.removed is NULL) WHERE "; private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART1 = "SELECT DISTINCT capacity.cluster_id FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster` cluster on (cluster.id = capacity.cluster_id AND cluster.removed is NULL) WHERE ";
private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART2 = " AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ? " + private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART2 = " AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ? " +
"AND cluster_id IN (SELECT distinct cluster_id FROM `cloud`.`op_host_capacity` WHERE "; "AND cluster_id IN (SELECT distinct cluster_id FROM `cloud`.`op_host_capacity` WHERE ";
private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART3 = " AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ?) "; private static final String LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART3 = " AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ?) ";
private final SearchBuilder<CapacityVO> _hostIdTypeSearch; private final SearchBuilder<CapacityVO> _hostIdTypeSearch;
private final SearchBuilder<CapacityVO> _hostOrPoolIdSearch; private final SearchBuilder<CapacityVO> _hostOrPoolIdSearch;
protected GenericSearchBuilder<CapacityVO, SummedCapacity> SummedCapacitySearch; protected GenericSearchBuilder<CapacityVO, SummedCapacity> SummedCapacitySearch;
private SearchBuilder<CapacityVO> _allFieldsSearch; private final SearchBuilder<CapacityVO> _allFieldsSearch;
@Inject protected StoragePoolDao _storagePoolDao; @Inject protected StoragePoolDao _storagePoolDao;
private static final String LIST_HOSTS_IN_CLUSTER_WITH_ENOUGH_CAPACITY = "SELECT a.host_id FROM (host JOIN op_host_capacity a ON host.id = a.host_id AND host.cluster_id = ? AND host.type = ? " + private static final String LIST_HOSTS_IN_CLUSTER_WITH_ENOUGH_CAPACITY = "SELECT a.host_id FROM (host JOIN op_host_capacity a ON host.id = a.host_id AND host.cluster_id = ? AND host.type = ? " +
"AND (a.total_capacity * ? - a.used_capacity) >= ? and a.capacity_type = 1) " + "AND (a.total_capacity * ? - a.used_capacity) >= ? and a.capacity_type = 1) " +
"JOIN op_host_capacity b ON a.host_id = b.host_id AND b.total_capacity - b.used_capacity >= ? AND b.capacity_type = 0"; "JOIN op_host_capacity b ON a.host_id = b.host_id AND b.total_capacity - b.used_capacity >= ? AND b.capacity_type = 0";
private static final String ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART1 = "SELECT cluster_id, SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) FROM `cloud`.`op_host_capacity` WHERE " ; private static final String ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART1 = "SELECT cluster_id, SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) FROM `cloud`.`op_host_capacity` WHERE " ;
private static final String ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART2 = " AND capacity_type = ? GROUP BY cluster_id ORDER BY SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) ASC"; private static final String ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART2 = " AND capacity_type = ? GROUP BY cluster_id ORDER BY SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) ASC";
private static final String LIST_PODSINZONE_BY_HOST_CAPACITIES = "SELECT DISTINCT capacity.pod_id FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host_pod_ref` pod " + private static final String LIST_PODSINZONE_BY_HOST_CAPACITIES = "SELECT DISTINCT capacity.pod_id FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host_pod_ref` pod " +
" ON (pod.id = capacity.pod_id AND pod.removed is NULL) WHERE " + " ON (pod.id = capacity.pod_id AND pod.removed is NULL) WHERE " +
" capacity.data_center_id = ? AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ? " + " capacity.data_center_id = ? AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ? " +
" AND pod_id IN (SELECT distinct pod_id FROM `cloud`.`op_host_capacity` WHERE " + " AND pod_id IN (SELECT distinct pod_id FROM `cloud`.`op_host_capacity` WHERE " +
" capacity.data_center_id = ? AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ?) "; " capacity.data_center_id = ? AND capacity_type = ? AND ((total_capacity * ?) - used_capacity + reserved_capacity) >= ?) ";
private static final String ORDER_PODS_BY_AGGREGATE_CAPACITY = "SELECT pod_id, SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) FROM `cloud`.`op_host_capacity` WHERE data_center_id = ? " + private static final String ORDER_PODS_BY_AGGREGATE_CAPACITY = "SELECT pod_id, SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) FROM `cloud`.`op_host_capacity` WHERE data_center_id = ? " +
" AND capacity_type = ? GROUP BY pod_id ORDER BY SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) ASC"; " AND capacity_type = ? GROUP BY pod_id ORDER BY SUM(used_capacity+reserved_capacity)/SUM(total_capacity * ?) ASC";
private static final String LIST_CAPACITY_BY_RESOURCE_STATE = "SELECT capacity.data_center_id, sum(capacity.used_capacity), sum(capacity.reserved_quantity), sum(capacity.total_capacity), capacity_capacity_type "+ private static final String LIST_CAPACITY_BY_RESOURCE_STATE = "SELECT capacity.data_center_id, sum(capacity.used_capacity), sum(capacity.reserved_quantity), sum(capacity.total_capacity), capacity_capacity_type "+
"FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`data_center` dc ON (dc.id = capacity.data_center_id AND dc.removed is NULL)"+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`data_center` dc ON (dc.id = capacity.data_center_id AND dc.removed is NULL)"+
"FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host_pod_ref` pod ON (pod.id = capacity.pod_id AND pod.removed is NULL)"+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host_pod_ref` pod ON (pod.id = capacity.pod_id AND pod.removed is NULL)"+
"FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster` cluster ON (cluster.id = capacity.cluster_id AND cluster.removed is NULL)"+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`cluster` cluster ON (cluster.id = capacity.cluster_id AND cluster.removed is NULL)"+
"FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host` host ON (host.id = capacity.host_id AND host.removed is NULL)"+ "FROM `cloud`.`op_host_capacity` capacity INNER JOIN `cloud`.`host` host ON (host.id = capacity.host_id AND host.removed is NULL)"+
"WHERE dc.allocation_state = ? AND pod.allocation_state = ? AND cluster.allocation_state = ? AND host.resource_state = ? AND capacity_type not in (3,4) "; "WHERE dc.allocation_state = ? AND pod.allocation_state = ? AND cluster.allocation_state = ? AND host.resource_state = ? AND capacity_type not in (3,4) ";
private static final String LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " + private static final String LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " +
"((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+ "((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+
" capacity.capacity_type, capacity.data_center_id "+ " capacity.capacity_type, capacity.data_center_id "+
"FROM `cloud`.`op_host_capacity` capacity "+ "FROM `cloud`.`op_host_capacity` capacity "+
"WHERE total_capacity > 0 AND data_center_id is not null AND capacity_state='Enabled'"; "WHERE total_capacity > 0 AND data_center_id is not null AND capacity_state='Enabled'";
private static final String LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART2 = " GROUP BY data_center_id, capacity_type order by percent desc limit "; private static final String LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART2 = " GROUP BY data_center_id, capacity_type order by percent desc limit ";
private static final String LIST_CAPACITY_GROUP_BY_POD_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " + private static final String LIST_CAPACITY_GROUP_BY_POD_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " +
"((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+ "((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+
" capacity.capacity_type, capacity.data_center_id, pod_id "+ " capacity.capacity_type, capacity.data_center_id, pod_id "+
"FROM `cloud`.`op_host_capacity` capacity "+ "FROM `cloud`.`op_host_capacity` capacity "+
"WHERE total_capacity > 0 AND pod_id is not null AND capacity_state='Enabled'"; "WHERE total_capacity > 0 AND pod_id is not null AND capacity_state='Enabled'";
private static final String LIST_CAPACITY_GROUP_BY_POD_TYPE_PART2 = " GROUP BY pod_id, capacity_type order by percent desc limit "; private static final String LIST_CAPACITY_GROUP_BY_POD_TYPE_PART2 = " GROUP BY pod_id, capacity_type order by percent desc limit ";
private static final String LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " + private static final String LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART1 = "SELECT (sum(capacity.used_capacity) + sum(capacity.reserved_capacity)), (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end), " +
"((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+ "((sum(capacity.used_capacity) + sum(capacity.reserved_capacity)) / (case capacity_type when 1 then (sum(total_capacity) * (select value from `cloud`.`configuration` where name like 'cpu.overprovisioning.factor')) else sum(total_capacity) end)) percent,"+
"capacity.capacity_type, capacity.data_center_id, pod_id, cluster_id "+ "capacity.capacity_type, capacity.data_center_id, pod_id, cluster_id "+
"FROM `cloud`.`op_host_capacity` capacity "+ "FROM `cloud`.`op_host_capacity` capacity "+
"WHERE total_capacity > 0 AND cluster_id is not null AND capacity_state='Enabled'"; "WHERE total_capacity > 0 AND cluster_id is not null AND capacity_state='Enabled'";
private static final String LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART2 = " GROUP BY cluster_id, capacity_type order by percent desc limit "; private static final String LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART2 = " GROUP BY cluster_id, capacity_type order by percent desc limit ";
private static final String UPDATE_CAPACITY_STATE = "UPDATE `cloud`.`op_host_capacity` SET capacity_state = ? WHERE "; private static final String UPDATE_CAPACITY_STATE = "UPDATE `cloud`.`op_host_capacity` SET capacity_state = ? WHERE ";
private static final String LIST_CLUSTERS_CROSSING_THRESHOLD = "SELECT cluster_id " + private static final String LIST_CLUSTERS_CROSSING_THRESHOLD = "SELECT cluster_id " +
"FROM (SELECT cluster_id, ( (sum(capacity.used_capacity) + sum(capacity.reserved_capacity) + ?)/sum(total_capacity) ) ratio "+ "FROM (SELECT cluster_id, ( (sum(capacity.used_capacity) + sum(capacity.reserved_capacity) + ?)/sum(total_capacity) ) ratio "+
"FROM `cloud`.`op_host_capacity` capacity "+ "FROM `cloud`.`op_host_capacity` capacity "+
"WHERE capacity.data_center_id = ? AND capacity.capacity_type = ? AND capacity.total_capacity > 0 "+ "WHERE capacity.data_center_id = ? AND capacity.capacity_type = ? AND capacity.total_capacity > 0 "+
"GROUP BY cluster_id) tmp " + "GROUP BY cluster_id) tmp " +
"WHERE tmp.ratio > ? "; "WHERE tmp.ratio > ? ";
public CapacityDaoImpl() { public CapacityDaoImpl() {
_hostIdTypeSearch = createSearchBuilder(); _hostIdTypeSearch = createSearchBuilder();
_hostIdTypeSearch.and("hostId", _hostIdTypeSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ); _hostIdTypeSearch.and("hostId", _hostIdTypeSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ);
_hostIdTypeSearch.and("type", _hostIdTypeSearch.entity().getCapacityType(), SearchCriteria.Op.EQ); _hostIdTypeSearch.and("type", _hostIdTypeSearch.entity().getCapacityType(), SearchCriteria.Op.EQ);
_hostIdTypeSearch.done(); _hostIdTypeSearch.done();
_hostOrPoolIdSearch = createSearchBuilder(); _hostOrPoolIdSearch = createSearchBuilder();
_hostOrPoolIdSearch.and("hostId", _hostOrPoolIdSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ); _hostOrPoolIdSearch.and("hostId", _hostOrPoolIdSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ);
_hostOrPoolIdSearch.done(); _hostOrPoolIdSearch.done();
_allFieldsSearch = createSearchBuilder(); _allFieldsSearch = createSearchBuilder();
_allFieldsSearch.and("id", _allFieldsSearch.entity().getId(), SearchCriteria.Op.EQ); _allFieldsSearch.and("id", _allFieldsSearch.entity().getId(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("hostId", _allFieldsSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ); _allFieldsSearch.and("hostId", _allFieldsSearch.entity().getHostOrPoolId(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("zoneId", _allFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); _allFieldsSearch.and("zoneId", _allFieldsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("podId", _allFieldsSearch.entity().getPodId(), SearchCriteria.Op.EQ); _allFieldsSearch.and("podId", _allFieldsSearch.entity().getPodId(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("clusterId", _allFieldsSearch.entity().getClusterId(), SearchCriteria.Op.EQ); _allFieldsSearch.and("clusterId", _allFieldsSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("capacityType", _allFieldsSearch.entity().getCapacityType(), SearchCriteria.Op.EQ); _allFieldsSearch.and("capacityType", _allFieldsSearch.entity().getCapacityType(), SearchCriteria.Op.EQ);
_allFieldsSearch.and("capacityState", _allFieldsSearch.entity().getCapacityState(), SearchCriteria.Op.EQ); _allFieldsSearch.and("capacityState", _allFieldsSearch.entity().getCapacityState(), SearchCriteria.Op.EQ);
_allFieldsSearch.done(); _allFieldsSearch.done();
} }
@Override @Override
public List<Long> listClustersCrossingThreshold(short capacityType, Long zoneId, Float disableThreshold, long compute_requested, Float overProvFactor){ public List<Long> listClustersCrossingThreshold(short capacityType, Long zoneId, Float disableThreshold, long compute_requested, Float overProvFactor){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
List<Long> result = new ArrayList<Long>(); List<Long> result = new ArrayList<Long>();
StringBuilder sql = new StringBuilder(LIST_CLUSTERS_CROSSING_THRESHOLD); StringBuilder sql = new StringBuilder(LIST_CLUSTERS_CROSSING_THRESHOLD);
try { try {
pstmt = txn.prepareAutoCloseStatement(sql.toString()); pstmt = txn.prepareAutoCloseStatement(sql.toString());
pstmt.setLong(1, compute_requested); pstmt.setLong(1, compute_requested);
pstmt.setLong(2, zoneId); pstmt.setLong(2, zoneId);
pstmt.setShort(3, capacityType); pstmt.setShort(3, capacityType);
pstmt.setFloat(4, disableThreshold*overProvFactor); pstmt.setFloat(4, disableThreshold*overProvFactor);
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
result.add(rs.getLong(1)); result.add(rs.getLong(1));
} }
return result; return result;
} catch (SQLException e) { } catch (SQLException e) {
throw new CloudRuntimeException("DB Exception on: " + sql, e); throw new CloudRuntimeException("DB Exception on: " + sql, e);
} catch (Throwable e) { } catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + sql, e); throw new CloudRuntimeException("Caught: " + sql, e);
} }
} }
/*public static String preparePlaceHolders(int length) { /*public static String preparePlaceHolders(int length) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -188,17 +185,17 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
} }
}*/ }*/
@Override @Override
public List<SummedCapacity> findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, String resource_state){ public List<SummedCapacity> findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId, String resource_state){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
List<SummedCapacity> result = new ArrayList<SummedCapacity>(); List<SummedCapacity> result = new ArrayList<SummedCapacity>();
StringBuilder sql = new StringBuilder(LIST_CAPACITY_BY_RESOURCE_STATE); StringBuilder sql = new StringBuilder(LIST_CAPACITY_BY_RESOURCE_STATE);
List<Long> resourceIdList = new ArrayList<Long>(); List<Long> resourceIdList = new ArrayList<Long>();
if (zoneId != null){ if (zoneId != null){
sql.append(" AND capacity.data_center_id = ?"); sql.append(" AND capacity.data_center_id = ?");
resourceIdList.add(zoneId); resourceIdList.add(zoneId);
@ -237,29 +234,29 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
throw new CloudRuntimeException("Caught: " + sql, e); throw new CloudRuntimeException("Caught: " + sql, e);
} }
} }
@Override @Override
public List<SummedCapacity> listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit){ public List<SummedCapacity> listCapacitiesGroupedByLevelAndType(Integer capacityType, Long zoneId, Long podId, Long clusterId, int level, Long limit){
StringBuilder finalQuery = new StringBuilder(); StringBuilder finalQuery = new StringBuilder();
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
List<SummedCapacity> result = new ArrayList<SummedCapacity>(); List<SummedCapacity> result = new ArrayList<SummedCapacity>();
switch(level){ switch(level){
case 1: // List all the capacities grouped by zone, capacity Type case 1: // List all the capacities grouped by zone, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART1); finalQuery.append(LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART1);
break; break;
case 2: // List all the capacities grouped by pod, capacity Type case 2: // List all the capacities grouped by pod, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_POD_TYPE_PART1); finalQuery.append(LIST_CAPACITY_GROUP_BY_POD_TYPE_PART1);
break; break;
case 3: // List all the capacities grouped by cluster, capacity Type case 3: // List all the capacities grouped by cluster, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART1); finalQuery.append(LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART1);
break; break;
} }
if (zoneId != null){ if (zoneId != null){
finalQuery.append(" AND data_center_id="+zoneId); finalQuery.append(" AND data_center_id="+zoneId);
} }
@ -272,32 +269,32 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
if (capacityType != null){ if (capacityType != null){
finalQuery.append(" AND capacity_type="+capacityType); finalQuery.append(" AND capacity_type="+capacityType);
} }
switch(level){ switch(level){
case 1: // List all the capacities grouped by zone, capacity Type case 1: // List all the capacities grouped by zone, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART2); finalQuery.append(LIST_CAPACITY_GROUP_BY_ZONE_TYPE_PART2);
break; break;
case 2: // List all the capacities grouped by pod, capacity Type case 2: // List all the capacities grouped by pod, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_POD_TYPE_PART2); finalQuery.append(LIST_CAPACITY_GROUP_BY_POD_TYPE_PART2);
break; break;
case 3: // List all the capacities grouped by cluster, capacity Type case 3: // List all the capacities grouped by cluster, capacity Type
finalQuery.append(LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART2); finalQuery.append(LIST_CAPACITY_GROUP_BY_CLUSTER_TYPE_PART2);
break; break;
} }
finalQuery.append(limit.toString()); finalQuery.append(limit.toString());
try { try {
pstmt = txn.prepareAutoCloseStatement(finalQuery.toString()); pstmt = txn.prepareAutoCloseStatement(finalQuery.toString());
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
SummedCapacity summedCapacity = new SummedCapacity( rs.getLong(1), rs.getLong(2), rs.getFloat(3), SummedCapacity summedCapacity = new SummedCapacity( rs.getLong(1), rs.getLong(2), rs.getFloat(3),
(short)rs.getLong(4), rs.getLong(5), (short)rs.getLong(4), rs.getLong(5),
level != 1 ? rs.getLong(6): null, level != 1 ? rs.getLong(6): null,
level == 3 ? rs.getLong(7): null); level == 3 ? rs.getLong(7): null);
result.add(summedCapacity); result.add(summedCapacity);
} }
return result; return result;
@ -306,61 +303,61 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
} catch (Throwable e) { } catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + finalQuery, e); throw new CloudRuntimeException("Caught: " + finalQuery, e);
} }
} }
@Override @Override
public List<SummedCapacity> findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId){ public List<SummedCapacity> findCapacityBy(Integer capacityType, Long zoneId, Long podId, Long clusterId){
SummedCapacitySearch = createSearchBuilder(SummedCapacity.class); SummedCapacitySearch = createSearchBuilder(SummedCapacity.class);
SummedCapacitySearch.select("dcId", Func.NATIVE, SummedCapacitySearch.entity().getDataCenterId()); SummedCapacitySearch.select("dcId", Func.NATIVE, SummedCapacitySearch.entity().getDataCenterId());
SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity()); SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity());
SummedCapacitySearch.select("sumReserved", Func.SUM, SummedCapacitySearch.entity().getReservedCapacity()); SummedCapacitySearch.select("sumReserved", Func.SUM, SummedCapacitySearch.entity().getReservedCapacity());
SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity()); SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity());
SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType());
if (zoneId==null && podId==null && clusterId==null){ // List all the capacities grouped by zone, capacity Type if (zoneId==null && podId==null && clusterId==null){ // List all the capacities grouped by zone, capacity Type
SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getDataCenterId(), SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getDataCenterId(), SummedCapacitySearch.entity().getCapacityType());
}else { }else {
SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getCapacityType());
} }
if (zoneId != null){ if (zoneId != null){
SummedCapacitySearch.and("dcId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ); SummedCapacitySearch.and("dcId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ);
} }
if (podId != null){ if (podId != null){
SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ); SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ);
} }
if (clusterId != null){ if (clusterId != null){
SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ); SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ);
} }
if (capacityType != null){ if (capacityType != null){
SummedCapacitySearch.and("capacityType", SummedCapacitySearch.entity().getCapacityType(), Op.EQ); SummedCapacitySearch.and("capacityType", SummedCapacitySearch.entity().getCapacityType(), Op.EQ);
} }
SummedCapacitySearch.done(); SummedCapacitySearch.done();
SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create(); SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create();
if (zoneId != null){ if (zoneId != null){
sc.setParameters("dcId", zoneId); sc.setParameters("dcId", zoneId);
} }
if (podId != null){ if (podId != null){
sc.setParameters("podId", podId); sc.setParameters("podId", podId);
} }
if (clusterId != null){ if (clusterId != null){
sc.setParameters("clusterId", clusterId); sc.setParameters("clusterId", clusterId);
} }
if (capacityType != null){ if (capacityType != null){
sc.setParameters("capacityType", capacityType); sc.setParameters("capacityType", capacityType);
} }
Filter filter = new Filter(CapacityVO.class, null, true, null, null); Filter filter = new Filter(CapacityVO.class, null, true, null, null);
List<SummedCapacity> results = customSearchIncludingRemoved(sc, filter); List<SummedCapacity> results = customSearchIncludingRemoved(sc, filter);
return results; return results;
} }
public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) { public void updateAllocated(Long hostId, long allocatedAmount, short capacityType, boolean add) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
@ -384,75 +381,47 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
} }
} }
@Override @Override
public CapacityVO findByHostIdType(Long hostId, short capacityType) { public CapacityVO findByHostIdType(Long hostId, short capacityType) {
SearchCriteria<CapacityVO> sc = _hostIdTypeSearch.create(); SearchCriteria<CapacityVO> sc = _hostIdTypeSearch.create();
sc.setParameters("hostId", hostId); sc.setParameters("hostId", hostId);
sc.setParameters("type", capacityType); sc.setParameters("type", capacityType);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<Long> listClustersInZoneOrPodByHostCapacities(long id, int requiredCpu, long requiredRam, short capacityTypeForOrdering, boolean isZone, float cpuOverprovisioningFactor){ public List<Long> listClustersInZoneOrPodByHostCapacities(long id, int requiredCpu, long requiredRam, short capacityTypeForOrdering, boolean isZone, float cpuOverprovisioningFactor){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
List<Long> result = new ArrayList<Long>(); List<Long> result = new ArrayList<Long>();
StringBuilder sql = new StringBuilder(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART1); StringBuilder sql = new StringBuilder(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART1);
if(isZone){ if(isZone){
sql.append("capacity.data_center_id = ?"); sql.append("capacity.data_center_id = ?");
}else{ }else{
sql.append("capacity.pod_id = ?"); sql.append("capacity.pod_id = ?");
} }
sql.append(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART2); sql.append(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART2);
if(isZone){ if(isZone){
sql.append("capacity.data_center_id = ?"); sql.append("capacity.data_center_id = ?");
}else{ }else{
sql.append("capacity.pod_id = ?"); sql.append("capacity.pod_id = ?");
} }
sql.append(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART3); sql.append(LIST_CLUSTERSINZONE_BY_HOST_CAPACITIES_PART3);
try { try {
pstmt = txn.prepareAutoCloseStatement(sql.toString()); pstmt = txn.prepareAutoCloseStatement(sql.toString());
pstmt.setLong(1, id); pstmt.setLong(1, id);
pstmt.setShort(2, CapacityVO.CAPACITY_TYPE_CPU); pstmt.setShort(2, CapacityVO.CAPACITY_TYPE_CPU);
pstmt.setFloat(3, cpuOverprovisioningFactor); pstmt.setFloat(3, cpuOverprovisioningFactor);
pstmt.setLong(4, requiredCpu); pstmt.setLong(4, requiredCpu);
pstmt.setLong(5, id); pstmt.setLong(5, id);
pstmt.setShort(6, CapacityVO.CAPACITY_TYPE_MEMORY); pstmt.setShort(6, CapacityVO.CAPACITY_TYPE_MEMORY);
pstmt.setFloat(7, 1); pstmt.setFloat(7, 1);
pstmt.setLong(8, requiredRam); pstmt.setLong(8, requiredRam);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
result.add(rs.getLong(1));
}
return result;
} catch (SQLException e) {
throw new CloudRuntimeException("DB Exception on: " + sql, e);
} catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + sql, e);
}
}
@Override
public List<Long> listHostsWithEnoughCapacity(int requiredCpu, long requiredRam, Long clusterId, String hostType, float cpuOverprovisioningFactor){
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
List<Long> result = new ArrayList<Long>();
StringBuilder sql = new StringBuilder(LIST_HOSTS_IN_CLUSTER_WITH_ENOUGH_CAPACITY);
try {
pstmt = txn.prepareAutoCloseStatement(sql.toString());
pstmt.setLong(1, clusterId);
pstmt.setString(2, hostType);
pstmt.setFloat(3, cpuOverprovisioningFactor);
pstmt.setLong(4, requiredCpu);
pstmt.setLong(5, requiredRam);
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
result.add(rs.getLong(1)); result.add(rs.getLong(1));
@ -464,61 +433,89 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
throw new CloudRuntimeException("Caught: " + sql, e); throw new CloudRuntimeException("Caught: " + sql, e);
} }
} }
public static class SummedCapacity {
public long sumUsed; @Override
public long sumReserved; public List<Long> listHostsWithEnoughCapacity(int requiredCpu, long requiredRam, Long clusterId, String hostType, float cpuOverprovisioningFactor){
public long sumTotal; Transaction txn = Transaction.currentTxn();
public Float percentUsed; PreparedStatement pstmt = null;
public short capacityType; List<Long> result = new ArrayList<Long>();
public Long clusterId;
public Long podId; StringBuilder sql = new StringBuilder(LIST_HOSTS_IN_CLUSTER_WITH_ENOUGH_CAPACITY);
public Long dcId; try {
public SummedCapacity() { pstmt = txn.prepareAutoCloseStatement(sql.toString());
} pstmt.setLong(1, clusterId);
public SummedCapacity(long sumUsed, long sumReserved, long sumTotal, pstmt.setString(2, hostType);
short capacityType, Long clusterId, Long podId) { pstmt.setFloat(3, cpuOverprovisioningFactor);
super(); pstmt.setLong(4, requiredCpu);
this.sumUsed = sumUsed; pstmt.setLong(5, requiredRam);
this.sumReserved = sumReserved;
this.sumTotal = sumTotal; ResultSet rs = pstmt.executeQuery();
this.capacityType = capacityType; while (rs.next()) {
this.clusterId = clusterId; result.add(rs.getLong(1));
this.podId = podId; }
} return result;
public SummedCapacity(long sumUsed, long sumReserved, long sumTotal, } catch (SQLException e) {
throw new CloudRuntimeException("DB Exception on: " + sql, e);
} catch (Throwable e) {
throw new CloudRuntimeException("Caught: " + sql, e);
}
}
public static class SummedCapacity {
public long sumUsed;
public long sumReserved;
public long sumTotal;
public Float percentUsed;
public short capacityType;
public Long clusterId;
public Long podId;
public Long dcId;
public SummedCapacity() {
}
public SummedCapacity(long sumUsed, long sumReserved, long sumTotal,
short capacityType, Long clusterId, Long podId) {
super();
this.sumUsed = sumUsed;
this.sumReserved = sumReserved;
this.sumTotal = sumTotal;
this.capacityType = capacityType;
this.clusterId = clusterId;
this.podId = podId;
}
public SummedCapacity(long sumUsed, long sumReserved, long sumTotal,
short capacityType, Long clusterId, Long podId, Long zoneId) { short capacityType, Long clusterId, Long podId, Long zoneId) {
this(sumUsed, sumReserved, sumTotal, capacityType, clusterId, podId); this(sumUsed, sumReserved, sumTotal, capacityType, clusterId, podId);
this.dcId = zoneId; this.dcId = zoneId;
} }
public SummedCapacity(long sumUsed, long sumTotal, float percentUsed, short capacityType, Long zoneId, Long podId, Long clusterId) { public SummedCapacity(long sumUsed, long sumTotal, float percentUsed, short capacityType, Long zoneId, Long podId, Long clusterId) {
super(); super();
this.sumUsed = sumUsed; this.sumUsed = sumUsed;
this.sumTotal = sumTotal; this.sumTotal = sumTotal;
this.percentUsed = percentUsed; this.percentUsed = percentUsed;
this.capacityType = capacityType; this.capacityType = capacityType;
this.clusterId = clusterId; this.clusterId = clusterId;
this.podId = podId; this.podId = podId;
this.dcId = zoneId; this.dcId = zoneId;
} }
public Short getCapacityType() { public Short getCapacityType() {
return capacityType; return capacityType;
} }
public Long getUsedCapacity() { public Long getUsedCapacity() {
return sumUsed; return sumUsed;
} }
public long getReservedCapacity() { public long getReservedCapacity() {
return sumReserved; return sumReserved;
} }
public Long getTotalCapacity() { public Long getTotalCapacity() {
return sumTotal; return sumTotal;
} }
public Long getDataCenterId() { public Long getDataCenterId() {
return dcId; return dcId;
} }
public Long getClusterId() { public Long getClusterId() {
return clusterId; return clusterId;
} }
public Long getPodId() { public Long getPodId() {
@ -527,110 +524,111 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
public Float getPercentUsed() { public Float getPercentUsed() {
return percentUsed; return percentUsed;
} }
} }
public List<SummedCapacity> findByClusterPodZone(Long zoneId, Long podId, Long clusterId){ @Override
public List<SummedCapacity> findByClusterPodZone(Long zoneId, Long podId, Long clusterId){
SummedCapacitySearch = createSearchBuilder(SummedCapacity.class); SummedCapacitySearch = createSearchBuilder(SummedCapacity.class);
SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity()); SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity());
SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity()); SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity());
SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType());
SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.groupBy(SummedCapacitySearch.entity().getCapacityType());
if(zoneId != null){ if(zoneId != null){
SummedCapacitySearch.and("zoneId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ); SummedCapacitySearch.and("zoneId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ);
} }
if (podId != null){ if (podId != null){
SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ); SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ);
} }
if (clusterId != null){ if (clusterId != null){
SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ); SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ);
} }
SummedCapacitySearch.done(); SummedCapacitySearch.done();
SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create(); SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create();
if (zoneId != null){ if (zoneId != null){
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
} }
if (podId != null){ if (podId != null){
sc.setParameters("podId", podId); sc.setParameters("podId", podId);
} }
if (clusterId != null){ if (clusterId != null){
sc.setParameters("clusterId", clusterId); sc.setParameters("clusterId", clusterId);
} }
return customSearchIncludingRemoved(sc, null);
}
@Override
public List<SummedCapacity> findNonSharedStorageForClusterPodZone(Long zoneId, Long podId, Long clusterId){
SummedCapacitySearch = createSearchBuilder(SummedCapacity.class); return customSearchIncludingRemoved(sc, null);
}
@Override
public List<SummedCapacity> findNonSharedStorageForClusterPodZone(Long zoneId, Long podId, Long clusterId){
SummedCapacitySearch = createSearchBuilder(SummedCapacity.class);
SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity()); SummedCapacitySearch.select("sumUsed", Func.SUM, SummedCapacitySearch.entity().getUsedCapacity());
SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity()); SummedCapacitySearch.select("sumTotal", Func.SUM, SummedCapacitySearch.entity().getTotalCapacity());
SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType()); SummedCapacitySearch.select("capacityType", Func.NATIVE, SummedCapacitySearch.entity().getCapacityType());
SummedCapacitySearch.and("capacityType", SummedCapacitySearch.entity().getCapacityType(), Op.EQ); SummedCapacitySearch.and("capacityType", SummedCapacitySearch.entity().getCapacityType(), Op.EQ);
SearchBuilder<StoragePoolVO> nonSharedStorage = _storagePoolDao.createSearchBuilder(); SearchBuilder<StoragePoolVO> nonSharedStorage = _storagePoolDao.createSearchBuilder();
nonSharedStorage.and("poolTypes", nonSharedStorage.entity().getPoolType(), SearchCriteria.Op.IN); nonSharedStorage.and("poolTypes", nonSharedStorage.entity().getPoolType(), SearchCriteria.Op.IN);
SummedCapacitySearch.join("nonSharedStorage", nonSharedStorage, nonSharedStorage.entity().getId(), SummedCapacitySearch.entity().getHostOrPoolId(), JoinType.INNER); SummedCapacitySearch.join("nonSharedStorage", nonSharedStorage, nonSharedStorage.entity().getId(), SummedCapacitySearch.entity().getHostOrPoolId(), JoinType.INNER);
nonSharedStorage.done(); nonSharedStorage.done();
if(zoneId != null){ if(zoneId != null){
SummedCapacitySearch.and("zoneId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ); SummedCapacitySearch.and("zoneId", SummedCapacitySearch.entity().getDataCenterId(), Op.EQ);
} }
if (podId != null){ if (podId != null){
SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ); SummedCapacitySearch.and("podId", SummedCapacitySearch.entity().getPodId(), Op.EQ);
} }
if (clusterId != null){ if (clusterId != null){
SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ); SummedCapacitySearch.and("clusterId", SummedCapacitySearch.entity().getClusterId(), Op.EQ);
} }
SummedCapacitySearch.done(); SummedCapacitySearch.done();
SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create(); SearchCriteria<SummedCapacity> sc = SummedCapacitySearch.create();
sc.setJoinParameters("nonSharedStorage", "poolTypes", Storage.getNonSharedStoragePoolTypes().toArray()); sc.setJoinParameters("nonSharedStorage", "poolTypes", Storage.getNonSharedStoragePoolTypes().toArray());
sc.setParameters("capacityType", Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED); sc.setParameters("capacityType", Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED);
if (zoneId != null){ if (zoneId != null){
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
} }
if (podId != null){ if (podId != null){
sc.setParameters("podId", podId); sc.setParameters("podId", podId);
} }
if (clusterId != null){ if (clusterId != null){
sc.setParameters("clusterId", clusterId); sc.setParameters("clusterId", clusterId);
} }
return customSearchIncludingRemoved(sc, null); return customSearchIncludingRemoved(sc, null);
} }
@Override @Override
public boolean removeBy(Short capacityType, Long zoneId, Long podId, Long clusterId, Long hostId) { public boolean removeBy(Short capacityType, Long zoneId, Long podId, Long clusterId, Long hostId) {
SearchCriteria<CapacityVO> sc = _allFieldsSearch.create(); SearchCriteria<CapacityVO> sc = _allFieldsSearch.create();
if (capacityType != null) { if (capacityType != null) {
sc.setParameters("capacityType", capacityType); sc.setParameters("capacityType", capacityType);
} }
if (zoneId != null) { if (zoneId != null) {
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
} }
if (podId != null) { if (podId != null) {
sc.setParameters("podId", podId); sc.setParameters("podId", podId);
} }
if (clusterId != null) { if (clusterId != null) {
sc.setParameters("clusterId", clusterId); sc.setParameters("clusterId", clusterId);
} }
if (hostId != null) { if (hostId != null) {
sc.setParameters("hostId", hostId); sc.setParameters("hostId", hostId);
} }
return remove(sc) > 0; return remove(sc) > 0;
} }
@Override @Override
public Pair<List<Long>, Map<Long, Double>> orderClustersByAggregateCapacity(long id, short capacityTypeForOrdering, boolean isZone, float cpuOverprovisioningFactor){ public Pair<List<Long>, Map<Long, Double>> orderClustersByAggregateCapacity(long id, short capacityTypeForOrdering, boolean isZone, float cpuOverprovisioningFactor){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -639,7 +637,7 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
Map<Long, Double> clusterCapacityMap = new HashMap<Long, Double>(); Map<Long, Double> clusterCapacityMap = new HashMap<Long, Double>();
StringBuilder sql = new StringBuilder(ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART1); StringBuilder sql = new StringBuilder(ORDER_CLUSTERS_BY_AGGREGATE_CAPACITY_PART1);
if(isZone){ if(isZone){
sql.append("data_center_id = ?"); sql.append("data_center_id = ?");
}else{ }else{
@ -708,13 +706,13 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
List<Long> result = new ArrayList<Long>(); List<Long> result = new ArrayList<Long>();
Map<Long, Double> podCapacityMap = new HashMap<Long, Double>(); Map<Long, Double> podCapacityMap = new HashMap<Long, Double>();
StringBuilder sql = new StringBuilder(ORDER_PODS_BY_AGGREGATE_CAPACITY); StringBuilder sql = new StringBuilder(ORDER_PODS_BY_AGGREGATE_CAPACITY);
try { try {
pstmt = txn.prepareAutoCloseStatement(sql.toString()); pstmt = txn.prepareAutoCloseStatement(sql.toString());
pstmt.setLong(2, zoneId); pstmt.setLong(2, zoneId);
pstmt.setShort(3, capacityTypeForOrdering); pstmt.setShort(3, capacityTypeForOrdering);
if(capacityTypeForOrdering == CapacityVO.CAPACITY_TYPE_CPU){ if(capacityTypeForOrdering == CapacityVO.CAPACITY_TYPE_CPU){
pstmt.setFloat(1, cpuOverprovisioningFactor); pstmt.setFloat(1, cpuOverprovisioningFactor);
pstmt.setFloat(4, cpuOverprovisioningFactor); pstmt.setFloat(4, cpuOverprovisioningFactor);
@ -722,7 +720,7 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
pstmt.setFloat(1, 1); pstmt.setFloat(1, 1);
pstmt.setFloat(4, 1); pstmt.setFloat(4, 1);
} }
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
Long podId = rs.getLong(1); Long podId = rs.getLong(1);
@ -736,13 +734,13 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
throw new CloudRuntimeException("Caught: " + sql, e); throw new CloudRuntimeException("Caught: " + sql, e);
} }
} }
@Override @Override
public void updateCapacityState(Long dcId, Long podId, Long clusterId, Long hostId, String capacityState) { public void updateCapacityState(Long dcId, Long podId, Long clusterId, Long hostId, String capacityState) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
StringBuilder sql = new StringBuilder(UPDATE_CAPACITY_STATE); StringBuilder sql = new StringBuilder(UPDATE_CAPACITY_STATE);
List<Long> resourceIdList = new ArrayList<Long>(); List<Long> resourceIdList = new ArrayList<Long>();
if (dcId != null){ if (dcId != null){
sql.append(" data_center_id = ?"); sql.append(" data_center_id = ?");
resourceIdList.add(dcId); resourceIdList.add(dcId);
@ -759,7 +757,7 @@ public class CapacityDaoImpl extends GenericDaoBase<CapacityVO, Long> implements
sql.append(" host_id = ?"); sql.append(" host_id = ?");
resourceIdList.add(hostId); resourceIdList.add(hostId);
} }
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
try { try {
pstmt = txn.prepareAutoCloseStatement(sql.toString()); pstmt = txn.prepareAutoCloseStatement(sql.toString());

View File

@ -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.cluster;
/**
* TaskManager helps business logic deal with clustering failover.
* Say you're writing code that introduces an inconsistent state over
* of your operation? Who will come back to cleanup this state? TaskManager
* with different content during your process. If the server dies, TaskManager
* running elsewhere. If there are no clustered servers, then TaskManager will
* cleanup when the dead server resumes.
*
*/
public interface CheckPointManager {
/**
* responsible for cleaning up.
*
* @param context context information to be stored.
* @return Check point id.
*/
long pushCheckPoint(CleanupMaid context);
/**
* update the task with new context
* @param taskId
* @param updatedContext new updated context.
*/
void updateCheckPointState(long taskId, CleanupMaid updatedContext);
/**
* removes the task as it is completed.
*
* @param taskId
*/
void popCheckPoint(long taskId);
}

View File

@ -1,247 +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.cluster;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.cluster.dao.StackMaidDao;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.serializer.SerializerHelper;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
@Component
@Local(value=CheckPointManager.class)
public class CheckPointManagerImpl implements CheckPointManager, Manager, ClusterManagerListener {
private static final Logger s_logger = Logger.getLogger(CheckPointManagerImpl.class);
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION = 3; // 3 seconds
private int _cleanupRetryInterval;
private String _name;
@Inject
private StackMaidDao _maidDao;
@Inject
private ClusterManager _clusterMgr;
@Inject ConfigurationDao _configDao;
long _msId;
private final ScheduledExecutorService _cleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Task-Cleanup"));
protected CheckPointManagerImpl() {
}
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
_name = name;
if (s_logger.isInfoEnabled()) {
s_logger.info("Start configuring StackMaidManager : " + name);
}
StackMaid.init(ManagementServerNode.getManagementServerId());
_msId = ManagementServerNode.getManagementServerId();
_clusterMgr.registerListener(this);
Map<String, String> params = _configDao.getConfiguration(xmlParams);
_cleanupRetryInterval = NumbersUtil.parseInt(params.get(Config.TaskCleanupRetryInterval.key()), 600);
_maidDao.takeover(_msId, _msId);
return true;
}
private void cleanupLeftovers(List<CheckPointVO> l) {
for (CheckPointVO maid : l) {
if (StackMaid.doCleanup(maid)) {
_maidDao.expunge(maid.getId());
}
}
}
@Override
public void onManagementNodeIsolated() {
}
@DB
private Runnable getGCTask() {
return new Runnable() {
@Override
public void run() {
GlobalLock scanLock = GlobalLock.getInternLock("StackMaidManagerGC");
try {
if (scanLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_COOPERATION)) {
try {
reallyRun();
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
public void reallyRun() {
try {
Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - 7200000);
List<CheckPointVO> l = _maidDao.listLeftoversByCutTime(cutTime);
cleanupLeftovers(l);
} catch (Throwable e) {
s_logger.error("Unexpected exception when trying to execute queue item, ", e);
}
}
};
}
@Override
public boolean start() {
_cleanupScheduler.schedule(new CleanupTask(), _cleanupRetryInterval > 0 ? _cleanupRetryInterval : 600, TimeUnit.SECONDS);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) {
// Nothing to do
}
@Override
public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) {
for (ManagementServerHostVO node : nodeList) {
if (_maidDao.takeover(node.getMsid(), selfNodeId)) {
s_logger.info("Taking over from " + node.getMsid());
_cleanupScheduler.execute(new CleanupTask());
}
}
}
@Override
@DB
public long pushCheckPoint(CleanupMaid context) {
long seq = _maidDao.pushCleanupDelegate(_msId, 0, context.getClass().getName(), context);
return seq;
}
@Override
@DB
public void updateCheckPointState(long taskId, CleanupMaid updatedContext) {
CheckPointVO task = _maidDao.createForUpdate();
task.setDelegate(updatedContext.getClass().getName());
task.setContext(SerializerHelper.toSerializedStringOld(updatedContext));
_maidDao.update(taskId, task);
}
@Override
@DB
public void popCheckPoint(long taskId) {
_maidDao.remove(taskId);
}
protected boolean cleanup(CheckPointVO task) {
s_logger.info("Cleaning up " + task);
CleanupMaid delegate = (CleanupMaid)SerializerHelper.fromSerializedString(task.getContext());
assert delegate.getClass().getName().equals(task.getDelegate()) : "Deserializer says " + delegate.getClass().getName() + " but it's suppose to be " + task.getDelegate();
int result = delegate.cleanup(this);
if (result <= 0) {
if (result == 0) {
s_logger.info("Successfully cleaned up " + task.getId());
} else {
s_logger.warn("Unsuccessful in cleaning up " + task + ". Procedure to cleanup manaully: " + delegate.getCleanupProcedure());
}
popCheckPoint(task.getId());
return true;
} else {
s_logger.error("Unable to cleanup " + task.getId());
return false;
}
}
class CleanupTask implements Runnable {
private Date _curDate;
public CleanupTask() {
_curDate = new Date();
}
@Override
public void run() {
try {
List<CheckPointVO> tasks = _maidDao.listLeftoversByCutTime(_curDate, _msId);
tasks.addAll(_maidDao.listCleanupTasks(_msId));
List<CheckPointVO> retries = new ArrayList<CheckPointVO>();
for (CheckPointVO task : tasks) {
try {
if (!cleanup(task)) {
retries.add(task);
}
} catch (Exception e) {
s_logger.warn("Unable to clean up " + task, e);
}
}
if (retries.size() > 0) {
if (_cleanupRetryInterval > 0) {
_cleanupScheduler.schedule(this, _cleanupRetryInterval, TimeUnit.SECONDS);
} else {
for (CheckPointVO task : retries) {
s_logger.warn("Cleanup procedure for " + task + ": " + ((CleanupMaid)SerializerHelper.fromSerializedString(task.getContext())).getCleanupProcedure());
}
}
}
} catch (Exception e) {
s_logger.error("Unable to cleanup all of the tasks for " + _msId, e);
}
}
}
}

View File

@ -1,41 +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.cluster;
/**
*
* task. The state is serialized and stored. When cleanup is required
* CleanupMaid is instantiated from the stored data and cleanup() is called.
*
*/
public interface CleanupMaid {
/**
* cleanup according the state that was stored.
*
* @return 0 indicates cleanup was successful. Negative number
* indicates the cleanup was unsuccessful but don't retry. Positive number
* indicates the cleanup was unsuccessful and retry in this many seconds.
*/
int cleanup(CheckPointManager checkPointMgr);
/**
* returned here is recorded.
* @return
*/
String getCleanupProcedure();
}

View File

@ -29,7 +29,6 @@ import java.sql.SQLException;
import java.sql.SQLRecoverableException; import java.sql.SQLRecoverableException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -75,8 +74,6 @@ import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Profiler; import com.cloud.utils.Profiler;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.ConnectionConcierge; import com.cloud.utils.db.ConnectionConcierge;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
@ -123,7 +120,7 @@ public class ClusterManagerImpl implements ClusterManager {
private final ExecutorService _executor; private final ExecutorService _executor;
private ClusterServiceAdapter _currentServiceAdapter; private ClusterServiceAdapter _currentServiceAdapter;
@Inject @Inject
private List<ClusterServiceAdapter> _serviceAdapters; private List<ClusterServiceAdapter> _serviceAdapters;
@ -149,11 +146,11 @@ public class ClusterManagerImpl implements ClusterManager {
private boolean _agentLBEnabled = false; private boolean _agentLBEnabled = false;
private double _connectedAgentsThreshold = 0.7; private double _connectedAgentsThreshold = 0.7;
private static boolean _agentLbHappened = false; private static boolean _agentLbHappened = false;
private List<ClusterServicePdu> _clusterPduOutgoingQueue = new ArrayList<ClusterServicePdu>(); private final List<ClusterServicePdu> _clusterPduOutgoingQueue = new ArrayList<ClusterServicePdu>();
private List<ClusterServicePdu> _clusterPduIncomingQueue = new ArrayList<ClusterServicePdu>(); private final List<ClusterServicePdu> _clusterPduIncomingQueue = new ArrayList<ClusterServicePdu>();
private Map<Long, ClusterServiceRequestPdu> _outgoingPdusWaitingForAck = new HashMap<Long, ClusterServiceRequestPdu>(); private final Map<Long, ClusterServiceRequestPdu> _outgoingPdusWaitingForAck = new HashMap<Long, ClusterServiceRequestPdu>();
public ClusterManagerImpl() { public ClusterManagerImpl() {
_clusterPeers = new HashMap<String, ClusterService>(); _clusterPeers = new HashMap<String, ClusterService>();
@ -164,13 +161,13 @@ public class ClusterManagerImpl implements ClusterManager {
// //
_executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Worker")); _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Worker"));
} }
private void registerRequestPdu(ClusterServiceRequestPdu pdu) { private void registerRequestPdu(ClusterServiceRequestPdu pdu) {
synchronized(_outgoingPdusWaitingForAck) { synchronized(_outgoingPdusWaitingForAck) {
_outgoingPdusWaitingForAck.put(pdu.getSequenceId(), pdu); _outgoingPdusWaitingForAck.put(pdu.getSequenceId(), pdu);
} }
} }
private ClusterServiceRequestPdu popRequestPdu(long ackSequenceId) { private ClusterServiceRequestPdu popRequestPdu(long ackSequenceId) {
synchronized(_outgoingPdusWaitingForAck) { synchronized(_outgoingPdusWaitingForAck) {
if(_outgoingPdusWaitingForAck.get(ackSequenceId) != null) { if(_outgoingPdusWaitingForAck.get(ackSequenceId) != null) {
@ -179,10 +176,10 @@ public class ClusterManagerImpl implements ClusterManager {
return pdu; return pdu;
} }
} }
return null; return null;
} }
private void cancelClusterRequestToPeer(String strPeer) { private void cancelClusterRequestToPeer(String strPeer) {
List<ClusterServiceRequestPdu> candidates = new ArrayList<ClusterServiceRequestPdu>(); List<ClusterServiceRequestPdu> candidates = new ArrayList<ClusterServiceRequestPdu>();
synchronized(_outgoingPdusWaitingForAck) { synchronized(_outgoingPdusWaitingForAck) {
@ -195,7 +192,7 @@ public class ClusterManagerImpl implements ClusterManager {
_outgoingPdusWaitingForAck.remove(pdu.getSequenceId()); _outgoingPdusWaitingForAck.remove(pdu.getSequenceId());
} }
} }
for(ClusterServiceRequestPdu pdu : candidates) { for(ClusterServiceRequestPdu pdu : candidates) {
s_logger.warn("Cancel cluster request PDU to peer: " + strPeer + ", pdu: " + _gson.toJson(pdu)); s_logger.warn("Cancel cluster request PDU to peer: " + strPeer + ", pdu: " + _gson.toJson(pdu));
synchronized(pdu) { synchronized(pdu) {
@ -203,76 +200,78 @@ public class ClusterManagerImpl implements ClusterManager {
} }
} }
} }
private void addOutgoingClusterPdu(ClusterServicePdu pdu) { private void addOutgoingClusterPdu(ClusterServicePdu pdu) {
synchronized(_clusterPduOutgoingQueue) { synchronized(_clusterPduOutgoingQueue) {
_clusterPduOutgoingQueue.add(pdu); _clusterPduOutgoingQueue.add(pdu);
_clusterPduOutgoingQueue.notifyAll(); _clusterPduOutgoingQueue.notifyAll();
} }
} }
private ClusterServicePdu popOutgoingClusterPdu(long timeoutMs) { private ClusterServicePdu popOutgoingClusterPdu(long timeoutMs) {
synchronized(_clusterPduOutgoingQueue) { synchronized(_clusterPduOutgoingQueue) {
try { try {
_clusterPduOutgoingQueue.wait(timeoutMs); _clusterPduOutgoingQueue.wait(timeoutMs);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
if(_clusterPduOutgoingQueue.size() > 0) { if(_clusterPduOutgoingQueue.size() > 0) {
ClusterServicePdu pdu = _clusterPduOutgoingQueue.get(0); ClusterServicePdu pdu = _clusterPduOutgoingQueue.get(0);
_clusterPduOutgoingQueue.remove(0); _clusterPduOutgoingQueue.remove(0);
return pdu; return pdu;
} }
} }
return null; return null;
} }
private void addIncomingClusterPdu(ClusterServicePdu pdu) { private void addIncomingClusterPdu(ClusterServicePdu pdu) {
synchronized(_clusterPduIncomingQueue) { synchronized(_clusterPduIncomingQueue) {
_clusterPduIncomingQueue.add(pdu); _clusterPduIncomingQueue.add(pdu);
_clusterPduIncomingQueue.notifyAll(); _clusterPduIncomingQueue.notifyAll();
} }
} }
private ClusterServicePdu popIncomingClusterPdu(long timeoutMs) { private ClusterServicePdu popIncomingClusterPdu(long timeoutMs) {
synchronized(_clusterPduIncomingQueue) { synchronized(_clusterPduIncomingQueue) {
try { try {
_clusterPduIncomingQueue.wait(timeoutMs); _clusterPduIncomingQueue.wait(timeoutMs);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
if(_clusterPduIncomingQueue.size() > 0) { if(_clusterPduIncomingQueue.size() > 0) {
ClusterServicePdu pdu = _clusterPduIncomingQueue.get(0); ClusterServicePdu pdu = _clusterPduIncomingQueue.get(0);
_clusterPduIncomingQueue.remove(0); _clusterPduIncomingQueue.remove(0);
return pdu; return pdu;
} }
} }
return null; return null;
} }
private Runnable getClusterPduSendingTask() { private Runnable getClusterPduSendingTask() {
return new Runnable() { return new Runnable() {
@Override
public void run() { public void run() {
onSendingClusterPdu(); onSendingClusterPdu();
} }
}; };
} }
private Runnable getClusterPduNotificationTask() { private Runnable getClusterPduNotificationTask() {
return new Runnable() { return new Runnable() {
@Override
public void run() { public void run() {
onNotifyingClusterPdu(); onNotifyingClusterPdu();
} }
}; };
} }
private void onSendingClusterPdu() { private void onSendingClusterPdu() {
while(true) { while(true) {
try { try {
ClusterServicePdu pdu = popOutgoingClusterPdu(1000); ClusterServicePdu pdu = popOutgoingClusterPdu(1000);
if(pdu == null) if(pdu == null)
continue; continue;
ClusterService peerService = null; ClusterService peerService = null;
for(int i = 0; i < 2; i++) { for(int i = 0; i < 2; i++) {
try { try {
@ -285,20 +284,20 @@ public class ClusterManagerImpl implements ClusterManager {
try { try {
if(s_logger.isDebugEnabled()) { if(s_logger.isDebugEnabled()) {
s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + ". agent: " + pdu.getAgentId() s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + ". agent: " + pdu.getAgentId()
+ ", pdu seq: " + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + ", pdu seq: " + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage());
} }
long startTick = System.currentTimeMillis(); long startTick = System.currentTimeMillis();
String strResult = peerService.execute(pdu); String strResult = peerService.execute(pdu);
if(s_logger.isDebugEnabled()) { if(s_logger.isDebugEnabled()) {
s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + " completed. time: " + s_logger.debug("Cluster PDU " + getSelfPeerName() + " -> " + pdu.getDestPeer() + " completed. time: " +
(System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId() (System.currentTimeMillis() - startTick) + "ms. agent: " + pdu.getAgentId()
+ ", pdu seq: " + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage()); + ", pdu seq: " + pdu.getSequenceId() + ", pdu ack seq: " + pdu.getAckSequenceId() + ", json: " + pdu.getJsonPackage());
} }
if("true".equals(strResult)) if("true".equals(strResult))
break; break;
} catch (RemoteException e) { } catch (RemoteException e) {
invalidatePeerService(pdu.getDestPeer()); invalidatePeerService(pdu.getDestPeer());
if(s_logger.isInfoEnabled()) { if(s_logger.isInfoEnabled()) {
@ -313,50 +312,51 @@ public class ClusterManagerImpl implements ClusterManager {
} }
} }
} }
private void onNotifyingClusterPdu() { private void onNotifyingClusterPdu() {
while(true) { while(true) {
try { try {
final ClusterServicePdu pdu = popIncomingClusterPdu(1000); final ClusterServicePdu pdu = popIncomingClusterPdu(1000);
if(pdu == null) if(pdu == null)
continue; continue;
_executor.execute(new Runnable() { _executor.execute(new Runnable() {
public void run() { @Override
if(pdu.getPduType() == ClusterServicePdu.PDU_TYPE_RESPONSE) { public void run() {
ClusterServiceRequestPdu requestPdu = popRequestPdu(pdu.getAckSequenceId()); if(pdu.getPduType() == ClusterServicePdu.PDU_TYPE_RESPONSE) {
if(requestPdu != null) { ClusterServiceRequestPdu requestPdu = popRequestPdu(pdu.getAckSequenceId());
requestPdu.setResponseResult(pdu.getJsonPackage()); if(requestPdu != null) {
synchronized(requestPdu) { requestPdu.setResponseResult(pdu.getJsonPackage());
requestPdu.notifyAll(); synchronized(requestPdu) {
} requestPdu.notifyAll();
} else { }
s_logger.warn("Original request has already been cancelled. pdu: " + _gson.toJson(pdu)); } else {
} s_logger.warn("Original request has already been cancelled. pdu: " + _gson.toJson(pdu));
} else { }
String result = dispatchClusterServicePdu(pdu); } else {
if(result == null) String result = dispatchClusterServicePdu(pdu);
result = ""; if(result == null)
result = "";
if(pdu.getPduType() == ClusterServicePdu.PDU_TYPE_REQUEST) {
ClusterServicePdu responsePdu = new ClusterServicePdu(); if(pdu.getPduType() == ClusterServicePdu.PDU_TYPE_REQUEST) {
responsePdu.setPduType(ClusterServicePdu.PDU_TYPE_RESPONSE); ClusterServicePdu responsePdu = new ClusterServicePdu();
responsePdu.setSourcePeer(pdu.getDestPeer()); responsePdu.setPduType(ClusterServicePdu.PDU_TYPE_RESPONSE);
responsePdu.setDestPeer(pdu.getSourcePeer()); responsePdu.setSourcePeer(pdu.getDestPeer());
responsePdu.setAckSequenceId(pdu.getSequenceId()); responsePdu.setDestPeer(pdu.getSourcePeer());
responsePdu.setJsonPackage(result); responsePdu.setAckSequenceId(pdu.getSequenceId());
responsePdu.setJsonPackage(result);
addOutgoingClusterPdu(responsePdu);
} addOutgoingClusterPdu(responsePdu);
} }
} }
}
}); });
} catch(Throwable e) { } catch(Throwable e) {
s_logger.error("Unexcpeted exception: ", e); s_logger.error("Unexcpeted exception: ", e);
} }
} }
} }
private String dispatchClusterServicePdu(ClusterServicePdu pdu) { private String dispatchClusterServicePdu(ClusterServicePdu pdu) {
if(s_logger.isDebugEnabled()) { if(s_logger.isDebugEnabled()) {
@ -370,7 +370,7 @@ public class ClusterManagerImpl implements ClusterManager {
assert(false); assert(false);
s_logger.error("Excection in gson decoding : ", e); s_logger.error("Excection in gson decoding : ", e);
} }
if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { //intercepted if (cmds.length == 1 && cmds[0] instanceof ChangeAgentCommand) { //intercepted
ChangeAgentCommand cmd = (ChangeAgentCommand)cmds[0]; ChangeAgentCommand cmd = (ChangeAgentCommand)cmds[0];
@ -416,22 +416,22 @@ public class ClusterManagerImpl implements ClusterManager {
answers[0] = new Answer(cmd, result, null); answers[0] = new Answer(cmd, result, null);
return _gson.toJson(answers); return _gson.toJson(answers);
} else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand ) { } else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand ) {
PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0]; PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0];
s_logger.debug("Intercepting command to propagate event " + cmd.getEvent().name() + " for host " + cmd.getHostId()); s_logger.debug("Intercepting command to propagate event " + cmd.getEvent().name() + " for host " + cmd.getHostId());
boolean result = false; boolean result = false;
try { try {
result = executeResourceUserRequest(cmd.getHostId(), cmd.getEvent()); result = executeResourceUserRequest(cmd.getHostId(), cmd.getEvent());
s_logger.debug("Result is " + result); s_logger.debug("Result is " + result);
} catch (AgentUnavailableException ex) { } catch (AgentUnavailableException ex) {
s_logger.warn("Agent is unavailable", ex); s_logger.warn("Agent is unavailable", ex);
return null; return null;
} }
Answer[] answers = new Answer[1]; Answer[] answers = new Answer[1];
answers[0] = new Answer(cmd, result, null); answers[0] = new Answer(cmd, result, null);
return _gson.toJson(answers); return _gson.toJson(answers);
} }
try { try {
@ -461,14 +461,15 @@ public class ClusterManagerImpl implements ClusterManager {
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
s_logger.warn("Timed Out", e); s_logger.warn("Timed Out", e);
} }
return null; return null;
} }
@Override
public void OnReceiveClusterServicePdu(ClusterServicePdu pdu) { public void OnReceiveClusterServicePdu(ClusterServicePdu pdu) {
addIncomingClusterPdu(pdu); addIncomingClusterPdu(pdu);
} }
@Override @Override
public Answer[] sendToAgent(Long hostId, Command[] cmds, boolean stopOnError) throws AgentUnavailableException, OperationTimedoutException { public Answer[] sendToAgent(Long hostId, Command[] cmds, boolean stopOnError) throws AgentUnavailableException, OperationTimedoutException {
Commands commands = new Commands(stopOnError ? OnError.Stop : OnError.Continue); Commands commands = new Commands(stopOnError ? OnError.Stop : OnError.Continue);
@ -558,7 +559,7 @@ public class ClusterManagerImpl implements ClusterManager {
s_logger.debug(getSelfPeerName() + " -> " + strPeer + "." + agentId + " " + s_logger.debug(getSelfPeerName() + " -> " + strPeer + "." + agentId + " " +
_gson.toJson(cmds, Command[].class)); _gson.toJson(cmds, Command[].class));
} }
ClusterServiceRequestPdu pdu = new ClusterServiceRequestPdu(); ClusterServiceRequestPdu pdu = new ClusterServiceRequestPdu();
pdu.setSourcePeer(getSelfPeerName()); pdu.setSourcePeer(getSelfPeerName());
pdu.setDestPeer(strPeer); pdu.setDestPeer(strPeer);
@ -567,7 +568,7 @@ public class ClusterManagerImpl implements ClusterManager {
pdu.setStopOnError(stopOnError); pdu.setStopOnError(stopOnError);
registerRequestPdu(pdu); registerRequestPdu(pdu);
addOutgoingClusterPdu(pdu); addOutgoingClusterPdu(pdu);
synchronized(pdu) { synchronized(pdu) {
try { try {
pdu.wait(); pdu.wait();
@ -577,9 +578,9 @@ public class ClusterManagerImpl implements ClusterManager {
if(s_logger.isDebugEnabled()) { if(s_logger.isDebugEnabled()) {
s_logger.debug(getSelfPeerName() + " -> " + strPeer + "." + agentId + " completed. result: " + s_logger.debug(getSelfPeerName() + " -> " + strPeer + "." + agentId + " completed. result: " +
pdu.getResponseResult()); pdu.getResponseResult());
} }
if(pdu.getResponseResult() != null && pdu.getResponseResult().length() > 0) { if(pdu.getResponseResult() != null && pdu.getResponseResult().length() > 0) {
try { try {
return _gson.fromJson(pdu.getResponseResult(), Answer[].class); return _gson.fromJson(pdu.getResponseResult(), Answer[].class);
@ -590,7 +591,7 @@ public class ClusterManagerImpl implements ClusterManager {
return null; return null;
} }
@Override @Override
public String getPeerName(long agentHostId) { public String getPeerName(long agentHostId) {
@ -625,18 +626,18 @@ public class ClusterManagerImpl implements ClusterManager {
// Note : we don't check duplicates // Note : we don't check duplicates
synchronized (_listeners) { synchronized (_listeners) {
s_logger.info("register cluster listener " + listener.getClass()); s_logger.info("register cluster listener " + listener.getClass());
_listeners.add(listener); _listeners.add(listener);
} }
} }
@Override @Override
public void unregisterListener(ClusterManagerListener listener) { public void unregisterListener(ClusterManagerListener listener) {
synchronized(_listeners) { synchronized(_listeners) {
s_logger.info("unregister cluster listener " + listener.getClass()); s_logger.info("unregister cluster listener " + listener.getClass());
_listeners.remove(listener); _listeners.remove(listener);
} }
} }
@ -663,7 +664,7 @@ public class ClusterManagerImpl implements ClusterManager {
if(s_logger.isDebugEnabled()) { if(s_logger.isDebugEnabled()) {
s_logger.debug("Notify management server node left to listeners."); s_logger.debug("Notify management server node left to listeners.");
} }
for(ManagementServerHostVO mshost : nodeList) { for(ManagementServerHostVO mshost : nodeList) {
if(s_logger.isDebugEnabled()) if(s_logger.isDebugEnabled())
s_logger.debug("Leaving node, IP: " + mshost.getServiceIP() + ", msid: " + mshost.getMsid()); s_logger.debug("Leaving node, IP: " + mshost.getServiceIP() + ", msid: " + mshost.getMsid());
@ -731,32 +732,32 @@ public class ClusterManagerImpl implements ClusterManager {
Profiler profilerHeartbeatUpdate = new Profiler(); Profiler profilerHeartbeatUpdate = new Profiler();
Profiler profilerPeerScan = new Profiler(); Profiler profilerPeerScan = new Profiler();
Profiler profilerAgentLB = new Profiler(); Profiler profilerAgentLB = new Profiler();
try { try {
profiler.start(); profiler.start();
profilerHeartbeatUpdate.start(); profilerHeartbeatUpdate.start();
txn.transitToUserManagedConnection(getHeartbeatConnection()); txn.transitToUserManagedConnection(getHeartbeatConnection());
if(s_logger.isTraceEnabled()) { if(s_logger.isTraceEnabled()) {
s_logger.trace("Cluster manager heartbeat update, id:" + _mshostId); s_logger.trace("Cluster manager heartbeat update, id:" + _mshostId);
} }
_mshostDao.update(_mshostId, getCurrentRunId(), DateUtil.currentGMTTime()); _mshostDao.update(_mshostId, getCurrentRunId(), DateUtil.currentGMTTime());
profilerHeartbeatUpdate.stop(); profilerHeartbeatUpdate.stop();
profilerPeerScan.start(); profilerPeerScan.start();
if (s_logger.isTraceEnabled()) { if (s_logger.isTraceEnabled()) {
s_logger.trace("Cluster manager peer-scan, id:" + _mshostId); s_logger.trace("Cluster manager peer-scan, id:" + _mshostId);
} }
if (!_peerScanInited) { if (!_peerScanInited) {
_peerScanInited = true; _peerScanInited = true;
initPeerScan(); initPeerScan();
} }
peerScan(); peerScan();
profilerPeerScan.stop(); profilerPeerScan.stop();
profilerAgentLB.start(); profilerAgentLB.start();
//initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold //initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold
if (_agentLBEnabled && !_agentLbHappened) { if (_agentLBEnabled && !_agentLbHappened) {
@ -764,7 +765,7 @@ public class ClusterManagerImpl implements ClusterManager {
sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL);
sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing);
List<HostVO> allManagedRoutingAgents = sc.list(); List<HostVO> allManagedRoutingAgents = sc.list();
sc = SearchCriteria2.create(HostVO.class); sc = SearchCriteria2.create(HostVO.class);
sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing);
List<HostVO> allAgents = sc.list(); List<HostVO> allAgents = sc.list();
@ -784,16 +785,16 @@ public class ClusterManagerImpl implements ClusterManager {
profilerAgentLB.stop(); profilerAgentLB.stop();
} finally { } finally {
profiler.stop(); profiler.stop();
if(profiler.getDuration() >= _heartbeatInterval) { if(profiler.getDuration() >= _heartbeatInterval) {
if(s_logger.isDebugEnabled()) if(s_logger.isDebugEnabled())
s_logger.debug("Management server heartbeat takes too long to finish. profiler: " + profiler.toString() + s_logger.debug("Management server heartbeat takes too long to finish. profiler: " + profiler.toString() +
", profilerHeartbeatUpdate: " + profilerHeartbeatUpdate.toString() + ", profilerHeartbeatUpdate: " + profilerHeartbeatUpdate.toString() +
", profilerPeerScan: " + profilerPeerScan.toString() + ", profilerPeerScan: " + profilerPeerScan.toString() +
", profilerAgentLB: " + profilerAgentLB.toString()); ", profilerAgentLB: " + profilerAgentLB.toString());
} }
} }
} catch(CloudRuntimeException e) { } catch(CloudRuntimeException e) {
s_logger.error("Runtime DB exception ", e.getCause()); s_logger.error("Runtime DB exception ", e.getCause());
@ -933,33 +934,33 @@ public class ClusterManagerImpl implements ClusterManager {
this._notificationMsgs.add(msg); this._notificationMsgs.add(msg);
this._notificationMsgs.notifyAll(); this._notificationMsgs.notifyAll();
} }
switch(msg.getMessageType()) { switch(msg.getMessageType()) {
case nodeAdded: case nodeAdded:
{ {
List<ManagementServerHostVO> l = msg.getNodes(); List<ManagementServerHostVO> l = msg.getNodes();
if(l != null && l.size() > 0) { if(l != null && l.size() > 0) {
for(ManagementServerHostVO mshost: l) { for(ManagementServerHostVO mshost: l) {
_mshostPeerDao.updatePeerInfo(_mshostId, mshost.getId(), mshost.getRunid(), ManagementServerHost.State.Up); _mshostPeerDao.updatePeerInfo(_mshostId, mshost.getId(), mshost.getRunid(), ManagementServerHost.State.Up);
}
} }
} }
break; }
break;
case nodeRemoved: case nodeRemoved:
{ {
List<ManagementServerHostVO> l = msg.getNodes(); List<ManagementServerHostVO> l = msg.getNodes();
if(l != null && l.size() > 0) { if(l != null && l.size() > 0) {
for(ManagementServerHostVO mshost: l) { for(ManagementServerHostVO mshost: l) {
_mshostPeerDao.updatePeerInfo(_mshostId, mshost.getId(), mshost.getRunid(), ManagementServerHost.State.Down); _mshostPeerDao.updatePeerInfo(_mshostId, mshost.getId(), mshost.getRunid(), ManagementServerHost.State.Down);
}
} }
} }
break; }
break;
default : default :
break; break;
} }
} }
@ -978,39 +979,39 @@ public class ClusterManagerImpl implements ClusterManager {
// missed cleanup // missed cleanup
Date cutTime = DateUtil.currentGMTTime(); Date cutTime = DateUtil.currentGMTTime();
List<ManagementServerHostVO> inactiveList = _mshostDao.getInactiveList(new Date(cutTime.getTime() - _heartbeatThreshold)); List<ManagementServerHostVO> inactiveList = _mshostDao.getInactiveList(new Date(cutTime.getTime() - _heartbeatThreshold));
// We don't have foreign key constraints to enforce the mgmt_server_id integrity in host table, when user manually // We don't have foreign key constraints to enforce the mgmt_server_id integrity in host table, when user manually
// remove records from mshost table, this will leave orphan mgmt_serve_id reference in host table. // remove records from mshost table, this will leave orphan mgmt_serve_id reference in host table.
List<Long> orphanList = _mshostDao.listOrphanMsids(); List<Long> orphanList = _mshostDao.listOrphanMsids();
if(orphanList.size() > 0) { if(orphanList.size() > 0) {
for(Long orphanMsid : orphanList) { for(Long orphanMsid : orphanList) {
// construct fake ManagementServerHostVO based on orphan MSID // construct fake ManagementServerHostVO based on orphan MSID
s_logger.info("Add orphan management server msid found in host table to initial clustering notification, orphan msid: " + orphanMsid); s_logger.info("Add orphan management server msid found in host table to initial clustering notification, orphan msid: " + orphanMsid);
inactiveList.add(new ManagementServerHostVO(orphanMsid, 0, "orphan", 0, new Date())); inactiveList.add(new ManagementServerHostVO(orphanMsid, 0, "orphan", 0, new Date()));
}
} else {
s_logger.info("We are good, no orphan management server msid in host table is found");
}
if(inactiveList.size() > 0) {
if(s_logger.isInfoEnabled()) {
s_logger.info("Found " + inactiveList.size() + " inactive management server node based on timestamp");
for(ManagementServerHostVO host : inactiveList)
s_logger.info("management server node msid: " + host.getMsid() + ", name: " + host.getName() + ", service ip: " + host.getServiceIP() + ", version: " + host.getVersion());
}
List<ManagementServerHostVO> downHostList = new ArrayList<ManagementServerHostVO>();
for(ManagementServerHostVO host : inactiveList) {
if(!pingManagementNode(host)) {
s_logger.warn("Management node " + host.getId() + " is detected inactive by timestamp and also not pingable");
downHostList.add(host);
}
} }
if(downHostList.size() > 0)
this.queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeRemoved, downHostList));
} else { } else {
s_logger.info("No inactive management server node found"); s_logger.info("We are good, no orphan management server msid in host table is found");
}
if(inactiveList.size() > 0) {
if(s_logger.isInfoEnabled()) {
s_logger.info("Found " + inactiveList.size() + " inactive management server node based on timestamp");
for(ManagementServerHostVO host : inactiveList)
s_logger.info("management server node msid: " + host.getMsid() + ", name: " + host.getName() + ", service ip: " + host.getServiceIP() + ", version: " + host.getVersion());
}
List<ManagementServerHostVO> downHostList = new ArrayList<ManagementServerHostVO>();
for(ManagementServerHostVO host : inactiveList) {
if(!pingManagementNode(host)) {
s_logger.warn("Management node " + host.getId() + " is detected inactive by timestamp and also not pingable");
downHostList.add(host);
}
}
if(downHostList.size() > 0)
this.queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeRemoved, downHostList));
} else {
s_logger.info("No inactive management server node found");
} }
} }
@ -1019,7 +1020,7 @@ public class ClusterManagerImpl implements ClusterManager {
Profiler profiler = new Profiler(); Profiler profiler = new Profiler();
profiler.start(); profiler.start();
Profiler profilerQueryActiveList = new Profiler(); Profiler profilerQueryActiveList = new Profiler();
profilerQueryActiveList.start(); profilerQueryActiveList.start();
List<ManagementServerHostVO> currentList = _mshostDao.getActiveList(new Date(cutTime.getTime() - _heartbeatThreshold)); List<ManagementServerHostVO> currentList = _mshostDao.getActiveList(new Date(cutTime.getTime() - _heartbeatThreshold));
@ -1031,13 +1032,13 @@ public class ClusterManagerImpl implements ClusterManager {
List<ManagementServerHostVO> invalidatedNodeList = new ArrayList<ManagementServerHostVO>(); List<ManagementServerHostVO> invalidatedNodeList = new ArrayList<ManagementServerHostVO>();
if(_mshostId != null) { if(_mshostId != null) {
if(_mshostPeerDao.countStateSeenInPeers(_mshostId, _runId, ManagementServerHost.State.Down) > 0) { if(_mshostPeerDao.countStateSeenInPeers(_mshostId, _runId, ManagementServerHost.State.Down) > 0) {
String msg = "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation"; String msg = "We have detected that at least one management server peer reports that this management server is down, perform active fencing to avoid split-brain situation";
s_logger.error(msg); s_logger.error(msg);
throw new ActiveFencingException(msg); throw new ActiveFencingException(msg);
} }
// only if we have already attached to cluster, will we start to check leaving nodes // only if we have already attached to cluster, will we start to check leaving nodes
for(Map.Entry<Long, ManagementServerHostVO> entry : _activePeers.entrySet()) { for(Map.Entry<Long, ManagementServerHostVO> entry : _activePeers.entrySet()) {
@ -1070,7 +1071,7 @@ public class ClusterManagerImpl implements ClusterManager {
} }
} }
profilerSyncClusterInfo.stop(); profilerSyncClusterInfo.stop();
Profiler profilerInvalidatedNodeList = new Profiler(); Profiler profilerInvalidatedNodeList = new Profiler();
profilerInvalidatedNodeList.start(); profilerInvalidatedNodeList.start();
// process invalidated node list // process invalidated node list
@ -1134,16 +1135,16 @@ public class ClusterManagerImpl implements ClusterManager {
if(newNodeList.size() > 0) { if(newNodeList.size() > 0) {
this.queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeAdded, newNodeList)); this.queueNotification(new ClusterManagerMessage(ClusterManagerMessage.MessageType.nodeAdded, newNodeList));
} }
profiler.stop(); profiler.stop();
if(profiler.getDuration() >= this._heartbeatInterval) { if(profiler.getDuration() >= this._heartbeatInterval) {
if(s_logger.isDebugEnabled()) if(s_logger.isDebugEnabled())
s_logger.debug("Peer scan takes too long to finish. profiler: " + profiler.toString() s_logger.debug("Peer scan takes too long to finish. profiler: " + profiler.toString()
+ ", profilerQueryActiveList: " + profilerQueryActiveList.toString() + ", profilerQueryActiveList: " + profilerQueryActiveList.toString()
+ ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString() + ", profilerSyncClusterInfo: " + profilerSyncClusterInfo.toString()
+ ", profilerInvalidatedNodeList: " + profilerInvalidatedNodeList.toString() + ", profilerInvalidatedNodeList: " + profilerInvalidatedNodeList.toString()
+ ", profilerRemovedList: " + profilerRemovedList.toString()); + ", profilerRemovedList: " + profilerRemovedList.toString());
} }
} }
@ -1206,7 +1207,7 @@ public class ClusterManagerImpl implements ClusterManager {
if (s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
s_logger.info("Management server (host id : " + _mshostId + ") is being started at " + _clusterNodeIP + ":" + _currentServiceAdapter.getServicePort()); s_logger.info("Management server (host id : " + _mshostId + ") is being started at " + _clusterNodeIP + ":" + _currentServiceAdapter.getServicePort());
} }
_mshostPeerDao.clearPeerInfo(_mshostId); _mshostPeerDao.clearPeerInfo(_mshostId);
// use seperate thread for heartbeat updates // use seperate thread for heartbeat updates
@ -1294,8 +1295,8 @@ public class ClusterManagerImpl implements ClusterManager {
} }
for(int i = 0; i < DEFAULT_OUTGOING_WORKERS; i++) for(int i = 0; i < DEFAULT_OUTGOING_WORKERS; i++)
_executor.execute(getClusterPduSendingTask()); _executor.execute(getClusterPduSendingTask());
// notification task itself in turn works as a task dispatcher // notification task itself in turn works as a task dispatcher
_executor.execute(getClusterPduNotificationTask()); _executor.execute(getClusterPduNotificationTask());
@ -1309,9 +1310,9 @@ public class ClusterManagerImpl implements ClusterManager {
} }
_agentLBEnabled = Boolean.valueOf(_configDao.getValue(Config.AgentLbEnable.key())); _agentLBEnabled = Boolean.valueOf(_configDao.getValue(Config.AgentLbEnable.key()));
String connectedAgentsThreshold = configs.get("agent.load.threshold"); String connectedAgentsThreshold = configs.get("agent.load.threshold");
if (connectedAgentsThreshold != null) { if (connectedAgentsThreshold != null) {
_connectedAgentsThreshold = Double.parseDouble(connectedAgentsThreshold); _connectedAgentsThreshold = Double.parseDouble(connectedAgentsThreshold);
} }
@ -1365,7 +1366,7 @@ public class ClusterManagerImpl implements ClusterManager {
s_logger.info("ping management node cluster service can not be performed on self"); s_logger.info("ping management node cluster service can not be performed on self");
return false; return false;
} }
int retry = 10; int retry = 10;
while (--retry > 0) { while (--retry > 0) {
SocketChannel sch = null; SocketChannel sch = null;
@ -1381,7 +1382,7 @@ public class ClusterManagerImpl implements ClusterManager {
} catch (IOException e) { } catch (IOException e) {
if (e instanceof ConnectException) { if (e instanceof ConnectException) {
s_logger.error("Unable to ping management server at " + targetIp + ":" + mshost.getServicePort() + " due to ConnectException", e); s_logger.error("Unable to ping management server at " + targetIp + ":" + mshost.getServicePort() + " due to ConnectException", e);
return false; return false;
} }
} finally { } finally {
if (sch != null) { if (sch != null) {
@ -1397,7 +1398,7 @@ public class ClusterManagerImpl implements ClusterManager {
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
} }
} }
s_logger.error("Unable to ping management server at " + targetIp + ":" + mshost.getServicePort() + " after retries"); s_logger.error("Unable to ping management server at " + targetIp + ":" + mshost.getServicePort() + " after retries");
return false; return false;
} }
@ -1455,7 +1456,7 @@ public class ClusterManagerImpl implements ClusterManager {
public boolean isAgentRebalanceEnabled() { public boolean isAgentRebalanceEnabled() {
return _agentLBEnabled; return _agentLBEnabled;
} }
@Override @Override
public Boolean propagateResourceEvent(long agentId, ResourceState.Event event) throws AgentUnavailableException { public Boolean propagateResourceEvent(long agentId, ResourceState.Event event) throws AgentUnavailableException {
final String msPeer = getPeerName(agentId); final String msPeer = getPeerName(agentId);
@ -1480,7 +1481,7 @@ public class ClusterManagerImpl implements ClusterManager {
return answers[0].getResult(); return answers[0].getResult();
} }
@Override @Override
public boolean executeResourceUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException { public boolean executeResourceUserRequest(long hostId, ResourceState.Event event) throws AgentUnavailableException {
return _resourceMgr.executeUserRequest(hostId, event); return _resourceMgr.executeUserRequest(hostId, event);

View File

@ -1,153 +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.cluster;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.cluster.dao.StackMaidDao;
import com.cloud.cluster.dao.StackMaidDaoImpl;
import com.cloud.serializer.SerializerHelper;
import com.cloud.utils.CleanupDelegate;
import com.cloud.utils.db.Transaction;
public class StackMaid {
protected final static Logger s_logger = Logger.getLogger(StackMaid.class);
private static ThreadLocal<StackMaid> threadMaid = new ThreadLocal<StackMaid>();
private static long msid_setby_manager = 0;
private StackMaidDao maidDao = new StackMaidDaoImpl();
private int currentSeq = 0;
private Map<String, Object> context = new HashMap<String, Object>();
public static void init(long msid) {
msid_setby_manager = msid;
}
public static StackMaid current() {
StackMaid maid = threadMaid.get();
if(maid == null) {
maid = new StackMaid();
threadMaid.set(maid);
}
return maid;
}
public void registerContext(String key, Object contextObject) {
assert(!context.containsKey(key)) : "Context key has already been registered";
context.put(key, contextObject);
}
public Object getContext(String key) {
return context.get(key);
}
public void expungeMaidItem(long maidId) {
// this is a bit ugly, but when it is not loaded by component locator, this is just a workable way for now
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
try {
maidDao.expunge(maidId);
} finally {
txn.close();
}
}
public int push(String delegateClzName, Object context) {
assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded";
if(msid_setby_manager == 0)
s_logger.error("Fatal, make sure StackMaidManager is loaded");
return push(msid_setby_manager, delegateClzName, context);
}
public int push(long currentMsid, String delegateClzName, Object context) {
int savePoint = currentSeq;
maidDao.pushCleanupDelegate(currentMsid, currentSeq++, delegateClzName, context);
return savePoint;
}
public void pop(int savePoint) {
assert(msid_setby_manager != 0) : "Fatal, make sure StackMaidManager is loaded";
if(msid_setby_manager == 0)
s_logger.error("Fatal, make sure StackMaidManager is loaded");
pop(msid_setby_manager, savePoint);
}
public void pop() {
if(currentSeq > 0)
pop(currentSeq -1);
}
/**
* must be called within thread context
* @param currentMsid
*/
public void pop(long currentMsid, int savePoint) {
while(currentSeq > savePoint) {
maidDao.popCleanupDelegate(currentMsid);
currentSeq--;
}
}
public void exitCleanup() {
exitCleanup(msid_setby_manager);
}
public void exitCleanup(long currentMsid) {
if(currentSeq > 0) {
CheckPointVO maid = null;
while((maid = maidDao.popCleanupDelegate(currentMsid)) != null) {
doCleanup(maid);
}
currentSeq = 0;
}
context.clear();
}
public static boolean doCleanup(CheckPointVO maid) {
if(maid.getDelegate() != null) {
try {
Class<?> clz = Class.forName(maid.getDelegate());
Object delegate = clz.newInstance();
if(delegate instanceof CleanupDelegate) {
return ((CleanupDelegate)delegate).cleanup(SerializerHelper.fromSerializedString(maid.getContext()), maid);
} else {
assert(false);
}
} catch (final ClassNotFoundException e) {
s_logger.error("Unable to load StackMaid delegate class: " + maid.getDelegate(), e);
} catch (final SecurityException e) {
s_logger.error("Security excetion when loading resource: " + maid.getDelegate());
} catch (final IllegalArgumentException e) {
s_logger.error("Illegal argument excetion when loading resource: " + maid.getDelegate());
} catch (final InstantiationException e) {
s_logger.error("Instantiation excetion when loading resource: " + maid.getDelegate());
} catch (final IllegalAccessException e) {
s_logger.error("Illegal access exception when loading resource: " + maid.getDelegate());
}
return false;
}
return true;
}
}

View File

@ -34,7 +34,6 @@ import com.cloud.configuration.ResourceLimit;
import com.cloud.domain.dao.DomainDaoImpl; import com.cloud.domain.dao.DomainDaoImpl;
import com.cloud.exception.UnsupportedServiceException; import com.cloud.exception.UnsupportedServiceException;
import com.cloud.user.dao.AccountDaoImpl; import com.cloud.user.dao.AccountDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
@ -44,90 +43,90 @@ import com.cloud.utils.db.Transaction;
@Component @Component
@Local(value={ResourceCountDao.class}) @Local(value={ResourceCountDao.class})
public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long> implements ResourceCountDao { public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long> implements ResourceCountDao {
private SearchBuilder<ResourceCountVO> TypeSearch; private final SearchBuilder<ResourceCountVO> TypeSearch;
private SearchBuilder<ResourceCountVO> AccountSearch;
private SearchBuilder<ResourceCountVO> DomainSearch;
//protected final DomainDaoImpl _domainDao = ComponentLocator.inject(DomainDaoImpl.class);
//protected final AccountDaoImpl _accountDao = ComponentLocator.inject(AccountDaoImpl.class);
@Inject protected DomainDaoImpl _domainDao; private final SearchBuilder<ResourceCountVO> AccountSearch;
@Inject protected AccountDaoImpl _accountDao; private final SearchBuilder<ResourceCountVO> DomainSearch;
public ResourceCountDaoImpl() { //protected final DomainDaoImpl _domainDao = ComponentLocator.inject(DomainDaoImpl.class);
TypeSearch = createSearchBuilder(); //protected final AccountDaoImpl _accountDao = ComponentLocator.inject(AccountDaoImpl.class);
TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeSearch.and("accountId", TypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ); @Inject protected DomainDaoImpl _domainDao;
TypeSearch.and("domainId", TypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ); @Inject protected AccountDaoImpl _accountDao;
TypeSearch.done();
public ResourceCountDaoImpl() {
AccountSearch = createSearchBuilder(); TypeSearch = createSearchBuilder();
AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.NNULL); TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ);
AccountSearch.done(); TypeSearch.and("accountId", TypeSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
TypeSearch.and("domainId", TypeSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
DomainSearch = createSearchBuilder(); TypeSearch.done();
DomainSearch.and("domainId", DomainSearch.entity().getDomainId(), SearchCriteria.Op.NNULL);
DomainSearch.done(); AccountSearch = createSearchBuilder();
} AccountSearch.and("accountId", AccountSearch.entity().getAccountId(), SearchCriteria.Op.NNULL);
AccountSearch.done();
@Override
public ResourceCountVO findByOwnerAndType(long ownerId, ResourceOwnerType ownerType, ResourceType type) { DomainSearch = createSearchBuilder();
SearchCriteria<ResourceCountVO> sc = TypeSearch.create(); DomainSearch.and("domainId", DomainSearch.entity().getDomainId(), SearchCriteria.Op.NNULL);
sc.setParameters("type", type); DomainSearch.done();
}
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId); @Override
return findOneIncludingRemovedBy(sc); public ResourceCountVO findByOwnerAndType(long ownerId, ResourceOwnerType ownerType, ResourceType type) {
} else if (ownerType == ResourceOwnerType.Domain) { SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
sc.setParameters("domainId", ownerId); sc.setParameters("type", type);
if (ownerType == ResourceOwnerType.Account) {
sc.setParameters("accountId", ownerId);
return findOneIncludingRemovedBy(sc); return findOneIncludingRemovedBy(sc);
} else { } else if (ownerType == ResourceOwnerType.Domain) {
return null; sc.setParameters("domainId", ownerId);
} return findOneIncludingRemovedBy(sc);
} } else {
return null;
@Override }
public long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type) { }
ResourceCountVO vo = findByOwnerAndType(ownerId, ownerType, type);
if (vo != null) { @Override
return vo.getCount(); public long getResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type) {
} else { ResourceCountVO vo = findByOwnerAndType(ownerId, ownerType, type);
return 0; if (vo != null) {
} return vo.getCount();
} } else {
return 0;
@Override }
public void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, long count) { }
ResourceCountVO resourceCountVO = findByOwnerAndType(ownerId, ownerType, type);
@Override
public void setResourceCount(long ownerId, ResourceOwnerType ownerType, ResourceType type, long count) {
ResourceCountVO resourceCountVO = findByOwnerAndType(ownerId, ownerType, type);
if (count != resourceCountVO.getCount()) { if (count != resourceCountVO.getCount()) {
resourceCountVO.setCount(count); resourceCountVO.setCount(count);
update(resourceCountVO.getId(), resourceCountVO); update(resourceCountVO.getId(), resourceCountVO);
} }
} }
@Override @Deprecated @Override @Deprecated
public void updateDomainCount(long domainId, ResourceType type, boolean increment, long delta) { public void updateDomainCount(long domainId, ResourceType type, boolean increment, long delta) {
delta = increment ? delta : delta * -1; delta = increment ? delta : delta * -1;
ResourceCountVO resourceCountVO = findByOwnerAndType(domainId, ResourceOwnerType.Domain, type); ResourceCountVO resourceCountVO = findByOwnerAndType(domainId, ResourceOwnerType.Domain, type);
resourceCountVO.setCount(resourceCountVO.getCount() + delta); resourceCountVO.setCount(resourceCountVO.getCount() + delta);
update(resourceCountVO.getId(), resourceCountVO); update(resourceCountVO.getId(), resourceCountVO);
} }
@Override @Override
public boolean updateById(long id, boolean increment, long delta) { public boolean updateById(long id, boolean increment, long delta) {
delta = increment ? delta : delta * -1; delta = increment ? delta : delta * -1;
ResourceCountVO resourceCountVO = findById(id); ResourceCountVO resourceCountVO = findById(id);
resourceCountVO.setCount(resourceCountVO.getCount() + delta); resourceCountVO.setCount(resourceCountVO.getCount() + delta);
return update(resourceCountVO.getId(), resourceCountVO); return update(resourceCountVO.getId(), resourceCountVO);
} }
@Override @Override
public Set<Long> listRowsToUpdateForDomain(long domainId, ResourceType type) { public Set<Long> listRowsToUpdateForDomain(long domainId, ResourceType type) {
Set<Long> rowIds = new HashSet<Long>(); Set<Long> rowIds = new HashSet<Long>();
Set<Long> domainIdsToUpdate = _domainDao.getDomainParentIds(domainId); Set<Long> domainIdsToUpdate = _domainDao.getDomainParentIds(domainId);
for (Long domainIdToUpdate : domainIdsToUpdate) { for (Long domainIdToUpdate : domainIdsToUpdate) {
ResourceCountVO domainCountRecord = findByOwnerAndType(domainIdToUpdate, ResourceOwnerType.Domain, type); ResourceCountVO domainCountRecord = findByOwnerAndType(domainIdToUpdate, ResourceOwnerType.Domain, type);
if (domainCountRecord != null) { if (domainCountRecord != null) {
@ -135,34 +134,34 @@ public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long>
} }
} }
return rowIds; return rowIds;
} }
@Override @Override
public Set<Long> listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type) { public Set<Long> listAllRowsToUpdate(long ownerId, ResourceOwnerType ownerType, ResourceType type) {
Set<Long> rowIds = new HashSet<Long>(); Set<Long> rowIds = new HashSet<Long>();
if (ownerType == ResourceOwnerType.Account) { if (ownerType == ResourceOwnerType.Account) {
//get records for account //get records for account
ResourceCountVO accountCountRecord = findByOwnerAndType(ownerId, ResourceOwnerType.Account, type); ResourceCountVO accountCountRecord = findByOwnerAndType(ownerId, ResourceOwnerType.Account, type);
if (accountCountRecord != null) { if (accountCountRecord != null) {
rowIds.add(accountCountRecord.getId()); rowIds.add(accountCountRecord.getId());
} }
//get records for account's domain and all its parent domains //get records for account's domain and all its parent domains
rowIds.addAll(listRowsToUpdateForDomain(_accountDao.findByIdIncludingRemoved(ownerId).getDomainId(),type)); rowIds.addAll(listRowsToUpdateForDomain(_accountDao.findByIdIncludingRemoved(ownerId).getDomainId(),type));
} else if (ownerType == ResourceOwnerType.Domain) { } else if (ownerType == ResourceOwnerType.Domain) {
return listRowsToUpdateForDomain(ownerId, type); return listRowsToUpdateForDomain(ownerId, type);
} }
return rowIds; return rowIds;
} }
@Override @DB @Override @DB
public void createResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType){ public void createResourceCounts(long ownerId, ResourceLimit.ResourceOwnerType ownerType){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
ResourceType[] resourceTypes = Resource.ResourceType.values(); ResourceType[] resourceTypes = Resource.ResourceType.values();
for (ResourceType resourceType : resourceTypes) { for (ResourceType resourceType : resourceTypes) {
if (!resourceType.supportsOwner(ownerType)) { if (!resourceType.supportsOwner(ownerType)) {
@ -171,24 +170,24 @@ public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long>
ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType); ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, ownerId, ownerType);
persist(resourceCountVO); persist(resourceCountVO);
} }
txn.commit(); txn.commit();
} }
private List<ResourceCountVO> listByDomainId(long domainId) { private List<ResourceCountVO> listByDomainId(long domainId) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create(); SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
sc.setParameters("domainId", domainId); sc.setParameters("domainId", domainId);
return listBy(sc); return listBy(sc);
} }
private List<ResourceCountVO> listByAccountId(long accountId) { private List<ResourceCountVO> listByAccountId(long accountId) {
SearchCriteria<ResourceCountVO> sc = TypeSearch.create(); SearchCriteria<ResourceCountVO> sc = TypeSearch.create();
sc.setParameters("accountId", accountId); sc.setParameters("accountId", accountId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<ResourceCountVO> listByOwnerId(long ownerId, ResourceOwnerType ownerType) { public List<ResourceCountVO> listByOwnerId(long ownerId, ResourceOwnerType ownerType) {
if (ownerType == ResourceOwnerType.Account) { if (ownerType == ResourceOwnerType.Account) {
@ -199,26 +198,26 @@ public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long>
return new ArrayList<ResourceCountVO>(); return new ArrayList<ResourceCountVO>();
} }
} }
@Override @Override
public List<ResourceCountVO> listResourceCountByOwnerType(ResourceOwnerType ownerType) { public List<ResourceCountVO> listResourceCountByOwnerType(ResourceOwnerType ownerType) {
if (ownerType == ResourceOwnerType.Account) { if (ownerType == ResourceOwnerType.Account) {
return listBy(AccountSearch.create()); return listBy(AccountSearch.create());
} else if (ownerType == ResourceOwnerType.Domain) { } else if (ownerType == ResourceOwnerType.Domain) {
return listBy(DomainSearch.create()); return listBy(DomainSearch.create());
} else { } else {
return new ArrayList<ResourceCountVO>(); return new ArrayList<ResourceCountVO>();
} }
} }
@Override @Override
public ResourceCountVO persist(ResourceCountVO resourceCountVO){ public ResourceCountVO persist(ResourceCountVO resourceCountVO){
ResourceOwnerType ownerType = resourceCountVO.getResourceOwnerType(); ResourceOwnerType ownerType = resourceCountVO.getResourceOwnerType();
ResourceType resourceType = resourceCountVO.getType(); ResourceType resourceType = resourceCountVO.getType();
if (!resourceType.supportsOwner(ownerType)) { if (!resourceType.supportsOwner(ownerType)) {
throw new UnsupportedServiceException("Resource type " + resourceType + " is not supported for owner of type " + ownerType.getName()); throw new UnsupportedServiceException("Resource type " + resourceType + " is not supported for owner of type " + ownerType.getName());
} }
return super.persist(resourceCountVO); return super.persist(resourceCountVO);
} }
} }

View File

@ -49,7 +49,6 @@ import com.cloud.host.dao.HostDao;
import com.cloud.info.ConsoleProxyInfo; import com.cloud.info.ConsoleProxyInfo;
import com.cloud.network.Network; import com.cloud.network.Network;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.ConsoleProxyVO;
import com.cloud.vm.ReservationContext; import com.cloud.vm.ReservationContext;
import com.cloud.vm.UserVmVO; import com.cloud.vm.UserVmVO;
@ -87,9 +86,9 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
VirtualMachineManager _itMgr; VirtualMachineManager _itMgr;
@Inject @Inject
protected ConsoleProxyDao _cpDao; protected ConsoleProxyDao _cpDao;
@Inject ConfigurationDao _configDao; @Inject ConfigurationDao _configDao;
public int getVncPort(VMInstanceVO vm) { public int getVncPort(VMInstanceVO vm) {
if (vm.getHostId() == null) { if (vm.getHostId() == null) {
return -1; return -1;
@ -112,7 +111,7 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
if (value != null) { if (value != null) {
_consoleProxyUrlPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_URL_PORT); _consoleProxyUrlPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_URL_PORT);
} }
value = configs.get("consoleproxy.port"); value = configs.get("consoleproxy.port");
if (value != null) { if (value != null) {
_consoleProxyPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT); _consoleProxyPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT);
@ -126,10 +125,10 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
_instance = configs.get("instance.name"); _instance = configs.get("instance.name");
_consoleProxyUrlDomain = configs.get("consoleproxy.url.domain"); _consoleProxyUrlDomain = configs.get("consoleproxy.url.domain");
_listener = new ConsoleProxyListener(this); _listener = new ConsoleProxyListener(this);
_agentMgr.registerForHostEvents(_listener, true, true, false); _agentMgr.registerForHostEvents(_listener, true, true, false);
_itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this); _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);
if (s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
@ -177,20 +176,20 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
} }
publicIp = host.getPrivateIpAddress(); publicIp = host.getPrivateIpAddress();
} }
int urlPort = _consoleProxyUrlPort; int urlPort = _consoleProxyUrlPort;
if (host.getProxyPort() != null && host.getProxyPort().intValue() > 0) { if (host.getProxyPort() != null && host.getProxyPort().intValue() > 0) {
urlPort = host.getProxyPort().intValue(); urlPort = host.getProxyPort().intValue();
} }
return new ConsoleProxyInfo(_sslEnabled, publicIp, _consoleProxyPort, urlPort, _consoleProxyUrlDomain); return new ConsoleProxyInfo(_sslEnabled, publicIp, _consoleProxyPort, urlPort, _consoleProxyUrlDomain);
} else { } else {
s_logger.warn("Host that VM is running is no longer available, console access to VM " + userVmId + " will be temporarily unavailable."); s_logger.warn("Host that VM is running is no longer available, console access to VM " + userVmId + " will be temporarily unavailable.");
} }
return null; return null;
} }
@Override @Override
public void onLoadReport(ConsoleProxyLoadReportCommand cmd) { public void onLoadReport(ConsoleProxyLoadReportCommand cmd) {
} }
@ -273,16 +272,16 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
@Override @Override
public void setManagementState(ConsoleProxyManagementState state) { public void setManagementState(ConsoleProxyManagementState state) {
} }
@Override @Override
public ConsoleProxyManagementState getManagementState() { public ConsoleProxyManagementState getManagementState() {
return null; return null;
} }
@Override @Override
public void resumeLastManagementState() { public void resumeLastManagementState() {
} }
@Override @Override
public void startAgentHttpHandlerInVM(StartupProxyCommand startupCmd) { public void startAgentHttpHandlerInVM(StartupProxyCommand startupCmd) {
} }
@ -299,7 +298,7 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
} }
return VirtualMachineName.getConsoleProxyId(vmName); return VirtualMachineName.getConsoleProxyId(vmName);
} }
@Override @Override
public ConsoleProxyVO findByName(String name) { public ConsoleProxyVO findByName(String name) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -329,7 +328,7 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
@Override @Override
public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile<ConsoleProxyVO> profile) { public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile<ConsoleProxyVO> profile) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -346,7 +345,7 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
public void finalizeStop(VirtualMachineProfile<ConsoleProxyVO> profile, StopAnswer answer) { public void finalizeStop(VirtualMachineProfile<ConsoleProxyVO> profile, StopAnswer answer) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@Override @Override
public void finalizeExpunge(ConsoleProxyVO proxy) { public void finalizeExpunge(ConsoleProxyVO proxy) {
} }
@ -366,7 +365,7 @@ public class AgentBasedConsoleProxyManager implements ConsoleProxyManager, Virtu
//not supported //not supported
throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType()); throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
} }
@Override @Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) { public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
} }

View File

@ -27,9 +27,6 @@ import javax.naming.ConfigurationException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.ConsoleProxyVO;
import edu.emory.mathcs.backport.java.util.Collections; import edu.emory.mathcs.backport.java.util.Collections;
@ -37,45 +34,45 @@ import edu.emory.mathcs.backport.java.util.Collections;
@Component @Component
@Local(value={ConsoleProxyAllocator.class}) @Local(value={ConsoleProxyAllocator.class})
public class ConsoleProxyBalanceAllocator implements ConsoleProxyAllocator { public class ConsoleProxyBalanceAllocator implements ConsoleProxyAllocator {
private String _name; private String _name;
private final Random _rand = new Random(System.currentTimeMillis()); private final Random _rand = new Random(System.currentTimeMillis());
@Override
public ConsoleProxyVO allocProxy(List<ConsoleProxyVO> candidates, final Map<Long, Integer> loadInfo, long dataCenterId) {
if(candidates != null) {
List<ConsoleProxyVO> allocationList = new ArrayList<ConsoleProxyVO>();
for(ConsoleProxyVO proxy : candidates) {
allocationList.add(proxy);
}
Collections.sort(candidates, new Comparator<ConsoleProxyVO> () {
@Override
public int compare(ConsoleProxyVO x, ConsoleProxyVO y) {
Integer loadOfX = loadInfo.get(x.getId());
Integer loadOfY = loadInfo.get(y.getId());
if(loadOfX != null && loadOfY != null) { @Override
if(loadOfX < loadOfY) public ConsoleProxyVO allocProxy(List<ConsoleProxyVO> candidates, final Map<Long, Integer> loadInfo, long dataCenterId) {
return -1; if(candidates != null) {
else if(loadOfX > loadOfY)
return 1; List<ConsoleProxyVO> allocationList = new ArrayList<ConsoleProxyVO>();
return 0; for(ConsoleProxyVO proxy : candidates) {
} else if(loadOfX == null && loadOfY == null) { allocationList.add(proxy);
return 0; }
} else {
if(loadOfX == null) Collections.sort(candidates, new Comparator<ConsoleProxyVO> () {
return -1; @Override
return 1; public int compare(ConsoleProxyVO x, ConsoleProxyVO y) {
} Integer loadOfX = loadInfo.get(x.getId());
} Integer loadOfY = loadInfo.get(y.getId());
});
if(loadOfX != null && loadOfY != null) {
if(allocationList.size() > 0) if(loadOfX < loadOfY)
return allocationList.get(0); return -1;
} else if(loadOfX > loadOfY)
return null; return 1;
return 0;
} else if(loadOfX == null && loadOfY == null) {
return 0;
} else {
if(loadOfX == null)
return -1;
return 1;
}
}
});
if(allocationList.size() > 0)
return allocationList.get(0);
}
return null;
} }
@Override @Override
@ -83,7 +80,7 @@ public class ConsoleProxyBalanceAllocator implements ConsoleProxyAllocator {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public String getName() { public String getName() {
return _name; return _name;

View File

@ -19,7 +19,6 @@ package com.cloud.consoleproxy;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -32,6 +31,7 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import javax.persistence.Table; import javax.persistence.Table;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -55,7 +55,6 @@ import com.cloud.agent.api.proxy.StartConsoleProxyAgentHttpHandlerCommand;
import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;
import org.apache.cloudstack.api.ServerApiException;
import com.cloud.api.commands.DestroyConsoleProxyCmd; import com.cloud.api.commands.DestroyConsoleProxyCmd;
import com.cloud.certificate.dao.CertificateDao; import com.cloud.certificate.dao.CertificateDao;
import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManager;
@ -128,8 +127,6 @@ import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.GlobalLock;
@ -236,7 +233,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
RulesManager _rulesMgr; RulesManager _rulesMgr;
@Inject @Inject
IPAddressDao _ipAddressDao; IPAddressDao _ipAddressDao;
private ConsoleProxyListener _listener; private ConsoleProxyListener _listener;
private ServiceOfferingVO _serviceOffering; private ServiceOfferingVO _serviceOffering;
@ -269,7 +266,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private Map<Long, ZoneHostInfo> _zoneHostInfoMap; // map <zone id, info about running host in zone> private Map<Long, ZoneHostInfo> _zoneHostInfoMap; // map <zone id, info about running host in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneProxyCountMap; // map <zone id, info about proxy VMs count in zone> private Map<Long, ConsoleProxyLoadInfo> _zoneProxyCountMap; // map <zone id, info about proxy VMs count in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneVmCountMap; // map <zone id, info about running VMs count in zone> private Map<Long, ConsoleProxyLoadInfo> _zoneVmCountMap; // map <zone id, info about running VMs count in zone>
private String _hashKey; private String _hashKey;
private String _staticPublicIp; private String _staticPublicIp;
private int _staticPort; private int _staticPort;
@ -478,9 +475,9 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
assert (ksVo != null); assert (ksVo != null);
if (_staticPublicIp == null) { if (_staticPublicIp == null) {
return new ConsoleProxyInfo(proxy.isSslEnabled(), proxy.getPublicIpAddress(), _consoleProxyPort, proxy.getPort(), ksVo.getDomainSuffix()); return new ConsoleProxyInfo(proxy.isSslEnabled(), proxy.getPublicIpAddress(), _consoleProxyPort, proxy.getPort(), ksVo.getDomainSuffix());
} else { } else {
return new ConsoleProxyInfo(proxy.isSslEnabled(), _staticPublicIp, _consoleProxyPort, _staticPort, ksVo.getDomainSuffix()); return new ConsoleProxyInfo(proxy.isSslEnabled(), _staticPublicIp, _consoleProxyPort, _staticPort, ksVo.getDomainSuffix());
} }
} }
@ -809,10 +806,10 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private ConsoleProxyAllocator getCurrentAllocator() { private ConsoleProxyAllocator getCurrentAllocator() {
// for now, only one adapter is supported // for now, only one adapter is supported
for(ConsoleProxyAllocator allocator : _consoleProxyAllocators) { for(ConsoleProxyAllocator allocator : _consoleProxyAllocators) {
return allocator; return allocator;
} }
return null; return null;
} }
@ -903,26 +900,26 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
} }
if(!cmd.isReauthenticating()) { if(!cmd.isReauthenticating()) {
String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId()); String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId());
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket); s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
} }
if (!ticket.equals(ticketInUrl)) { if (!ticket.equals(ticketInUrl)) {
Date now = new Date(); Date now = new Date();
// considering of minute round-up // considering of minute round-up
String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000)); String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000));
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket); s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket);
} }
if (!minuteEarlyTicket.equals(ticketInUrl)) { if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + "," s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + ","
+ minuteEarlyTicket); + minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false); return new ConsoleAccessAuthenticationAnswer(cmd, false);
} }
} }
} }
if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) { if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) {
@ -959,38 +956,38 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
s_logger.warn("sid " + sid + " in url does not match stored sid " + vm.getVncPassword()); s_logger.warn("sid " + sid + " in url does not match stored sid " + vm.getVncPassword());
return new ConsoleAccessAuthenticationAnswer(cmd, false); return new ConsoleAccessAuthenticationAnswer(cmd, false);
} }
if(cmd.isReauthenticating()) { if(cmd.isReauthenticating()) {
ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true); ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true);
authenticationAnswer.setReauthenticating(true); authenticationAnswer.setReauthenticating(true);
s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info"); s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info");
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new
GetVncPortCommand(vm.getId(), vm.getInstanceName())); GetVncPortCommand(vm.getId(), vm.getInstanceName()));
if (answer != null && answer.getResult()) { if (answer != null && answer.getResult()) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress()); Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) { if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second() s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second()
+ ", tunnel session: " + parsedHostInfo.third()); + ", tunnel session: " + parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second()); authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third()); authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else { } else {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first() s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first()
+ ", port: " + answer.getPort()); + ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first()); authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort()); authenticationAnswer.setPort(answer.getPort());
} }
} else { } else {
s_logger.warn("Re-authentication request failed"); s_logger.warn("Re-authentication request failed");
authenticationAnswer.setSuccess(false); authenticationAnswer.setSuccess(false);
} }
return authenticationAnswer; return authenticationAnswer;
} }
@ -1198,11 +1195,11 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
} }
} else { } else {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
if (secondaryStorageHost != null) { if (secondaryStorageHost != null) {
s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage: " + secondaryStorageHost.getId()); s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage: " + secondaryStorageHost.getId());
} else { } else {
s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage."); s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage.");
} }
} }
} }
} }
@ -1411,7 +1408,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
result = result && _hostDao.remove(host.getId()); result = result && _hostDao.remove(host.getId());
} }
} }
return result; return result;
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
s_logger.warn("Unable to expunge " + proxy, e); s_logger.warn("Unable to expunge " + proxy, e);
@ -1514,11 +1511,11 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this); _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key())); boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
//check if there is a default service offering configured //check if there is a default service offering configured
String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key()); String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key());
if (cpvmSrvcOffIdStr != null) { if (cpvmSrvcOffIdStr != null) {
Long cpvmSrvcOffId = null; Long cpvmSrvcOffId = null;
try { try {
cpvmSrvcOffId = _identityDao.getIdentityId(DiskOfferingVO.class.getAnnotation(Table.class).name(),cpvmSrvcOffIdStr); cpvmSrvcOffId = _identityDao.getIdentityId(DiskOfferingVO.class.getAnnotation(Table.class).name(),cpvmSrvcOffIdStr);
@ -1532,8 +1529,8 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
} }
if(_serviceOffering == null || !_serviceOffering.getSystemUse()){ if(_serviceOffering == null || !_serviceOffering.getSystemUse()){
int ramSize = NumbersUtil.parseInt(_configDao.getValue("console.ram.size"), DEFAULT_PROXY_VM_RAMSIZE); int ramSize = NumbersUtil.parseInt(_configDao.getValue("console.ram.size"), DEFAULT_PROXY_VM_RAMSIZE);
int cpuFreq = NumbersUtil.parseInt(_configDao.getValue("console.cpu.mhz"), DEFAULT_PROXY_VM_CPUMHZ); int cpuFreq = NumbersUtil.parseInt(_configDao.getValue("console.cpu.mhz"), DEFAULT_PROXY_VM_CPUMHZ);
_serviceOffering = new ServiceOfferingVO("System Offering For Console Proxy", 1, ramSize, cpuFreq, 0, 0, false, null, useLocalStorage, true, null, true, VirtualMachine.Type.ConsoleProxy, true); _serviceOffering = new ServiceOfferingVO("System Offering For Console Proxy", 1, ramSize, cpuFreq, 0, 0, false, null, useLocalStorage, true, null, true, VirtualMachine.Type.ConsoleProxy, true);
_serviceOffering.setUniqueName(ServiceOffering.consoleProxyDefaultOffUniqueName); _serviceOffering.setUniqueName(ServiceOffering.consoleProxyDefaultOffUniqueName);
_serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering); _serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering);
@ -1552,7 +1549,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_staticPublicIp = _configDao.getValue("consoleproxy.static.publicIp"); _staticPublicIp = _configDao.getValue("consoleproxy.static.publicIp");
if (_staticPublicIp != null) { if (_staticPublicIp != null) {
_staticPort = NumbersUtil.parseInt(_configDao.getValue("consoleproxy.static.port"), 8443); _staticPort = NumbersUtil.parseInt(_configDao.getValue("consoleproxy.static.port"), 8443);
} }
if (s_logger.isInfoEnabled()) { if (s_logger.isInfoEnabled()) {
@ -2011,7 +2008,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
sc.addAnd(sc.getEntity().getName(), Op.EQ, name); sc.addAnd(sc.getEntity().getName(), Op.EQ, name);
return sc.find(); return sc.find();
} }
public String getHashKey() { 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 // give us the same key
@ -2036,8 +2033,8 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
//not supported //not supported
throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType()); throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
} }
@Override @Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) { public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
} }
} }

View File

@ -30,7 +30,6 @@ import com.cloud.host.Host.Type;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.info.ConsoleProxyInfo; import com.cloud.info.ConsoleProxyInfo;
import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceManager;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.ConsoleProxyDao;
@ -41,31 +40,31 @@ public class StaticConsoleProxyManager extends AgentBasedConsoleProxyManager imp
@Inject ConsoleProxyDao _proxyDao; @Inject ConsoleProxyDao _proxyDao;
@Inject ResourceManager _resourceMgr; @Inject ResourceManager _resourceMgr;
@Inject ConfigurationDao _configDao; @Inject ConfigurationDao _configDao;
@Override @Override
protected HostVO findHost(VMInstanceVO vm) { protected HostVO findHost(VMInstanceVO vm) {
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByType(Type.ConsoleProxy, vm.getDataCenterIdToDeployIn()); List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByType(Type.ConsoleProxy, vm.getDataCenterIdToDeployIn());
return hosts.isEmpty() ? null : hosts.get(0); return hosts.isEmpty() ? null : hosts.get(0);
} }
@Override @Override
public ConsoleProxyInfo assignProxy(long dataCenterId, long userVmId) { public ConsoleProxyInfo assignProxy(long dataCenterId, long userVmId) {
return new ConsoleProxyInfo(false, _ip, _consoleProxyPort, _consoleProxyUrlPort, _consoleProxyUrlDomain); return new ConsoleProxyInfo(false, _ip, _consoleProxyPort, _consoleProxyUrlPort, _consoleProxyUrlDomain);
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params); super.configure(name, params);
Map<String, String> dbParams = _configDao.getConfiguration("ManagementServer", params); Map<String, String> dbParams = _configDao.getConfiguration("ManagementServer", params);
_ip = dbParams.get("public.ip"); _ip = dbParams.get("public.ip");
if (_ip == null) { if (_ip == null) {
_ip = "127.0.0.1"; _ip = "127.0.0.1";
} }
return true; return true;
} }
} }

View File

@ -33,7 +33,6 @@ import com.cloud.dc.ClusterVO;
import com.cloud.dc.HostPodVO; import com.cloud.dc.HostPodVO;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Grouping; import com.cloud.org.Grouping;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder;
@ -53,73 +52,73 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
protected final SearchBuilder<ClusterVO> AvailHyperSearch; protected final SearchBuilder<ClusterVO> AvailHyperSearch;
protected final SearchBuilder<ClusterVO> ZoneSearch; protected final SearchBuilder<ClusterVO> ZoneSearch;
protected final SearchBuilder<ClusterVO> ZoneHyTypeSearch; protected final SearchBuilder<ClusterVO> ZoneHyTypeSearch;
private static final String GET_POD_CLUSTER_MAP_PREFIX = "SELECT pod_id, id FROM cloud.cluster WHERE cluster.id IN( "; private static final String GET_POD_CLUSTER_MAP_PREFIX = "SELECT pod_id, id FROM cloud.cluster WHERE cluster.id IN( ";
private static final String GET_POD_CLUSTER_MAP_SUFFIX = " )"; private static final String GET_POD_CLUSTER_MAP_SUFFIX = " )";
@Inject @Inject
protected HostPodDao _hostPodDao; protected HostPodDao _hostPodDao;
public ClusterDaoImpl() { public ClusterDaoImpl() {
super(); super();
HyTypeWithoutGuidSearch = createSearchBuilder(); HyTypeWithoutGuidSearch = createSearchBuilder();
HyTypeWithoutGuidSearch.and("hypervisorType", HyTypeWithoutGuidSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); HyTypeWithoutGuidSearch.and("hypervisorType", HyTypeWithoutGuidSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ);
HyTypeWithoutGuidSearch.and("guid", HyTypeWithoutGuidSearch.entity().getGuid(), SearchCriteria.Op.NULL); HyTypeWithoutGuidSearch.and("guid", HyTypeWithoutGuidSearch.entity().getGuid(), SearchCriteria.Op.NULL);
HyTypeWithoutGuidSearch.done(); HyTypeWithoutGuidSearch.done();
ZoneHyTypeSearch = createSearchBuilder(); ZoneHyTypeSearch = createSearchBuilder();
ZoneHyTypeSearch.and("hypervisorType", ZoneHyTypeSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ); ZoneHyTypeSearch.and("hypervisorType", ZoneHyTypeSearch.entity().getHypervisorType(), SearchCriteria.Op.EQ);
ZoneHyTypeSearch.and("dataCenterId", ZoneHyTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneHyTypeSearch.and("dataCenterId", ZoneHyTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneHyTypeSearch.done(); ZoneHyTypeSearch.done();
PodSearch = createSearchBuilder(); PodSearch = createSearchBuilder();
PodSearch.and("pod", PodSearch.entity().getPodId(), SearchCriteria.Op.EQ); PodSearch.and("pod", PodSearch.entity().getPodId(), SearchCriteria.Op.EQ);
PodSearch.and("name", PodSearch.entity().getName(), SearchCriteria.Op.EQ); PodSearch.and("name", PodSearch.entity().getName(), SearchCriteria.Op.EQ);
PodSearch.done(); PodSearch.done();
ZoneSearch = createSearchBuilder(); ZoneSearch = createSearchBuilder();
ZoneSearch.and("dataCenterId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneSearch.and("dataCenterId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneSearch.groupBy(ZoneSearch.entity().getHypervisorType()); ZoneSearch.groupBy(ZoneSearch.entity().getHypervisorType());
ZoneSearch.done(); ZoneSearch.done();
AvailHyperSearch = createSearchBuilder(); AvailHyperSearch = createSearchBuilder();
AvailHyperSearch.and("zoneId", AvailHyperSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AvailHyperSearch.and("zoneId", AvailHyperSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
AvailHyperSearch.select(null, Func.DISTINCT, AvailHyperSearch.entity().getHypervisorType()); AvailHyperSearch.select(null, Func.DISTINCT, AvailHyperSearch.entity().getHypervisorType());
AvailHyperSearch.done(); AvailHyperSearch.done();
} }
@Override @Override
public List<ClusterVO> listByZoneId(long zoneId) { public List<ClusterVO> listByZoneId(long zoneId) {
SearchCriteria<ClusterVO> sc = ZoneSearch.create(); SearchCriteria<ClusterVO> sc = ZoneSearch.create();
sc.setParameters("dataCenterId", zoneId); sc.setParameters("dataCenterId", zoneId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<ClusterVO> listByPodId(long podId) { public List<ClusterVO> listByPodId(long podId) {
SearchCriteria<ClusterVO> sc = PodSearch.create(); SearchCriteria<ClusterVO> sc = PodSearch.create();
sc.setParameters("pod", podId); sc.setParameters("pod", podId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public ClusterVO findBy(String name, long podId) { public ClusterVO findBy(String name, long podId) {
SearchCriteria<ClusterVO> sc = PodSearch.create(); SearchCriteria<ClusterVO> sc = PodSearch.create();
sc.setParameters("pod", podId); sc.setParameters("pod", podId);
sc.setParameters("name", name); sc.setParameters("name", name);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<ClusterVO> listByHyTypeWithoutGuid(String hyType) { public List<ClusterVO> listByHyTypeWithoutGuid(String hyType) {
SearchCriteria<ClusterVO> sc = HyTypeWithoutGuidSearch.create(); SearchCriteria<ClusterVO> sc = HyTypeWithoutGuidSearch.create();
sc.setParameters("hypervisorType", hyType); sc.setParameters("hypervisorType", hyType);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<ClusterVO> listByDcHyType(long dcId, String hyType) { public List<ClusterVO> listByDcHyType(long dcId, String hyType) {
SearchCriteria<ClusterVO> sc = ZoneHyTypeSearch.create(); SearchCriteria<ClusterVO> sc = ZoneHyTypeSearch.create();
@ -127,7 +126,7 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
sc.setParameters("hypervisorType", hyType); sc.setParameters("hypervisorType", hyType);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<HypervisorType> getAvailableHypervisorInZone(Long zoneId) { public List<HypervisorType> getAvailableHypervisorInZone(Long zoneId) {
SearchCriteria<ClusterVO> sc = AvailHyperSearch.create(); SearchCriteria<ClusterVO> sc = AvailHyperSearch.create();
@ -139,13 +138,13 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
for (ClusterVO cluster : clusters) { for (ClusterVO cluster : clusters) {
hypers.add(cluster.getHypervisorType()); hypers.add(cluster.getHypervisorType());
} }
return hypers; return hypers;
} }
@Override @Override
public Map<Long, List<Long>> getPodClusterIdMap(List<Long> clusterIds){ public Map<Long, List<Long>> getPodClusterIdMap(List<Long> clusterIds){
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
Map<Long, List<Long>> result = new HashMap<Long, List<Long>>(); Map<Long, List<Long>> result = new HashMap<Long, List<Long>>();
@ -158,20 +157,20 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
sql.delete(sql.length()-1, sql.length()); sql.delete(sql.length()-1, sql.length());
sql.append(GET_POD_CLUSTER_MAP_SUFFIX); sql.append(GET_POD_CLUSTER_MAP_SUFFIX);
} }
pstmt = txn.prepareAutoCloseStatement(sql.toString()); pstmt = txn.prepareAutoCloseStatement(sql.toString());
ResultSet rs = pstmt.executeQuery(); ResultSet rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
Long podId = rs.getLong(1); Long podId = rs.getLong(1);
Long clusterIdInPod = rs.getLong(2); Long clusterIdInPod = rs.getLong(2);
if(result.containsKey(podId)){ if(result.containsKey(podId)){
List<Long> clusterList = result.get(podId); List<Long> clusterList = result.get(podId);
clusterList.add(clusterIdInPod); clusterList.add(clusterIdInPod);
result.put(podId, clusterList); result.put(podId, clusterList);
}else{ }else{
List<Long> clusterList = new ArrayList<Long>(); List<Long> clusterList = new ArrayList<Long>();
clusterList.add(clusterIdInPod); clusterList.add(clusterIdInPod);
result.put(podId, clusterList); result.put(podId, clusterList);
} }
} }
return result; return result;
@ -181,49 +180,49 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
throw new CloudRuntimeException("Caught: " + GET_POD_CLUSTER_MAP_PREFIX, e); throw new CloudRuntimeException("Caught: " + GET_POD_CLUSTER_MAP_PREFIX, e);
} }
} }
@Override @Override
public List<Long> listDisabledClusters(long zoneId, Long podId) { public List<Long> listDisabledClusters(long zoneId, Long podId) {
GenericSearchBuilder<ClusterVO, Long> clusterIdSearch = createSearchBuilder(Long.class); GenericSearchBuilder<ClusterVO, Long> clusterIdSearch = createSearchBuilder(Long.class);
clusterIdSearch.selectField(clusterIdSearch.entity().getId()); clusterIdSearch.selectField(clusterIdSearch.entity().getId());
clusterIdSearch.and("dataCenterId", clusterIdSearch.entity().getDataCenterId(), Op.EQ); clusterIdSearch.and("dataCenterId", clusterIdSearch.entity().getDataCenterId(), Op.EQ);
if(podId != null){ if(podId != null){
clusterIdSearch.and("podId", clusterIdSearch.entity().getPodId(), Op.EQ); clusterIdSearch.and("podId", clusterIdSearch.entity().getPodId(), Op.EQ);
} }
clusterIdSearch.and("allocationState", clusterIdSearch.entity().getAllocationState(), Op.EQ); clusterIdSearch.and("allocationState", clusterIdSearch.entity().getAllocationState(), Op.EQ);
clusterIdSearch.done(); clusterIdSearch.done();
SearchCriteria<Long> sc = clusterIdSearch.create(); SearchCriteria<Long> sc = clusterIdSearch.create();
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
if (podId != null) { if (podId != null) {
sc.addAnd("podId", SearchCriteria.Op.EQ, podId); sc.addAnd("podId", SearchCriteria.Op.EQ, podId);
} }
sc.addAnd("allocationState", SearchCriteria.Op.EQ, Grouping.AllocationState.Disabled); sc.addAnd("allocationState", SearchCriteria.Op.EQ, Grouping.AllocationState.Disabled);
return customSearch(sc, null); return customSearch(sc, null);
} }
@Override @Override
public List<Long> listClustersWithDisabledPods(long zoneId) { public List<Long> listClustersWithDisabledPods(long zoneId) {
GenericSearchBuilder<HostPodVO, Long> disabledPodIdSearch = _hostPodDao.createSearchBuilder(Long.class);
disabledPodIdSearch.selectField(disabledPodIdSearch.entity().getId());
disabledPodIdSearch.and("dataCenterId", disabledPodIdSearch.entity().getDataCenterId(), Op.EQ);
disabledPodIdSearch.and("allocationState", disabledPodIdSearch.entity().getAllocationState(), Op.EQ);
GenericSearchBuilder<ClusterVO, Long> clusterIdSearch = createSearchBuilder(Long.class); GenericSearchBuilder<HostPodVO, Long> disabledPodIdSearch = _hostPodDao.createSearchBuilder(Long.class);
clusterIdSearch.selectField(clusterIdSearch.entity().getId()); disabledPodIdSearch.selectField(disabledPodIdSearch.entity().getId());
clusterIdSearch.join("disabledPodIdSearch", disabledPodIdSearch, clusterIdSearch.entity().getPodId(), disabledPodIdSearch.entity().getId(), JoinBuilder.JoinType.INNER); disabledPodIdSearch.and("dataCenterId", disabledPodIdSearch.entity().getDataCenterId(), Op.EQ);
clusterIdSearch.done(); disabledPodIdSearch.and("allocationState", disabledPodIdSearch.entity().getAllocationState(), Op.EQ);
GenericSearchBuilder<ClusterVO, Long> clusterIdSearch = createSearchBuilder(Long.class);
SearchCriteria<Long> sc = clusterIdSearch.create(); clusterIdSearch.selectField(clusterIdSearch.entity().getId());
clusterIdSearch.join("disabledPodIdSearch", disabledPodIdSearch, clusterIdSearch.entity().getPodId(), disabledPodIdSearch.entity().getId(), JoinBuilder.JoinType.INNER);
clusterIdSearch.done();
SearchCriteria<Long> sc = clusterIdSearch.create();
sc.setJoinParameters("disabledPodIdSearch", "dataCenterId", zoneId); sc.setJoinParameters("disabledPodIdSearch", "dataCenterId", zoneId);
sc.setJoinParameters("disabledPodIdSearch", "allocationState", Grouping.AllocationState.Disabled); sc.setJoinParameters("disabledPodIdSearch", "allocationState", Grouping.AllocationState.Disabled);
return customSearch(sc, null); return customSearch(sc, null);
} }
@Override @Override
public boolean remove(Long id) { public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -231,7 +230,7 @@ public class ClusterDaoImpl extends GenericDaoBase<ClusterVO, Long> implements C
ClusterVO cluster = createForUpdate(); ClusterVO cluster = createForUpdate();
cluster.setName(null); cluster.setName(null);
cluster.setGuid(null); cluster.setGuid(null);
update(id, cluster); update(id, cluster);
boolean result = super.remove(id); boolean result = super.remove(id);

View File

@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -37,7 +38,6 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.VMInstanceDaoImpl; import com.cloud.vm.dao.VMInstanceDaoImpl;
@ -46,32 +46,32 @@ import com.cloud.vm.dao.VMInstanceDaoImpl;
@Local(value={HostPodDao.class}) @Local(value={HostPodDao.class})
public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements HostPodDao { public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements HostPodDao {
private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class); private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class);
@Inject VMInstanceDaoImpl _vmDao;
protected SearchBuilder<HostPodVO> DataCenterAndNameSearch;
protected SearchBuilder<HostPodVO> DataCenterIdSearch; protected SearchBuilder<HostPodVO> DataCenterAndNameSearch;
protected SearchBuilder<HostPodVO> DataCenterIdSearch;
protected HostPodDaoImpl() {
DataCenterAndNameSearch = createSearchBuilder(); protected HostPodDaoImpl() {
DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); DataCenterAndNameSearch = createSearchBuilder();
DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ); DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DataCenterAndNameSearch.done(); DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ);
DataCenterAndNameSearch.done();
DataCenterIdSearch = createSearchBuilder();
DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); DataCenterIdSearch = createSearchBuilder();
DataCenterIdSearch.done(); DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
} DataCenterIdSearch.done();
}
@Override
@Override
public List<HostPodVO> listByDataCenterId(long id) { public List<HostPodVO> listByDataCenterId(long id) {
SearchCriteria<HostPodVO> sc = DataCenterIdSearch.create(); SearchCriteria<HostPodVO> sc = DataCenterIdSearch.create();
sc.setParameters("dcId", id); sc.setParameters("dcId", id);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<HostPodVO> listByDataCenterIdVMTypeAndStates(long id, VirtualMachine.Type type, VirtualMachine.State... states) { public List<HostPodVO> listByDataCenterIdVMTypeAndStates(long id, VirtualMachine.Type type, VirtualMachine.State... states) {
final VMInstanceDaoImpl _vmDao = ComponentLocator.inject(VMInstanceDaoImpl.class);
SearchBuilder<VMInstanceVO> vmInstanceSearch = _vmDao.createSearchBuilder(); SearchBuilder<VMInstanceVO> vmInstanceSearch = _vmDao.createSearchBuilder();
vmInstanceSearch.and("type", vmInstanceSearch.entity().getType(), SearchCriteria.Op.EQ); vmInstanceSearch.and("type", vmInstanceSearch.entity().getType(), SearchCriteria.Op.EQ);
vmInstanceSearch.and("states", vmInstanceSearch.entity().getState(), SearchCriteria.Op.IN); vmInstanceSearch.and("states", vmInstanceSearch.entity().getState(), SearchCriteria.Op.IN);
@ -90,51 +90,51 @@ public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements H
return listBy(sc); return listBy(sc);
} }
@Override @Override
public HostPodVO findByName(String name, long dcId) { public HostPodVO findByName(String name, long dcId) {
SearchCriteria<HostPodVO> sc = DataCenterAndNameSearch.create(); SearchCriteria<HostPodVO> sc = DataCenterAndNameSearch.create();
sc.setParameters("dc", dcId); sc.setParameters("dc", dcId);
sc.setParameters("name", name); sc.setParameters("name", name);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public HashMap<Long, List<Object>> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) { public HashMap<Long, List<Object>> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) {
HashMap<Long, List<Object>> currentPodCidrSubnets = new HashMap<Long, List<Object>>(); HashMap<Long, List<Object>> currentPodCidrSubnets = new HashMap<Long, List<Object>>();
String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL"; String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL";
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
try { try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql); PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();
while (rs.next()) { while (rs.next()) {
Long podId = rs.getLong("id"); Long podId = rs.getLong("id");
if (podId.longValue() == podIdToSkip) { if (podId.longValue() == podIdToSkip) {
continue; continue;
} }
String cidrAddress = rs.getString("cidr_address"); String cidrAddress = rs.getString("cidr_address");
long cidrSize = rs.getLong("cidr_size"); long cidrSize = rs.getLong("cidr_size");
List<Object> cidrPair = new ArrayList<Object>(); List<Object> cidrPair = new ArrayList<Object>();
cidrPair.add(0, cidrAddress); cidrPair.add(0, cidrAddress);
cidrPair.add(1, new Long(cidrSize)); cidrPair.add(1, new Long(cidrSize));
currentPodCidrSubnets.put(podId, cidrPair); currentPodCidrSubnets.put(podId, cidrPair);
} }
} catch (SQLException ex) { } catch (SQLException ex) {
s_logger.warn("DB exception " + ex.getMessage(), ex); s_logger.warn("DB exception " + ex.getMessage(), ex);
return null; return null;
} }
return currentPodCidrSubnets; return currentPodCidrSubnets;
} }
@Override @Override
public boolean remove(Long id) { public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
HostPodVO pod = createForUpdate(); HostPodVO pod = createForUpdate();
pod.setName(null); pod.setName(null);
update(id, pod); update(id, pod);
boolean result = super.remove(id); boolean result = super.remove(id);
@ -150,11 +150,11 @@ public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements H
podIdSearch.and("allocationState", podIdSearch.entity().getAllocationState(), Op.EQ); podIdSearch.and("allocationState", podIdSearch.entity().getAllocationState(), Op.EQ);
podIdSearch.done(); podIdSearch.done();
SearchCriteria<Long> sc = podIdSearch.create(); SearchCriteria<Long> sc = podIdSearch.create();
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId); sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
sc.addAnd("allocationState", SearchCriteria.Op.EQ, Grouping.AllocationState.Disabled); sc.addAnd("allocationState", SearchCriteria.Op.EQ, Grouping.AllocationState.Disabled);
return customSearch(sc, null); return customSearch(sc, null);
} }
} }

View File

@ -36,7 +36,6 @@ import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO; import com.cloud.dc.VlanVO;
import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder;
@ -48,56 +47,56 @@ import com.cloud.utils.exception.CloudRuntimeException;
@Component @Component
@Local(value={VlanDao.class}) @Local(value={VlanDao.class})
public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao { public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao {
private final String FindZoneWideVlans = "SELECT * FROM vlan WHERE data_center_id=? and vlan_type=? and vlan_id!=? and id not in (select vlan_db_id from account_vlan_map)";
protected SearchBuilder<VlanVO> ZoneVlanIdSearch;
protected SearchBuilder<VlanVO> ZoneSearch;
protected SearchBuilder<VlanVO> ZoneTypeSearch;
protected SearchBuilder<VlanVO> ZoneTypeAllPodsSearch;
protected SearchBuilder<VlanVO> ZoneTypePodSearch;
protected SearchBuilder<VlanVO> ZoneVlanSearch;
protected SearchBuilder<VlanVO> NetworkVlanSearch;
protected SearchBuilder<VlanVO> PhysicalNetworkVlanSearch;
@Inject protected PodVlanMapDao _podVlanMapDao; private final String FindZoneWideVlans = "SELECT * FROM vlan WHERE data_center_id=? and vlan_type=? and vlan_id!=? and id not in (select vlan_db_id from account_vlan_map)";
@Inject protected AccountVlanMapDao _accountVlanMapDao;
@Inject protected IPAddressDao _ipAddressDao; protected SearchBuilder<VlanVO> ZoneVlanIdSearch;
protected SearchBuilder<VlanVO> ZoneSearch;
protected SearchBuilder<VlanVO> ZoneTypeSearch;
protected SearchBuilder<VlanVO> ZoneTypeAllPodsSearch;
protected SearchBuilder<VlanVO> ZoneTypePodSearch;
protected SearchBuilder<VlanVO> ZoneVlanSearch;
protected SearchBuilder<VlanVO> NetworkVlanSearch;
protected SearchBuilder<VlanVO> PhysicalNetworkVlanSearch;
@Inject protected PodVlanMapDao _podVlanMapDao;
@Inject protected AccountVlanMapDao _accountVlanMapDao;
@Inject protected IPAddressDao _ipAddressDao;
@Override @Override
public VlanVO findByZoneAndVlanId(long zoneId, String vlanId) { public VlanVO findByZoneAndVlanId(long zoneId, String vlanId) {
SearchCriteria<VlanVO> sc = ZoneVlanIdSearch.create(); SearchCriteria<VlanVO> sc = ZoneVlanIdSearch.create();
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanId", vlanId); sc.setParameters("vlanId", vlanId);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<VlanVO> listByZone(long zoneId) { public List<VlanVO> listByZone(long zoneId) {
SearchCriteria<VlanVO> sc = ZoneSearch.create(); SearchCriteria<VlanVO> sc = ZoneSearch.create();
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
return listBy(sc); return listBy(sc);
} }
public VlanDaoImpl() { public VlanDaoImpl() {
ZoneVlanIdSearch = createSearchBuilder(); ZoneVlanIdSearch = createSearchBuilder();
ZoneVlanIdSearch.and("zoneId", ZoneVlanIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneVlanIdSearch.and("zoneId", ZoneVlanIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneVlanIdSearch.and("vlanId", ZoneVlanIdSearch.entity().getVlanTag(), SearchCriteria.Op.EQ); ZoneVlanIdSearch.and("vlanId", ZoneVlanIdSearch.entity().getVlanTag(), SearchCriteria.Op.EQ);
ZoneVlanIdSearch.done(); ZoneVlanIdSearch.done();
ZoneSearch = createSearchBuilder(); ZoneSearch = createSearchBuilder();
ZoneSearch.and("zoneId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneSearch.and("zoneId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneSearch.done(); ZoneSearch.done();
ZoneTypeSearch = createSearchBuilder(); ZoneTypeSearch = createSearchBuilder();
ZoneTypeSearch.and("zoneId", ZoneTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneTypeSearch.and("zoneId", ZoneTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypeSearch.and("vlanType", ZoneTypeSearch.entity().getVlanType(), SearchCriteria.Op.EQ); ZoneTypeSearch.and("vlanType", ZoneTypeSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
ZoneTypeSearch.done(); ZoneTypeSearch.done();
NetworkVlanSearch = createSearchBuilder(); NetworkVlanSearch = createSearchBuilder();
NetworkVlanSearch.and("networkOfferingId", NetworkVlanSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); NetworkVlanSearch.and("networkOfferingId", NetworkVlanSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
NetworkVlanSearch.done(); NetworkVlanSearch.done();
PhysicalNetworkVlanSearch = createSearchBuilder(); PhysicalNetworkVlanSearch = createSearchBuilder();
PhysicalNetworkVlanSearch.and("physicalNetworkId", PhysicalNetworkVlanSearch.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ); PhysicalNetworkVlanSearch.and("physicalNetworkId", PhysicalNetworkVlanSearch.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
PhysicalNetworkVlanSearch.done(); PhysicalNetworkVlanSearch.done();
@ -105,211 +104,211 @@ public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao
@Override @Override
public List<VlanVO> listZoneWideVlans(long zoneId, VlanType vlanType, String vlanId){ public List<VlanVO> listZoneWideVlans(long zoneId, VlanType vlanType, String vlanId){
SearchCriteria<VlanVO> sc = ZoneVlanSearch.create(); SearchCriteria<VlanVO> sc = ZoneVlanSearch.create();
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanId", vlanId); sc.setParameters("vlanId", vlanId);
sc.setParameters("vlanType", vlanType); sc.setParameters("vlanType", vlanType);
return listBy(sc);
}
@Override
public List<VlanVO> listByZoneAndType(long zoneId, VlanType vlanType) {
SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", vlanType);
return listBy(sc); return listBy(sc);
} }
@Override
@Override public List<VlanVO> listByZoneAndType(long zoneId, VlanType vlanType) {
SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", vlanType);
return listBy(sc);
}
@Override
public List<VlanVO> listByType(VlanType vlanType) { public List<VlanVO> listByType(VlanType vlanType) {
SearchCriteria<VlanVO> sc = ZoneTypeSearch.create(); SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
sc.setParameters("vlanType", vlanType); sc.setParameters("vlanType", vlanType);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<VlanVO> listVlansForPod(long podId) { public List<VlanVO> listVlansForPod(long podId) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two
List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId); List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
List<VlanVO> result = new ArrayList<VlanVO>(); List<VlanVO> result = new ArrayList<VlanVO>();
for (PodVlanMapVO pvmvo: vlanMaps) { for (PodVlanMapVO pvmvo: vlanMaps) {
result.add(findById(pvmvo.getVlanDbId())); result.add(findById(pvmvo.getVlanDbId()));
} }
return result; return result;
} }
@Override @Override
public List<VlanVO> listVlansForPodByType(long podId, VlanType vlanType) { public List<VlanVO> listVlansForPodByType(long podId, VlanType vlanType) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two) //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId); List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
List<VlanVO> result = new ArrayList<VlanVO>(); List<VlanVO> result = new ArrayList<VlanVO>();
for (PodVlanMapVO pvmvo: vlanMaps) { for (PodVlanMapVO pvmvo: vlanMaps) {
VlanVO vlan =findById(pvmvo.getVlanDbId()); VlanVO vlan =findById(pvmvo.getVlanDbId());
if (vlan.getVlanType() == vlanType) { if (vlan.getVlanType() == vlanType) {
result.add(vlan); result.add(vlan);
} }
} }
return result; return result;
} }
@Override
public List<VlanVO> listVlansForAccountByType(Long zoneId, long accountId, VlanType vlanType) {
//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
List<AccountVlanMapVO> vlanMaps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
List<VlanVO> result = new ArrayList<VlanVO>();
for (AccountVlanMapVO acvmvo: vlanMaps) {
VlanVO vlan =findById(acvmvo.getVlanDbId());
if (vlan.getVlanType() == vlanType && (zoneId == null || vlan.getDataCenterId() == zoneId)) {
result.add(vlan);
}
}
return result;
}
@Override @Override
public void addToPod(long podId, long vlanDbId) { public List<VlanVO> listVlansForAccountByType(Long zoneId, long accountId, VlanType vlanType) {
PodVlanMapVO pvmvo = new PodVlanMapVO(podId, vlanDbId); //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
_podVlanMapDao.persist(pvmvo); List<AccountVlanMapVO> vlanMaps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
List<VlanVO> result = new ArrayList<VlanVO>();
} for (AccountVlanMapVO acvmvo: vlanMaps) {
VlanVO vlan =findById(acvmvo.getVlanDbId());
if (vlan.getVlanType() == vlanType && (zoneId == null || vlan.getDataCenterId() == zoneId)) {
result.add(vlan);
}
}
return result;
}
@Override @Override
public boolean configure(String name, Map<String, Object> params) public void addToPod(long podId, long vlanDbId) {
throws ConfigurationException { PodVlanMapVO pvmvo = new PodVlanMapVO(podId, vlanDbId);
boolean result = super.configure(name, params); _podVlanMapDao.persist(pvmvo);
}
@Override
public boolean configure(String name, Map<String, Object> params)
throws ConfigurationException {
boolean result = super.configure(name, params);
ZoneTypeAllPodsSearch = createSearchBuilder(); ZoneTypeAllPodsSearch = createSearchBuilder();
ZoneTypeAllPodsSearch.and("zoneId", ZoneTypeAllPodsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneTypeAllPodsSearch.and("zoneId", ZoneTypeAllPodsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypeAllPodsSearch.and("vlanType", ZoneTypeAllPodsSearch.entity().getVlanType(), SearchCriteria.Op.EQ); ZoneTypeAllPodsSearch.and("vlanType", ZoneTypeAllPodsSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
SearchBuilder<PodVlanMapVO> PodVlanSearch = _podVlanMapDao.createSearchBuilder(); SearchBuilder<PodVlanMapVO> PodVlanSearch = _podVlanMapDao.createSearchBuilder();
PodVlanSearch.and("podId", PodVlanSearch.entity().getPodId(), SearchCriteria.Op.NNULL); PodVlanSearch.and("podId", PodVlanSearch.entity().getPodId(), SearchCriteria.Op.NNULL);
ZoneTypeAllPodsSearch.join("vlan", PodVlanSearch, PodVlanSearch.entity().getVlanDbId(), ZoneTypeAllPodsSearch.entity().getId(), JoinBuilder.JoinType.INNER); ZoneTypeAllPodsSearch.join("vlan", PodVlanSearch, PodVlanSearch.entity().getVlanDbId(), ZoneTypeAllPodsSearch.entity().getId(), JoinBuilder.JoinType.INNER);
ZoneTypeAllPodsSearch.done(); ZoneTypeAllPodsSearch.done();
PodVlanSearch.done(); PodVlanSearch.done();
ZoneTypePodSearch = createSearchBuilder(); ZoneTypePodSearch = createSearchBuilder();
ZoneTypePodSearch.and("zoneId", ZoneTypePodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneTypePodSearch.and("zoneId", ZoneTypePodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
ZoneTypePodSearch.and("vlanType", ZoneTypePodSearch.entity().getVlanType(), SearchCriteria.Op.EQ); ZoneTypePodSearch.and("vlanType", ZoneTypePodSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
SearchBuilder<PodVlanMapVO> PodVlanSearch2 = _podVlanMapDao.createSearchBuilder(); SearchBuilder<PodVlanMapVO> PodVlanSearch2 = _podVlanMapDao.createSearchBuilder();
PodVlanSearch2.and("podId", PodVlanSearch2.entity().getPodId(), SearchCriteria.Op.EQ); PodVlanSearch2.and("podId", PodVlanSearch2.entity().getPodId(), SearchCriteria.Op.EQ);
ZoneTypePodSearch.join("vlan", PodVlanSearch2, PodVlanSearch2.entity().getVlanDbId(), ZoneTypePodSearch.entity().getId(), JoinBuilder.JoinType.INNER); ZoneTypePodSearch.join("vlan", PodVlanSearch2, PodVlanSearch2.entity().getVlanDbId(), ZoneTypePodSearch.entity().getId(), JoinBuilder.JoinType.INNER);
PodVlanSearch2.done(); PodVlanSearch2.done();
ZoneTypePodSearch.done(); ZoneTypePodSearch.done();
return result; return result;
} }
private VlanVO findNextVlan(long zoneId, Vlan.VlanType vlanType) { private VlanVO findNextVlan(long zoneId, Vlan.VlanType vlanType) {
List<VlanVO> allVlans = listByZoneAndType(zoneId, vlanType); List<VlanVO> allVlans = listByZoneAndType(zoneId, vlanType);
List<VlanVO> emptyVlans = new ArrayList<VlanVO>(); List<VlanVO> emptyVlans = new ArrayList<VlanVO>();
List<VlanVO> fullVlans = new ArrayList<VlanVO>(); List<VlanVO> fullVlans = new ArrayList<VlanVO>();
// Try to find a VLAN that is partially allocated // Try to find a VLAN that is partially allocated
for (VlanVO vlan : allVlans) { for (VlanVO vlan : allVlans) {
long vlanDbId = vlan.getId(); long vlanDbId = vlan.getId();
int countOfAllocatedIps = _ipAddressDao.countIPs(zoneId, vlanDbId, true); int countOfAllocatedIps = _ipAddressDao.countIPs(zoneId, vlanDbId, true);
int countOfAllIps = _ipAddressDao.countIPs(zoneId, vlanDbId, false); int countOfAllIps = _ipAddressDao.countIPs(zoneId, vlanDbId, false);
if ((countOfAllocatedIps > 0) && (countOfAllocatedIps < countOfAllIps)) { if ((countOfAllocatedIps > 0) && (countOfAllocatedIps < countOfAllIps)) {
return vlan; return vlan;
} else if (countOfAllocatedIps == 0) { } else if (countOfAllocatedIps == 0) {
emptyVlans.add(vlan); emptyVlans.add(vlan);
} else if (countOfAllocatedIps == countOfAllIps) { } else if (countOfAllocatedIps == countOfAllIps) {
fullVlans.add(vlan); fullVlans.add(vlan);
} }
} }
if (emptyVlans.isEmpty()) { if (emptyVlans.isEmpty()) {
return null; return null;
} }
// Try to find an empty VLAN with the same tag/subnet as a VLAN that is full // Try to find an empty VLAN with the same tag/subnet as a VLAN that is full
for (VlanVO fullVlan : fullVlans) { for (VlanVO fullVlan : fullVlans) {
for (VlanVO emptyVlan : emptyVlans) { for (VlanVO emptyVlan : emptyVlans) {
if (fullVlan.getVlanTag().equals(emptyVlan.getVlanTag()) && if (fullVlan.getVlanTag().equals(emptyVlan.getVlanTag()) &&
fullVlan.getVlanGateway().equals(emptyVlan.getVlanGateway()) && fullVlan.getVlanGateway().equals(emptyVlan.getVlanGateway()) &&
fullVlan.getVlanNetmask().equals(emptyVlan.getVlanNetmask())) { fullVlan.getVlanNetmask().equals(emptyVlan.getVlanNetmask())) {
return emptyVlan; return emptyVlan;
} }
} }
} }
// Return a random empty VLAN // Return a random empty VLAN
return emptyVlans.get(0); return emptyVlans.get(0);
} }
@Override
public boolean zoneHasDirectAttachUntaggedVlans(long zoneId) {
SearchCriteria<VlanVO> sc = ZoneTypeAllPodsSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", VlanType.DirectAttached);
@Override
public boolean zoneHasDirectAttachUntaggedVlans(long zoneId) {
SearchCriteria<VlanVO> sc = ZoneTypeAllPodsSearch.create();
sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", VlanType.DirectAttached);
return listIncludingRemovedBy(sc).size() > 0; return listIncludingRemovedBy(sc).size() > 0;
} }
public Pair<String, VlanVO> assignPodDirectAttachIpAddress(long zoneId, public Pair<String, VlanVO> assignPodDirectAttachIpAddress(long zoneId,
long podId, long accountId, long domainId) { long podId, long accountId, long domainId) {
SearchCriteria<VlanVO> sc = ZoneTypePodSearch.create(); SearchCriteria<VlanVO> sc = ZoneTypePodSearch.create();
sc.setParameters("zoneId", zoneId); sc.setParameters("zoneId", zoneId);
sc.setParameters("vlanType", VlanType.DirectAttached); sc.setParameters("vlanType", VlanType.DirectAttached);
sc.setJoinParameters("vlan", "podId", podId); sc.setJoinParameters("vlan", "podId", podId);
VlanVO vlan = findOneIncludingRemovedBy(sc); VlanVO vlan = findOneIncludingRemovedBy(sc);
if (vlan == null) { if (vlan == null) {
return null; return null;
} }
return null; return null;
// String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress(); // String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
// if (ipAddress == null) { // if (ipAddress == null) {
// return null; // return null;
// } // }
// return new Pair<String, VlanVO>(ipAddress, vlan); // return new Pair<String, VlanVO>(ipAddress, vlan);
} }
@Override
@DB
public List<VlanVO> searchForZoneWideVlans(long dcId, String vlanType, String vlanId){
StringBuilder sql = new StringBuilder(FindZoneWideVlans);
Transaction txn = Transaction.currentTxn(); @Override
PreparedStatement pstmt = null; @DB
try { public List<VlanVO> searchForZoneWideVlans(long dcId, String vlanType, String vlanId){
pstmt = txn.prepareAutoCloseStatement(sql.toString());
pstmt.setLong(1, dcId);
pstmt.setString(2, vlanType);
pstmt.setString(3, vlanId);
ResultSet rs = pstmt.executeQuery();
List<VlanVO> zoneWideVlans = new ArrayList<VlanVO>();
while (rs.next()) { StringBuilder sql = new StringBuilder(FindZoneWideVlans);
zoneWideVlans.add(toEntityBean(rs, false));
} Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
return zoneWideVlans; try {
} catch (SQLException e) { pstmt = txn.prepareAutoCloseStatement(sql.toString());
throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e); pstmt.setLong(1, dcId);
} pstmt.setString(2, vlanType);
} pstmt.setString(3, vlanId);
@Override ResultSet rs = pstmt.executeQuery();
List<VlanVO> zoneWideVlans = new ArrayList<VlanVO>();
while (rs.next()) {
zoneWideVlans.add(toEntityBean(rs, false));
}
return zoneWideVlans;
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e);
}
}
@Override
public List<VlanVO> listVlansByNetworkId(long networkOfferingId) { public List<VlanVO> listVlansByNetworkId(long networkOfferingId) {
SearchCriteria<VlanVO> sc = NetworkVlanSearch.create(); SearchCriteria<VlanVO> sc = NetworkVlanSearch.create();
sc.setParameters("networkOfferingId", networkOfferingId); sc.setParameters("networkOfferingId", networkOfferingId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<VlanVO> listVlansByPhysicalNetworkId(long physicalNetworkId) { public List<VlanVO> listVlansByPhysicalNetworkId(long physicalNetworkId) {
SearchCriteria<VlanVO> sc = PhysicalNetworkVlanSearch.create(); SearchCriteria<VlanVO> sc = PhysicalNetworkVlanSearch.create();
sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("physicalNetworkId", physicalNetworkId);
return listBy(sc); return listBy(sc);
} }

View File

@ -18,7 +18,6 @@ package com.cloud.deploy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -74,7 +73,6 @@ import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.component.Adapters;
import com.cloud.vm.DiskProfile; import com.cloud.vm.DiskProfile;
import com.cloud.vm.ReservationContext; import com.cloud.vm.ReservationContext;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;
@ -106,7 +104,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
//@com.cloud.utils.component.Inject(adapter=StoragePoolAllocator.class) //@com.cloud.utils.component.Inject(adapter=StoragePoolAllocator.class)
@Inject protected List<StoragePoolAllocator> _storagePoolAllocators; @Inject protected List<StoragePoolAllocator> _storagePoolAllocators;
//@com.cloud.utils.component.Inject(adapter=HostAllocator.class) //@com.cloud.utils.component.Inject(adapter=HostAllocator.class)
@Inject protected List<HostAllocator> _hostAllocators; @Inject protected List<HostAllocator> _hostAllocators;
protected String _allocationAlgorithm = "random"; protected String _allocationAlgorithm = "random";
@ -115,7 +113,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
@Override @Override
public DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vmProfile, public DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vmProfile,
DeploymentPlan plan, ExcludeList avoid) DeploymentPlan plan, ExcludeList avoid)
throws InsufficientServerCapacityException { throws InsufficientServerCapacityException {
VirtualMachine vm = vmProfile.getVirtualMachine(); VirtualMachine vm = vmProfile.getVirtualMachine();
DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn()); DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
@ -126,7 +124,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
return null; return null;
} }
ServiceOffering offering = vmProfile.getServiceOffering(); ServiceOffering offering = vmProfile.getServiceOffering();
int cpu_requested = offering.getCpu() * offering.getSpeed(); int cpu_requested = offering.getCpu() * offering.getSpeed();
long ram_requested = offering.getRamSize() * 1024L * 1024L; long ram_requested = offering.getRamSize() * 1024L * 1024L;
@ -143,9 +141,9 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId()!=null ? "Yes": "No")); s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId()!=null ? "Yes": "No"));
} }
String haVmTag = (String)vmProfile.getParameter(VirtualMachineProfile.Param.HaTag); String haVmTag = (String)vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
if(plan.getHostId() != null && haVmTag == null){ if(plan.getHostId() != null && haVmTag == null){
Long hostIdSpecified = plan.getHostId(); Long hostIdSpecified = plan.getHostId();
if (s_logger.isDebugEnabled()){ if (s_logger.isDebugEnabled()){
@ -238,7 +236,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
s_logger.debug("Cannot choose the last host to deploy this VM "); s_logger.debug("Cannot choose the last host to deploy this VM ");
} }
List<Long> clusterList = new ArrayList<Long>(); List<Long> clusterList = new ArrayList<Long>();
if (plan.getClusterId() != null) { if (plan.getClusterId() != null) {
@ -272,7 +270,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
} else { } else {
s_logger.debug("Searching all possible resources under this Zone: "+ plan.getDataCenterId()); s_logger.debug("Searching all possible resources under this Zone: "+ plan.getDataCenterId());
boolean applyAllocationAtPods = Boolean.parseBoolean(_configDao.getValue(Config.ApplyAllocationAlgorithmToPods.key())); boolean applyAllocationAtPods = Boolean.parseBoolean(_configDao.getValue(Config.ApplyAllocationAlgorithmToPods.key()));
if(applyAllocationAtPods){ if(applyAllocationAtPods){
//start scan at all pods under this zone. //start scan at all pods under this zone.
@ -284,15 +282,15 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
} }
private DeployDestination scanPodsForDestination(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){ private DeployDestination scanPodsForDestination(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
ServiceOffering offering = vmProfile.getServiceOffering(); ServiceOffering offering = vmProfile.getServiceOffering();
int requiredCpu = offering.getCpu() * offering.getSpeed(); int requiredCpu = offering.getCpu() * offering.getSpeed();
long requiredRam = offering.getRamSize() * 1024L * 1024L; long requiredRam = offering.getRamSize() * 1024L * 1024L;
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key()); String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1); float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
//list pods under this zone by cpu and ram capacity //list pods under this zone by cpu and ram capacity
List<Long> prioritizedPodIds = new ArrayList<Long>(); List<Long> prioritizedPodIds = new ArrayList<Long>();
Pair<List<Long>, Map<Long, Double>> podCapacityInfo = listPodsByCapacity(plan.getDataCenterId(), requiredCpu, requiredRam, cpuOverprovisioningFactor); Pair<List<Long>, Map<Long, Double>> podCapacityInfo = listPodsByCapacity(plan.getDataCenterId(), requiredCpu, requiredRam, cpuOverprovisioningFactor);
@ -313,16 +311,16 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
podsWithCapacity.removeAll(disabledPods); podsWithCapacity.removeAll(disabledPods);
} }
} }
}else{ }else{
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("No pods found having a host with enough capacity, returning."); s_logger.debug("No pods found having a host with enough capacity, returning.");
} }
return null; return null;
} }
if(!podsWithCapacity.isEmpty()){ if(!podsWithCapacity.isEmpty()){
prioritizedPodIds = reorderPods(podCapacityInfo, vmProfile, plan); prioritizedPodIds = reorderPods(podCapacityInfo, vmProfile, plan);
//loop over pods //loop over pods
@ -345,9 +343,9 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
return null; return null;
} }
} }
private DeployDestination scanClustersForDestinationInZoneOrPod(long id, boolean isZone, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){ private DeployDestination scanClustersForDestinationInZoneOrPod(long id, boolean isZone, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
VirtualMachine vm = vmProfile.getVirtualMachine(); VirtualMachine vm = vmProfile.getVirtualMachine();
ServiceOffering offering = vmProfile.getServiceOffering(); ServiceOffering offering = vmProfile.getServiceOffering();
DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn()); DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
@ -355,7 +353,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
long requiredRam = offering.getRamSize() * 1024L * 1024L; long requiredRam = offering.getRamSize() * 1024L * 1024L;
String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key()); String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1); float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
//list clusters under this zone by cpu and ram capacity //list clusters under this zone by cpu and ram capacity
Pair<List<Long>, Map<Long, Double>> clusterCapacityInfo = listClustersByCapacity(id, requiredCpu, requiredRam, avoid, isZone, cpuOverprovisioningFactor); Pair<List<Long>, Map<Long, Double>> clusterCapacityInfo = listClustersByCapacity(id, requiredCpu, requiredRam, avoid, isZone, cpuOverprovisioningFactor);
List<Long> prioritizedClusterIds = clusterCapacityInfo.first(); List<Long> prioritizedClusterIds = clusterCapacityInfo.first();
@ -366,7 +364,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
prioritizedClusterIds.removeAll(avoid.getClustersToAvoid()); prioritizedClusterIds.removeAll(avoid.getClustersToAvoid());
} }
if(!isRootAdmin(plan.getReservationContext())){ if(!isRootAdmin(plan.getReservationContext())){
List<Long> disabledClusters = new ArrayList<Long>(); List<Long> disabledClusters = new ArrayList<Long>();
if(isZone){ if(isZone){
@ -397,7 +395,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
return null; return null;
} }
} }
/** /**
* This method should reorder the given list of Cluster Ids by applying any necessary heuristic * This method should reorder the given list of Cluster Ids by applying any necessary heuristic
* for this planner * for this planner
@ -409,7 +407,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
List<Long> reordersClusterIds = clusterCapacityInfo.first(); List<Long> reordersClusterIds = clusterCapacityInfo.first();
return reordersClusterIds; return reordersClusterIds;
} }
/** /**
* This method should reorder the given list of Pod Ids by applying any necessary heuristic * This method should reorder the given list of Pod Ids by applying any necessary heuristic
* for this planner * for this planner
@ -421,7 +419,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
List<Long> podIdsByCapacity = podCapacityInfo.first(); List<Long> podIdsByCapacity = podCapacityInfo.first();
return podIdsByCapacity; return podIdsByCapacity;
} }
private List<Long> listDisabledClusters(long zoneId, Long podId){ private List<Long> listDisabledClusters(long zoneId, Long podId){
List<Long> disabledClusters = _clusterDao.listDisabledClusters(zoneId, podId); List<Long> disabledClusters = _clusterDao.listDisabledClusters(zoneId, podId);
if(podId == null){ if(podId == null){
@ -431,70 +429,70 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
return disabledClusters; return disabledClusters;
} }
private List<Long> listDisabledPods(long zoneId){ private List<Long> listDisabledPods(long zoneId){
List<Long> disabledPods = _podDao.listDisabledPods(zoneId); List<Long> disabledPods = _podDao.listDisabledPods(zoneId);
return disabledPods; return disabledPods;
} }
private Map<Short,Float> getCapacityThresholdMap(){ private Map<Short,Float> getCapacityThresholdMap(){
// Lets build this real time so that the admin wont have to restart MS if he changes these values // Lets build this real time so that the admin wont have to restart MS if he changes these values
Map<Short,Float> disableThresholdMap = new HashMap<Short, Float>(); Map<Short,Float> disableThresholdMap = new HashMap<Short, Float>();
String cpuDisableThresholdString = _configDao.getValue(Config.CPUCapacityDisableThreshold.key()); String cpuDisableThresholdString = _configDao.getValue(Config.CPUCapacityDisableThreshold.key());
float cpuDisableThreshold = NumbersUtil.parseFloat(cpuDisableThresholdString, 0.85F); float cpuDisableThreshold = NumbersUtil.parseFloat(cpuDisableThresholdString, 0.85F);
disableThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, cpuDisableThreshold); disableThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, cpuDisableThreshold);
String memoryDisableThresholdString = _configDao.getValue(Config.MemoryCapacityDisableThreshold.key()); String memoryDisableThresholdString = _configDao.getValue(Config.MemoryCapacityDisableThreshold.key());
float memoryDisableThreshold = NumbersUtil.parseFloat(memoryDisableThresholdString, 0.85F); float memoryDisableThreshold = NumbersUtil.parseFloat(memoryDisableThresholdString, 0.85F);
disableThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, memoryDisableThreshold); disableThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, memoryDisableThreshold);
return disableThresholdMap; return disableThresholdMap;
} }
private List<Short> getCapacitiesForCheckingThreshold(){ private List<Short> getCapacitiesForCheckingThreshold(){
List<Short> capacityList = new ArrayList<Short>(); List<Short> capacityList = new ArrayList<Short>();
capacityList.add(Capacity.CAPACITY_TYPE_CPU); capacityList.add(Capacity.CAPACITY_TYPE_CPU);
capacityList.add(Capacity.CAPACITY_TYPE_MEMORY); capacityList.add(Capacity.CAPACITY_TYPE_MEMORY);
return capacityList; return capacityList;
} }
private void removeClustersCrossingThreshold(List<Long> clusterListForVmAllocation, ExcludeList avoid, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan){ private void removeClustersCrossingThreshold(List<Long> clusterListForVmAllocation, ExcludeList avoid, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan){
Map<Short,Float> capacityThresholdMap = getCapacityThresholdMap(); Map<Short,Float> capacityThresholdMap = getCapacityThresholdMap();
List<Short> capacityList = getCapacitiesForCheckingThreshold(); List<Short> capacityList = getCapacitiesForCheckingThreshold();
List<Long> clustersCrossingThreshold = new ArrayList<Long>(); List<Long> clustersCrossingThreshold = new ArrayList<Long>();
ServiceOffering offering = vmProfile.getServiceOffering(); ServiceOffering offering = vmProfile.getServiceOffering();
int cpu_requested = offering.getCpu() * offering.getSpeed(); int cpu_requested = offering.getCpu() * offering.getSpeed();
long ram_requested = offering.getRamSize() * 1024L * 1024L; long ram_requested = offering.getRamSize() * 1024L * 1024L;
// For each capacity get the cluster list crossing the threshold and remove it from the clusterList that will be used for vm allocation. // For each capacity get the cluster list crossing the threshold and remove it from the clusterList that will be used for vm allocation.
for(short capacity : capacityList){ for(short capacity : capacityList){
if (clusterListForVmAllocation == null || clusterListForVmAllocation.size() == 0){
return;
}
if (capacity == Capacity.CAPACITY_TYPE_CPU){
clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(Capacity.CAPACITY_TYPE_CPU, plan.getDataCenterId(),
capacityThresholdMap.get(capacity), cpu_requested, ApiDBUtils.getCpuOverprovisioningFactor());
}else{
clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(capacity, plan.getDataCenterId(),
capacityThresholdMap.get(capacity), ram_requested, 1.0f);//Mem overprov not supported yet
}
if (clusterListForVmAllocation == null || clusterListForVmAllocation.size() == 0){
if (clustersCrossingThreshold != null && clustersCrossingThreshold.size() != 0){ return;
// addToAvoid Set }
avoid.addClusterList(clustersCrossingThreshold);
// Remove clusters crossing disabled threshold if (capacity == Capacity.CAPACITY_TYPE_CPU){
clusterListForVmAllocation.removeAll(clustersCrossingThreshold); clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(Capacity.CAPACITY_TYPE_CPU, plan.getDataCenterId(),
capacityThresholdMap.get(capacity), cpu_requested, ApiDBUtils.getCpuOverprovisioningFactor());
s_logger.debug("Cannot allocate cluster list " + clustersCrossingThreshold.toString() + " for vm creation since their allocated percentage" + }else{
" crosses the disable capacity threshold: " + capacityThresholdMap.get(capacity) + " for capacity Type : " + capacity + ", skipping these clusters"); clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(capacity, plan.getDataCenterId(),
} capacityThresholdMap.get(capacity), ram_requested, 1.0f);//Mem overprov not supported yet
}
if (clustersCrossingThreshold != null && clustersCrossingThreshold.size() != 0){
// addToAvoid Set
avoid.addClusterList(clustersCrossingThreshold);
// Remove clusters crossing disabled threshold
clusterListForVmAllocation.removeAll(clustersCrossingThreshold);
s_logger.debug("Cannot allocate cluster list " + clustersCrossingThreshold.toString() + " for vm creation since their allocated percentage" +
" crosses the disable capacity threshold: " + capacityThresholdMap.get(capacity) + " for capacity Type : " + capacity + ", skipping these clusters");
}
} }
} }
@ -506,7 +504,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
removeClustersCrossingThreshold(clusterList, avoid, vmProfile, plan); removeClustersCrossingThreshold(clusterList, avoid, vmProfile, plan);
for(Long clusterId : clusterList){ for(Long clusterId : clusterList){
Cluster clusterVO = _clusterDao.findById(clusterId); Cluster clusterVO = _clusterDao.findById(clusterId);
@ -515,7 +513,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
avoid.addCluster(clusterVO.getId()); avoid.addCluster(clusterVO.getId());
continue; continue;
} }
s_logger.debug("Checking resources in Cluster: "+clusterId + " under Pod: "+clusterVO.getPodId()); s_logger.debug("Checking resources in Cluster: "+clusterId + " under Pod: "+clusterVO.getPodId());
//search for resources(hosts and storage) under this zone, pod, cluster. //search for resources(hosts and storage) under this zone, pod, cluster.
DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId(), null, plan.getReservationContext()); DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId(), null, plan.getReservationContext());
@ -595,11 +593,11 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
if (s_logger.isTraceEnabled()) { if (s_logger.isTraceEnabled()) {
s_logger.trace("ClusterId List having enough CPU and RAM capacity & in order of aggregate capacity: " + clusterIdsOrderedByAggregateCapacity); s_logger.trace("ClusterId List having enough CPU and RAM capacity & in order of aggregate capacity: " + clusterIdsOrderedByAggregateCapacity);
} }
return result; return result;
} }
protected Pair<List<Long>, Map<Long, Double>> listPodsByCapacity(long zoneId, int requiredCpu, long requiredRam, float cpuOverprovisioningFactor){ protected Pair<List<Long>, Map<Long, Double>> listPodsByCapacity(long zoneId, int requiredCpu, long requiredRam, float cpuOverprovisioningFactor){
//look at the aggregate available cpu and ram per pod //look at the aggregate available cpu and ram per pod
//although an aggregate value may be false indicator that a pod can host a vm, it will at the least eliminate those pods which definitely cannot //although an aggregate value may be false indicator that a pod can host a vm, it will at the least eliminate those pods which definitely cannot
@ -632,7 +630,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
if (s_logger.isTraceEnabled()) { if (s_logger.isTraceEnabled()) {
s_logger.trace("PodId List having enough CPU and RAM capacity & in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity); s_logger.trace("PodId List having enough CPU and RAM capacity & in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity);
} }
return result; return result;
} }
@ -719,7 +717,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
break; break;
} }
} }
if(suitableHosts.isEmpty()){ if(suitableHosts.isEmpty()){
s_logger.debug("No suitable hosts found"); s_logger.debug("No suitable hosts found");
} }
@ -801,8 +799,8 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
// when deploying VM based on ISO, we have a service offering and an additional disk offering, use-local storage flag is actually // when deploying VM based on ISO, we have a service offering and an additional disk offering, use-local storage flag is actually
// saved in service offering, overrde the flag from service offering when it is a ROOT disk // saved in service offering, overrde the flag from service offering when it is a ROOT disk
if(!useLocalStorage && vmProfile.getServiceOffering().getUseLocalStorage()) { if(!useLocalStorage && vmProfile.getServiceOffering().getUseLocalStorage()) {
if(toBeCreated.getVolumeType() == Volume.Type.ROOT) if(toBeCreated.getVolumeType() == Volume.Type.ROOT)
useLocalStorage = true; useLocalStorage = true;
} }
} }
diskProfile.setUseLocalStorage(useLocalStorage); diskProfile.setUseLocalStorage(useLocalStorage);
@ -816,7 +814,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
break; break;
} }
} }
if(!foundPotentialPools){ if(!foundPotentialPools){
s_logger.debug("No suitable pools found for volume: "+toBeCreated +" under cluster: "+plan.getClusterId()); s_logger.debug("No suitable pools found for volume: "+toBeCreated +" under cluster: "+plan.getClusterId());
//No suitable storage pools found under this cluster for this volume. - remove any suitable pools found for other volumes. //No suitable storage pools found under this cluster for this volume. - remove any suitable pools found for other volumes.
@ -862,7 +860,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
} }
return false; return false;
} }
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params); super.configure(name, params);

View File

@ -37,7 +37,6 @@ import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager; import com.cloud.alert.AlertManager;
import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterDetailsDao;
@ -142,7 +141,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
ManagementServer _msServer; ManagementServer _msServer;
@Inject @Inject
ConfigurationDao _configDao; ConfigurationDao _configDao;
String _instance; String _instance;
ScheduledExecutorService _executor; ScheduledExecutorService _executor;
int _stopRetryInterval; int _stopRetryInterval;
@ -189,12 +188,12 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
if (host.getType() != Host.Type.Routing) { if (host.getType() != Host.Type.Routing) {
return; return;
} }
if(host.getHypervisorType() == HypervisorType.VMware) { if(host.getHypervisorType() == HypervisorType.VMware) {
s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host"); s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host");
return; return;
} }
s_logger.warn("Scheduling restart for VMs on host " + host.getId()); s_logger.warn("Scheduling restart for VMs on host " + host.getId());
final List<VMInstanceVO> vms = _instanceDao.listByHostId(host.getId()); final List<VMInstanceVO> vms = _instanceDao.listByHostId(host.getId());
@ -268,29 +267,29 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
@Override @Override
public void scheduleRestart(VMInstanceVO vm, boolean investigate) { public void scheduleRestart(VMInstanceVO vm, boolean investigate) {
Long hostId = vm.getHostId(); Long hostId = vm.getHostId();
if (hostId == null) { if (hostId == null) {
try { try {
s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm); s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm);
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (ConcurrentOperationException e) { } catch (ConcurrentOperationException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} }
return; return;
} }
if(vm.getHypervisorType() == HypervisorType.VMware) {
s_logger.info("Skip HA for VMware VM " + vm.getInstanceName());
return;
}
if(vm.getHypervisorType() == HypervisorType.VMware) {
s_logger.info("Skip HA for VMware VM " + vm.getInstanceName());
return;
}
if (!investigate) { if (!investigate) {
if (s_logger.isDebugEnabled()) { if (s_logger.isDebugEnabled()) {
s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString()); s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString());
@ -319,13 +318,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (ConcurrentOperationException e) { } catch (ConcurrentOperationException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} }
} }
@ -360,7 +359,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
s_logger.info(str.toString()); s_logger.info(str.toString());
return null; return null;
} }
items = _haDao.listRunningHaWorkForVm(work.getInstanceId()); items = _haDao.listRunningHaWorkForVm(work.getInstanceId());
if (items.size() > 0) { if (items.size() > 0) {
StringBuilder str = new StringBuilder("Waiting because there's HA work being executed on an item currently. Work Ids =["); StringBuilder str = new StringBuilder("Waiting because there's HA work being executed on an item currently. Work Ids =[");
@ -371,7 +370,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
s_logger.info(str.toString()); s_logger.info(str.toString());
return (System.currentTimeMillis() >> 10) + _investigateRetryInterval; return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
} }
long vmId = work.getInstanceId(); long vmId = work.getInstanceId();
VMInstanceVO vm = _itMgr.findByIdAndType(work.getType(), work.getInstanceId()); VMInstanceVO vm = _itMgr.findByIdAndType(work.getType(), work.getInstanceId());
@ -420,14 +419,14 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
Investigator investigator = null; Investigator investigator = null;
for(Investigator it : _investigators) { for(Investigator it : _investigators) {
investigator = it; investigator = it;
alive = investigator.isVmAlive(vm, host); alive = investigator.isVmAlive(vm, host);
s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive); s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive);
if (alive != null) { if (alive != null) {
break; break;
} }
} }
boolean fenced = false; boolean fenced = false;
if (alive == null) { if (alive == null) {
s_logger.debug("Fencing off VM that we don't know the state of"); s_logger.debug("Fencing off VM that we don't know the state of");
@ -439,7 +438,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
break; break;
} }
} }
} else if (!alive) { } else if (!alive) {
fenced = true; fenced = true;
} else { } else {
@ -464,13 +463,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (ConcurrentOperationException e) { } catch (ConcurrentOperationException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} }
work.setStep(Step.Scheduled); work.setStep(Step.Scheduled);
@ -481,13 +480,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) { } catch (ResourceUnavailableException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (OperationTimedoutException e) { } catch (OperationTimedoutException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (ConcurrentOperationException e) { } catch (ConcurrentOperationException e) {
assert false : "How do we hit this when force is true?"; assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e); throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} }
} }
} }
@ -519,7 +518,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
params.put(VirtualMachineProfile.Param.HaTag, _haTag); params.put(VirtualMachineProfile.Param.HaTag, _haTag);
} }
VMInstanceVO started = _itMgr.advanceStart(vm, params, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount()); VMInstanceVO started = _itMgr.advanceStart(vm, params, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
if (started != null) { if (started != null) {
s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId()); s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId());
return null; return null;
@ -735,7 +734,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
if (_instance == null) { if (_instance == null) {
_instance = "VMOPS"; _instance = "VMOPS";
} }
_haTag = params.get("ha.tag"); _haTag = params.get("ha.tag");
_haDao.releaseWorkItems(_serverId); _haDao.releaseWorkItems(_serverId);
@ -785,8 +784,6 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
_haDao.cleanup(System.currentTimeMillis() - _timeBetweenFailures); _haDao.cleanup(System.currentTimeMillis() - _timeBetweenFailures);
} catch (Exception e) { } catch (Exception e) {
s_logger.warn("Error while cleaning up", e); s_logger.warn("Error while cleaning up", e);
} finally {
StackMaid.current().exitCleanup();
} }
} }
} }
@ -832,7 +829,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
nextTime = destroyVM(work); nextTime = destroyVM(work);
} else { } else {
assert false : "How did we get here with " + wt.toString(); assert false : "How did we get here with " + wt.toString();
continue; continue;
} }
if (nextTime == null) { if (nextTime == null) {
@ -852,7 +849,6 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
} catch (final Throwable th) { } catch (final Throwable th) {
s_logger.error("Caught this throwable, ", th); s_logger.error("Caught this throwable, ", th);
} finally { } finally {
StackMaid.current().exitCleanup();
if (work != null) { if (work != null) {
NDC.pop(); NDC.pop();
} }
@ -885,5 +881,5 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
public String getHaTag() { public String getHaTag() {
return _haTag; return _haTag;
} }
} }

View File

@ -47,7 +47,6 @@ import com.cloud.info.RunningHostCountInfo;
import com.cloud.org.Managed; import com.cloud.org.Managed;
import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceState;
import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Attribute; import com.cloud.utils.db.Attribute;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;
@ -103,7 +102,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
protected SearchBuilder<HostVO> ManagedDirectConnectSearch; protected SearchBuilder<HostVO> ManagedDirectConnectSearch;
protected SearchBuilder<HostVO> ManagedRoutingServersSearch; protected SearchBuilder<HostVO> ManagedRoutingServersSearch;
protected SearchBuilder<HostVO> SecondaryStorageVMSearch; protected SearchBuilder<HostVO> SecondaryStorageVMSearch;
protected GenericSearchBuilder<HostVO, Long> HostsInStatusSearch; protected GenericSearchBuilder<HostVO, Long> HostsInStatusSearch;
protected GenericSearchBuilder<HostVO, Long> CountRoutingByDc; protected GenericSearchBuilder<HostVO, Long> CountRoutingByDc;
@ -123,7 +122,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
public HostDaoImpl() { public HostDaoImpl() {
} }
@PostConstruct @PostConstruct
public void init() { public void init() {
@ -152,7 +151,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
TypeDcSearch.and("type", TypeDcSearch.entity().getType(), SearchCriteria.Op.EQ); TypeDcSearch.and("type", TypeDcSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeDcSearch.and("dc", TypeDcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); TypeDcSearch.and("dc", TypeDcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeDcSearch.done(); TypeDcSearch.done();
SecondaryStorageVMSearch = createSearchBuilder(); SecondaryStorageVMSearch = createSearchBuilder();
SecondaryStorageVMSearch.and("type", SecondaryStorageVMSearch.entity().getType(), SearchCriteria.Op.EQ); SecondaryStorageVMSearch.and("type", SecondaryStorageVMSearch.entity().getType(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.and("dc", SecondaryStorageVMSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); SecondaryStorageVMSearch.and("dc", SecondaryStorageVMSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
@ -165,14 +164,14 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
TypeDcStatusSearch.and("status", TypeDcStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ); TypeDcStatusSearch.and("status", TypeDcStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("resourceState", TypeDcStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ); TypeDcStatusSearch.and("resourceState", TypeDcStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.done(); TypeDcStatusSearch.done();
TypeClusterStatusSearch = createSearchBuilder(); TypeClusterStatusSearch = createSearchBuilder();
TypeClusterStatusSearch.and("type", TypeClusterStatusSearch.entity().getType(), SearchCriteria.Op.EQ); TypeClusterStatusSearch.and("type", TypeClusterStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("cluster", TypeClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ); TypeClusterStatusSearch.and("cluster", TypeClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("status", TypeClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ); TypeClusterStatusSearch.and("status", TypeClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ); TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.done(); TypeClusterStatusSearch.done();
IdStatusSearch = createSearchBuilder(); IdStatusSearch = createSearchBuilder();
IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ); IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ);
IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN); IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
@ -218,7 +217,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
StatusSearch = createSearchBuilder(); StatusSearch = createSearchBuilder();
StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN); StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
StatusSearch.done(); StatusSearch.done();
ResourceStateSearch = createSearchBuilder(); ResourceStateSearch = createSearchBuilder();
ResourceStateSearch.and("resourceState", ResourceStateSearch.entity().getResourceState(), SearchCriteria.Op.IN); ResourceStateSearch.and("resourceState", ResourceStateSearch.entity().getResourceState(), SearchCriteria.Op.IN);
ResourceStateSearch.done(); ResourceStateSearch.done();
@ -261,7 +260,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ); ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getClusterId(), JoinType.INNER); UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getClusterId(), JoinType.INNER);
UnmanagedDirectConnectSearch.done(); UnmanagedDirectConnectSearch.done();
DirectConnectSearch = createSearchBuilder(); DirectConnectSearch = createSearchBuilder();
DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL); DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
@ -311,7 +310,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
ManagedRoutingServersSearch.and("server", ManagedRoutingServersSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL); ManagedRoutingServersSearch.and("server", ManagedRoutingServersSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
ManagedRoutingServersSearch.and("type", ManagedRoutingServersSearch.entity().getType(), SearchCriteria.Op.EQ); ManagedRoutingServersSearch.and("type", ManagedRoutingServersSearch.entity().getType(), SearchCriteria.Op.EQ);
ManagedRoutingServersSearch.done(); ManagedRoutingServersSearch.done();
RoutingSearch = createSearchBuilder(); RoutingSearch = createSearchBuilder();
RoutingSearch.and("type", RoutingSearch.entity().getType(), SearchCriteria.Op.EQ); RoutingSearch.and("type", RoutingSearch.entity().getType(), SearchCriteria.Op.EQ);
RoutingSearch.done(); RoutingSearch.done();
@ -334,52 +333,52 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
List<HostVO> hosts = listBy(sc); List<HostVO> hosts = listBy(sc);
return hosts.size(); return hosts.size();
} }
@Override @Override
public HostVO findByGuid(String guid) { public HostVO findByGuid(String guid) {
SearchCriteria<HostVO> sc = GuidSearch.create("guid", guid); SearchCriteria<HostVO> sc = GuidSearch.create("guid", guid);
return findOneBy(sc); return findOneBy(sc);
} }
@Override @DB @Override @DB
public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) { public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create(); SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter); sc.setParameters("lastPinged", lastPingSecondsAfter);
//sc.setParameters("resourceStates", ResourceState.ErrorInMaintenance, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.Disabled); //sc.setParameters("resourceStates", ResourceState.ErrorInMaintenance, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.Disabled);
sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed); sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
List<HostVO> hosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true); List<HostVO> hosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true);
for (HostVO host : hosts) { for (HostVO host : hosts) {
host.setManagementServerId(managementServerId); host.setManagementServerId(managementServerId);
update(host.getId(), host); update(host.getId(), host);
} }
txn.commit(); txn.commit();
return hosts; return hosts;
} }
@Override @DB @Override @DB
public List<HostVO> findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) { public List<HostVO> findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
txn.start(); txn.start();
SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create(); SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter); sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.PxeServer, Type.TrafficMonitor, Type.L2Networking); sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.PxeServer, Type.TrafficMonitor, Type.L2Networking);
List<HostVO> hosts = lockRows(sc, null, true); List<HostVO> hosts = lockRows(sc, null, true);
for (HostVO host : hosts) { for (HostVO host : hosts) {
host.setManagementServerId(managementServerId); host.setManagementServerId(managementServerId);
update(host.getId(), host); update(host.getId(), host);
} }
txn.commit(); txn.commit();
return hosts; return hosts;
} }
@Override @Override
@ -405,7 +404,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
ub = getUpdateBuilder(host); ub = getUpdateBuilder(host);
update(ub, sc, null); update(ub, sc, null);
} }
@Override @Override
public List<HostVO> listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) { public List<HostVO> listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) {
@ -438,8 +437,8 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) { public List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) {
SearchBuilder<HostTagVO> hostTagSearch = null; SearchBuilder<HostTagVO> hostTagSearch = null;
@ -449,42 +448,42 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
hostTagSearch.or("tagNull", hostTagSearch.entity().getTag(), SearchCriteria.Op.NULL); hostTagSearch.or("tagNull", hostTagSearch.entity().getTag(), SearchCriteria.Op.NULL);
hostTagSearch.cp(); hostTagSearch.cp();
} }
SearchBuilder<HostVO> hostSearch = createSearchBuilder(); SearchBuilder<HostVO> hostSearch = createSearchBuilder();
hostSearch.and("type", hostSearch.entity().getType(), SearchCriteria.Op.EQ); hostSearch.and("type", hostSearch.entity().getType(), SearchCriteria.Op.EQ);
hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ); hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
hostSearch.and("podId", hostSearch.entity().getPodId(), SearchCriteria.Op.EQ); hostSearch.and("podId", hostSearch.entity().getPodId(), SearchCriteria.Op.EQ);
hostSearch.and("zoneId", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); hostSearch.and("zoneId", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
hostSearch.and("status", hostSearch.entity().getStatus(), SearchCriteria.Op.EQ); hostSearch.and("status", hostSearch.entity().getStatus(), SearchCriteria.Op.EQ);
hostSearch.and("resourceState", hostSearch.entity().getResourceState(), SearchCriteria.Op.EQ); hostSearch.and("resourceState", hostSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
if (haTag != null && !haTag.isEmpty()) { if (haTag != null && !haTag.isEmpty()) {
hostSearch.join("hostTagSearch", hostTagSearch, hostSearch.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER); hostSearch.join("hostTagSearch", hostTagSearch, hostSearch.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER);
} }
SearchCriteria<HostVO> sc = hostSearch.create(); SearchCriteria<HostVO> sc = hostSearch.create();
if (haTag != null && !haTag.isEmpty()) { if (haTag != null && !haTag.isEmpty()) {
sc.setJoinParameters("hostTagSearch", "tag", haTag); sc.setJoinParameters("hostTagSearch", "tag", haTag);
} }
if (type != null) { if (type != null) {
sc.setParameters("type", type); sc.setParameters("type", type);
} }
if (clusterId != null) { if (clusterId != null) {
sc.setParameters("clusterId", clusterId); sc.setParameters("clusterId", clusterId);
} }
if (podId != null) { if (podId != null) {
sc.setParameters("podId", podId); sc.setParameters("podId", podId);
} }
sc.setParameters("zoneId", dcId); sc.setParameters("zoneId", dcId);
sc.setParameters("status", Status.Up); sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled); sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc); return listBy(sc);
} }
@ -531,7 +530,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
} }
return result; return result;
} }
@Override @Override
public void saveDetails(HostVO host) { public void saveDetails(HostVO host) {
Map<String, String> details = host.getDetails(); Map<String, String> details = host.getDetails();
@ -653,81 +652,81 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
} }
@Override @Override
public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) { public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) {
HostVO host = findById(vo.getId()); HostVO host = findById(vo.getId());
long oldPingTime = host.getLastPinged(); long oldPingTime = host.getLastPinged();
SearchBuilder<HostVO> sb = createSearchBuilder(); SearchBuilder<HostVO> sb = createSearchBuilder();
sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ); sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ);
if (newStatus.checkManagementServer()) { if (newStatus.checkManagementServer()) {
sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ); sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ);
sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL); sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL);
sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ); sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ);
sb.closeParen(); sb.closeParen();
} }
sb.done(); sb.done();
SearchCriteria<HostVO> sc = sb.create(); SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("status", oldStatus); sc.setParameters("status", oldStatus);
sc.setParameters("id", host.getId()); sc.setParameters("id", host.getId());
sc.setParameters("update", host.getUpdated()); sc.setParameters("update", host.getUpdated());
long oldUpdateCount = host.getUpdated(); long oldUpdateCount = host.getUpdated();
if (newStatus.checkManagementServer()) { if (newStatus.checkManagementServer()) {
sc.setParameters("ping", oldPingTime); sc.setParameters("ping", oldPingTime);
sc.setParameters("msid", host.getManagementServerId()); sc.setParameters("msid", host.getManagementServerId());
} }
long newUpdateCount = host.incrUpdated(); long newUpdateCount = host.incrUpdated();
UpdateBuilder ub = getUpdateBuilder(host); UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _statusAttr, newStatus); ub.set(host, _statusAttr, newStatus);
if (newStatus.updateManagementServer()) { if (newStatus.updateManagementServer()) {
if (newStatus.lostConnection()) { if (newStatus.lostConnection()) {
ub.set(host, _msIdAttr, null); ub.set(host, _msIdAttr, null);
} else { } else {
ub.set(host, _msIdAttr, host.getManagementServerId()); ub.set(host, _msIdAttr, host.getManagementServerId());
} }
if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) { if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) {
ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10); ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10);
} }
} }
if (event.equals(Event.ManagementServerDown)) { if (event.equals(Event.ManagementServerDown)) {
ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60))); ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60)));
} }
int result = update(ub, sc, null); int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? "; assert result <= 1 : "How can this update " + result + " rows? ";
if (status_logger.isDebugEnabled() && result == 0) { if (status_logger.isDebugEnabled() && result == 0) {
HostVO ho = findById(host.getId()); HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId(); assert ho != null : "How how how? : " + host.getId();
StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
str.append(". Name=").append(host.getName());
str.append("; New=[status=").append(newStatus.toString()).append(":msid=")
.append(newStatus.lostConnection() ? "null" : host.getManagementServerId()).append(":lastpinged=").append(host.getLastPinged()).append("]");
str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=")
.append(oldPingTime).append("]");
str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=")
.append(vo.getLastPinged()).append(":old update count=").append(oldUpdateCount).append("]");
status_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Agent status update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old status = " + oldStatus);
msg.append("; event = " + event);
msg.append("; new status = " + newStatus);
msg.append("; old update count = " + oldUpdateCount);
msg.append("; new update count = " + newUpdateCount + "]");
status_logger.debug(msg.toString());
}
return result > 0;
}
StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
str.append(". Name=").append(host.getName());
str.append("; New=[status=").append(newStatus.toString()).append(":msid=")
.append(newStatus.lostConnection() ? "null" : host.getManagementServerId()).append(":lastpinged=").append(host.getLastPinged()).append("]");
str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=")
.append(oldPingTime).append("]");
str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=")
.append(vo.getLastPinged()).append(":old update count=").append(oldUpdateCount).append("]");
status_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Agent status update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old status = " + oldStatus);
msg.append("; event = " + event);
msg.append("; new status = " + newStatus);
msg.append("; old update count = " + oldUpdateCount);
msg.append("; new update count = " + newUpdateCount + "]");
status_logger.debug(msg.toString());
}
return result > 0;
}
@Override @Override
public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) { public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) {
HostVO host = (HostVO)vo; HostVO host = (HostVO)vo;
@ -735,41 +734,41 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
sb.and("resource_state", sb.entity().getResourceState(), SearchCriteria.Op.EQ); sb.and("resource_state", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.done(); sb.done();
SearchCriteria<HostVO> sc = sb.create(); SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("resource_state", oldState); sc.setParameters("resource_state", oldState);
sc.setParameters("id", host.getId()); sc.setParameters("id", host.getId());
UpdateBuilder ub = getUpdateBuilder(host); UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _resourceStateAttr, newState); ub.set(host, _resourceStateAttr, newState);
int result = update(ub, sc, null); int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? "; assert result <= 1 : "How can this update " + result + " rows? ";
if (state_logger.isDebugEnabled() && result == 0) { if (state_logger.isDebugEnabled() && result == 0) {
HostVO ho = findById(host.getId()); HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId(); assert ho != null : "How how how? : " + host.getId();
StringBuilder str = new StringBuilder("Unable to update resource state: ["); StringBuilder str = new StringBuilder("Unable to update resource state: [");
str.append("m = " + host.getId()); str.append("m = " + host.getId());
str.append("; name = " + host.getName()); str.append("; name = " + host.getName());
str.append("; old state = " + oldState); str.append("; old state = " + oldState);
str.append("; event = " + event); str.append("; event = " + event);
str.append("; new state = " + newState + "]"); str.append("; new state = " + newState + "]");
state_logger.debug(str.toString()); state_logger.debug(str.toString());
} else { } else {
StringBuilder msg = new StringBuilder("Resource state update: ["); StringBuilder msg = new StringBuilder("Resource state update: [");
msg.append("id = " + host.getId()); msg.append("id = " + host.getId());
msg.append("; name = " + host.getName()); msg.append("; name = " + host.getName());
msg.append("; old state = " + oldState); msg.append("; old state = " + oldState);
msg.append("; event = " + event); msg.append("; event = " + event);
msg.append("; new state = " + newState + "]"); msg.append("; new state = " + newState + "]");
state_logger.debug(msg.toString()); state_logger.debug(msg.toString());
} }
return result > 0; return result > 0;
} }
@Override @Override
public HostVO findByTypeNameAndZoneId(long zoneId, String name, Host.Type type) { public HostVO findByTypeNameAndZoneId(long zoneId, String name, Host.Type type) {
SearchCriteria<HostVO> sc = TypeNameZoneSearch.create(); SearchCriteria<HostVO> sc = TypeNameZoneSearch.create();
@ -779,15 +778,15 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public List<HostVO> findHypervisorHostInCluster(long clusterId) { public List<HostVO> findHypervisorHostInCluster(long clusterId) {
SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create(); SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create();
sc.setParameters("type", Host.Type.Routing); sc.setParameters("type", Host.Type.Routing);
sc.setParameters("cluster", clusterId); sc.setParameters("cluster", clusterId);
sc.setParameters("status", Status.Up); sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled); sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc); return listBy(sc);
} }
} }

View File

@ -33,8 +33,6 @@ import com.cloud.host.Host;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
@Component @Component
@Local(value = { HypervisorGuruManager.class } ) @Local(value = { HypervisorGuruManager.class } )
@ -42,54 +40,56 @@ public class HypervisorGuruManagerImpl implements HypervisorGuruManager {
public static final Logger s_logger = Logger.getLogger(HypervisorGuruManagerImpl.class.getName()); public static final Logger s_logger = Logger.getLogger(HypervisorGuruManagerImpl.class.getName());
@Inject HostDao _hostDao; @Inject HostDao _hostDao;
String _name; String _name;
@Inject List<HypervisorGuru> _hvGuruList; @Inject List<HypervisorGuru> _hvGuruList;
Map<HypervisorType, HypervisorGuru> _hvGurus = new HashMap<HypervisorType, HypervisorGuru>(); Map<HypervisorType, HypervisorGuru> _hvGurus = new HashMap<HypervisorType, HypervisorGuru>();
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@PostConstruct
public void init() {
for(HypervisorGuru guru : _hvGuruList) {
_hvGurus.put(guru.getHypervisorType(), guru);
}
}
@Override @Override
public boolean start() { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
return true; _name = name;
} return true;
}
@Override @PostConstruct
public boolean stop() { public void init() {
return true; for(HypervisorGuru guru : _hvGuruList) {
} _hvGurus.put(guru.getHypervisorType(), guru);
}
}
@Override @Override
public String getName() { public boolean start() {
return _name; return true;
} }
public HypervisorGuru getGuru(HypervisorType hypervisorType) { @Override
return _hvGurus.get(hypervisorType); public boolean stop() {
} return true;
}
@Override
public String getName() {
return _name;
}
@Override
public HypervisorGuru getGuru(HypervisorType hypervisorType) {
return _hvGurus.get(hypervisorType);
}
@Override
public long getGuruProcessedCommandTargetHost(long hostId, Command cmd) { public long getGuruProcessedCommandTargetHost(long hostId, Command cmd) {
HostVO hostVo = _hostDao.findById(hostId); HostVO hostVo = _hostDao.findById(hostId);
HypervisorGuru hvGuru = null; HypervisorGuru hvGuru = null;
if(hostVo.getType() == Host.Type.Routing) { if(hostVo.getType() == Host.Type.Routing) {
hvGuru = _hvGurus.get(hostVo.getHypervisorType()); hvGuru = _hvGurus.get(hostVo.getHypervisorType());
} }
if(hvGuru != null) if(hvGuru != null)
return hvGuru.getCommandHostDelegation(hostId, cmd); return hvGuru.getCommandHostDelegation(hostId, cmd);
return hostId; return hostId;
} }
} }

View File

@ -36,15 +36,14 @@ import javax.naming.ConfigurationException;
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.maint.dao.AgentUpgradeDao; import com.cloud.maint.dao.AgentUpgradeDao;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
/** /**
* *
@ -57,7 +56,7 @@ import com.cloud.utils.component.ComponentLocator;
@Component @Component
@Local(UpgradeManager.class) @Local(UpgradeManager.class)
public class UpgradeManagerImpl implements UpgradeManager { public class UpgradeManagerImpl implements UpgradeManager {
private final static Logger s_logger = Logger.getLogger(UpgradeManagerImpl.class); private final static Logger s_logger = Logger.getLogger(UpgradeManagerImpl.class);
private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
String _name; String _name;
@ -66,10 +65,10 @@ public class UpgradeManagerImpl implements UpgradeManager {
// String _upgradeUrl; // String _upgradeUrl;
String _agentPath; String _agentPath;
long _checkInterval; long _checkInterval;
@Inject AgentUpgradeDao _upgradeDao; @Inject AgentUpgradeDao _upgradeDao;
@Inject ConfigurationDao _configDao; @Inject ConfigurationDao _configDao;
@Override @Override
public State registerForUpgrade(long hostId, String version) { public State registerForUpgrade(long hostId, String version) {
State state = State.UpToDate; State state = State.UpToDate;
@ -90,11 +89,11 @@ public class UpgradeManagerImpl implements UpgradeManager {
_upgradeDao.persist(vo); _upgradeDao.persist(vo);
} }
} }
*/ */
return state; return state;
} }
public String deployNewAgent(String url) { public String deployNewAgent(String url) {
s_logger.info("Updating agent with binary from " + url); s_logger.info("Updating agent with binary from " + url);
@ -132,18 +131,18 @@ public class UpgradeManagerImpl implements UpgradeManager {
s_logger.debug("New Agent zip file is now retrieved"); s_logger.debug("New Agent zip file is now retrieved");
} catch (final HttpException e) { } catch (final HttpException e) {
return "Unable to retrieve the file from " + url; return "Unable to retrieve the file from " + url;
} catch (final IOException e) { } catch (final IOException e) {
return "Unable to retrieve the file from " + url; return "Unable to retrieve the file from " + url;
} finally { } finally {
method.releaseConnection(); method.releaseConnection();
} }
file.delete(); file.delete();
return "File will be deployed."; return "File will be deployed.";
} }
// @Override // @Override
// public String getAgentUrl() { // public String getAgentUrl() {
// return _upgradeUrl; // return _upgradeUrl;
@ -174,7 +173,7 @@ public class UpgradeManagerImpl implements UpgradeManager {
} }
//_upgradeUrl = configs.get("upgrade.url"); //_upgradeUrl = configs.get("upgrade.url");
// if (_upgradeUrl == null) { // if (_upgradeUrl == null) {
// s_logger.debug("There is no upgrade url found in configuration table"); // s_logger.debug("There is no upgrade url found in configuration table");
// // _upgradeUrl = "http://updates.vmops.com/releases/rss.xml"; // // _upgradeUrl = "http://updates.vmops.com/releases/rss.xml";

View File

@ -19,9 +19,7 @@ package com.cloud.migration;
import java.io.File; import java.io.File;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Queue;
import javax.inject.Inject; import javax.inject.Inject;
@ -32,21 +30,17 @@ import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.ResourceCountVO; import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.DomainVO; import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao; import com.cloud.domain.dao.DomainDao;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceManager;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PropertiesUtil; import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
@ -56,37 +50,37 @@ import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.InstanceGroupVMMapDao; import com.cloud.vm.dao.InstanceGroupVMMapDao;
public class Db21to22MigrationUtil { public class Db21to22MigrationUtil {
@Inject private ClusterDao _clusterDao; @Inject private ClusterDao _clusterDao;
@Inject private HostDao _hostDao; @Inject private HostDao _hostDao;
@Inject private AccountDao _accountDao; @Inject private AccountDao _accountDao;
@Inject private DomainDao _domainDao; @Inject private DomainDao _domainDao;
@Inject private ResourceCountDao _resourceCountDao; @Inject private ResourceCountDao _resourceCountDao;
@Inject private InstanceGroupDao _vmGroupDao; @Inject private InstanceGroupDao _vmGroupDao;
@Inject private InstanceGroupVMMapDao _groupVMMapDao; @Inject private InstanceGroupVMMapDao _groupVMMapDao;
@Inject private ConfigurationDao _configurationDao; @Inject private ConfigurationDao _configurationDao;
@Inject private DataCenterDao _zoneDao; @Inject private DataCenterDao _zoneDao;
@Inject private ResourceManager _resourceMgr; @Inject private ResourceManager _resourceMgr;
private void doMigration() { private void doMigration() {
setupComponents(); setupComponents();
migrateResourceCounts(); migrateResourceCounts();
setupInstanceGroups(); setupInstanceGroups();
migrateZones(); migrateZones();
setupClusterGuid(); setupClusterGuid();
System.out.println("Migration done"); System.out.println("Migration done");
} }
/* add guid in cluster table */ /* add guid in cluster table */
private void setupClusterGuid() { private void setupClusterGuid() {
//FIXME moving out XenServer code out of server. This upgrade step need to be taken care of //FIXME moving out XenServer code out of server. This upgrade step need to be taken care of
/* /*
XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance(); XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance();
List<ClusterVO> clusters = _clusterDao.listByHyTypeWithoutGuid(HypervisorType.XenServer.toString()); List<ClusterVO> clusters = _clusterDao.listByHyTypeWithoutGuid(HypervisorType.XenServer.toString());
for (ClusterVO cluster : clusters) { for (ClusterVO cluster : clusters) {
@ -120,34 +114,34 @@ public class Db21to22MigrationUtil {
break; break;
} }
} }
*/ */
} }
/** /**
* This method migrates the zones based on bug: 7204 * This method migrates the zones based on bug: 7204
* based on the param direct.attach.untagged.vlan.enabled, we update zone to basic or advanced for 2.2 * based on the param direct.attach.untagged.vlan.enabled, we update zone to basic or advanced for 2.2
*/ */
private void migrateZones(){ private void migrateZones(){
try { try {
System.out.println("Migrating zones"); System.out.println("Migrating zones");
String val = _configurationDao.getValue("direct.attach.untagged.vlan.enabled"); String val = _configurationDao.getValue("direct.attach.untagged.vlan.enabled");
NetworkType networkType; NetworkType networkType;
if(val == null || val.equalsIgnoreCase("true")){ if(val == null || val.equalsIgnoreCase("true")){
networkType = NetworkType.Basic; networkType = NetworkType.Basic;
}else{ }else{
networkType = NetworkType.Advanced; networkType = NetworkType.Advanced;
} }
List<DataCenterVO> existingZones = _zoneDao.listAll(); List<DataCenterVO> existingZones = _zoneDao.listAll();
for(DataCenterVO zone : existingZones){ for(DataCenterVO zone : existingZones){
zone.setNetworkType(networkType); zone.setNetworkType(networkType);
_zoneDao.update(zone.getId(), zone); _zoneDao.update(zone.getId(), zone);
} }
} catch (Exception e) { } catch (Exception e) {
System.out.println("Unhandled exception in migrateZones()" + e); System.out.println("Unhandled exception in migrateZones()" + e);
} }
} }
private void migrateResourceCounts() { private void migrateResourceCounts() {
System.out.println("migrating resource counts"); System.out.println("migrating resource counts");
SearchBuilder<ResourceCountVO> sb = _resourceCountDao.createSearchBuilder(); SearchBuilder<ResourceCountVO> sb = _resourceCountDao.createSearchBuilder();
@ -175,46 +169,46 @@ public class Db21to22MigrationUtil {
private void setupComponents() { private void setupComponents() {
} }
private void setupInstanceGroups() { private void setupInstanceGroups() {
System.out.println("setting up vm instance groups"); System.out.println("setting up vm instance groups");
//Search for all the vms that have not null groups //Search for all the vms that have not null groups
Long vmId = 0L; Long vmId = 0L;
Long accountId = 0L; Long accountId = 0L;
String groupName; String groupName;
Transaction txn = Transaction.open(Transaction.CLOUD_DB); Transaction txn = Transaction.open(Transaction.CLOUD_DB);
txn.start(); txn.start();
try { try {
String request = "SELECT vm.id, uservm.account_id, vm.group from vm_instance vm, user_vm uservm where vm.group is not null and vm.removed is null and vm.id=uservm.id order by id"; String request = "SELECT vm.id, uservm.account_id, vm.group from vm_instance vm, user_vm uservm where vm.group is not null and vm.removed is null and vm.id=uservm.id order by id";
System.out.println(request); System.out.println(request);
PreparedStatement statement = txn.prepareStatement(request); PreparedStatement statement = txn.prepareStatement(request);
ResultSet result = statement.executeQuery(); ResultSet result = statement.executeQuery();
while (result.next()) { while (result.next()) {
vmId = result.getLong(1); vmId = result.getLong(1);
accountId = result.getLong(2); accountId = result.getLong(2);
groupName = result.getString(3); groupName = result.getString(3);
InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, groupName); InstanceGroupVO group = _vmGroupDao.findByAccountAndName(accountId, groupName);
//Create vm group if the group doesn't exist for this account //Create vm group if the group doesn't exist for this account
if (group == null) { if (group == null) {
group = new InstanceGroupVO(groupName, accountId); group = new InstanceGroupVO(groupName, accountId);
group = _vmGroupDao.persist(group); group = _vmGroupDao.persist(group);
System.out.println("Created new isntance group with name " + groupName + " for account id=" + accountId); System.out.println("Created new isntance group with name " + groupName + " for account id=" + accountId);
} }
if (group != null) { if (group != null) {
InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), vmId); InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(group.getId(), vmId);
_groupVMMapDao.persist(groupVmMapVO); _groupVMMapDao.persist(groupVmMapVO);
System.out.println("Assigned vm id=" + vmId + " to group with name " + groupName + " for account id=" + accountId); System.out.println("Assigned vm id=" + vmId + " to group with name " + groupName + " for account id=" + accountId);
} }
} }
txn.commit(); txn.commit();
statement.close(); statement.close();
} catch (Exception e) { } catch (Exception e) {
System.out.println("Unhandled exception: " + e); System.out.println("Unhandled exception: " + e);
} finally { } finally {
txn.close(); txn.close();
} }
} }

View File

@ -19,7 +19,6 @@ package com.cloud.network;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
@ -33,136 +32,135 @@ import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.dao.VlanDao; import com.cloud.dc.dao.VlanDao;
import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
@Component @Component
@Local(value=IpAddrAllocator.class) @Local(value=IpAddrAllocator.class)
public class ExteralIpAddressAllocator implements IpAddrAllocator{ public class ExteralIpAddressAllocator implements IpAddrAllocator{
private static final Logger s_logger = Logger.getLogger(ExteralIpAddressAllocator.class); private static final Logger s_logger = Logger.getLogger(ExteralIpAddressAllocator.class);
String _name; String _name;
@Inject ConfigurationDao _configDao = null; @Inject ConfigurationDao _configDao = null;
@Inject IPAddressDao _ipAddressDao = null; @Inject IPAddressDao _ipAddressDao = null;
@Inject VlanDao _vlanDao; @Inject VlanDao _vlanDao;
private boolean _isExternalIpAllocatorEnabled = false; private boolean _isExternalIpAllocatorEnabled = false;
private String _externalIpAllocatorUrl = null; private String _externalIpAllocatorUrl = null;
@Override
public IpAddr getPrivateIpAddress(String macAddr, long dcId, long podId) {
if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) {
return new IpAddr();
}
String urlString = this._externalIpAllocatorUrl + "?command=getIpAddr&mac=" + macAddr + "&dc=" + dcId + "&pod=" + podId;
s_logger.debug("getIP:" + urlString);
BufferedReader in = null;
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setReadTimeout(30000);
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
s_logger.debug(inputLine);
String[] tokens = inputLine.split(",");
if (tokens.length != 3) {
s_logger.debug("the return value should be: mac,netmask,gateway");
return new IpAddr();
}
return new IpAddr(tokens[0], tokens[1], tokens[2]);
}
return new IpAddr();
} catch (MalformedURLException e) {
throw new CloudRuntimeException("URL is malformed " + urlString, e);
} catch (IOException e) {
return new IpAddr();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
@Override
public IpAddr getPublicIpAddress(String macAddr, long dcId, long podId) {
/*TODO: call API to get ip address from external DHCP server*/
return getPrivateIpAddress(macAddr, dcId, podId);
}
@Override
public boolean releasePrivateIpAddress(String ip, long dcId, long podId) {
/*TODO: call API to release the ip address from external DHCP server*/
if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) {
return false;
}
String urlString = this._externalIpAllocatorUrl + "?command=releaseIpAddr&ip=" + ip + "&dc=" + dcId + "&pod=" + podId;
s_logger.debug("releaseIP:" + urlString);
BufferedReader in = null;
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setReadTimeout(30000);
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
return true;
} catch (MalformedURLException e) {
throw new CloudRuntimeException("URL is malformed " + urlString, e);
} catch (IOException e) {
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
@Override
public boolean releasePublicIpAddress(String ip, long dcId, long podId) {
/*TODO: call API to release the ip address from external DHCP server*/
return releasePrivateIpAddress(ip, dcId, podId);
}
public boolean exteralIpAddressAllocatorEnabled() {
return _isExternalIpAllocatorEnabled;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_isExternalIpAllocatorEnabled = Boolean.parseBoolean(_configDao.getValue("direct.attach.network.externalIpAllocator.enabled"));
_externalIpAllocatorUrl = _configDao.getValue("direct.attach.network.externalIpAllocator.url");
_name = name;
return true;
}
@Override @Override
public String getName() { public IpAddr getPrivateIpAddress(String macAddr, long dcId, long podId) {
return _name; if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) {
} return new IpAddr();
}
String urlString = this._externalIpAllocatorUrl + "?command=getIpAddr&mac=" + macAddr + "&dc=" + dcId + "&pod=" + podId;
s_logger.debug("getIP:" + urlString);
@Override BufferedReader in = null;
public boolean start() { try {
return true; URL url = new URL(urlString);
} URLConnection conn = url.openConnection();
conn.setReadTimeout(30000);
@Override in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
public boolean stop() { String inputLine;
return true; while ((inputLine = in.readLine()) != null) {
} s_logger.debug(inputLine);
String[] tokens = inputLine.split(",");
if (tokens.length != 3) {
s_logger.debug("the return value should be: mac,netmask,gateway");
return new IpAddr();
}
return new IpAddr(tokens[0], tokens[1], tokens[2]);
}
return new IpAddr();
} catch (MalformedURLException e) {
throw new CloudRuntimeException("URL is malformed " + urlString, e);
} catch (IOException e) {
return new IpAddr();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
@Override
public IpAddr getPublicIpAddress(String macAddr, long dcId, long podId) {
/*TODO: call API to get ip address from external DHCP server*/
return getPrivateIpAddress(macAddr, dcId, podId);
}
@Override
public boolean releasePrivateIpAddress(String ip, long dcId, long podId) {
/*TODO: call API to release the ip address from external DHCP server*/
if (_externalIpAllocatorUrl == null || this._externalIpAllocatorUrl.equalsIgnoreCase("")) {
return false;
}
String urlString = this._externalIpAllocatorUrl + "?command=releaseIpAddr&ip=" + ip + "&dc=" + dcId + "&pod=" + podId;
s_logger.debug("releaseIP:" + urlString);
BufferedReader in = null;
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setReadTimeout(30000);
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
return true;
} catch (MalformedURLException e) {
throw new CloudRuntimeException("URL is malformed " + urlString, e);
} catch (IOException e) {
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
@Override
public boolean releasePublicIpAddress(String ip, long dcId, long podId) {
/*TODO: call API to release the ip address from external DHCP server*/
return releasePrivateIpAddress(ip, dcId, podId);
}
@Override
public boolean exteralIpAddressAllocatorEnabled() {
return _isExternalIpAllocatorEnabled;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_isExternalIpAllocatorEnabled = Boolean.parseBoolean(_configDao.getValue("direct.attach.network.externalIpAllocator.enabled"));
_externalIpAllocatorUrl = _configDao.getValue("direct.attach.network.externalIpAllocator.url");
_name = name;
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
} }

View File

@ -27,22 +27,21 @@ import javax.ejb.Local;
import javax.inject.Inject; import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.command.admin.network.AddNetworkDeviceCmd; 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 org.apache.cloudstack.api.command.admin.network.ListNetworkDeviceCmd;
import org.apache.cloudstack.api.response.NetworkDeviceResponse;
import org.apache.cloudstack.network.ExternalNetworkDeviceManager; import org.apache.cloudstack.network.ExternalNetworkDeviceManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.agent.AgentManager; import com.cloud.agent.AgentManager;
import com.cloud.api.ApiDBUtils; 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.ExternalDhcpManager;
import com.cloud.baremetal.PxeServerManager; import com.cloud.baremetal.PxeServerManager;
import com.cloud.baremetal.PxeServerProfile;
import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.baremetal.PxeServerManager.PxeServerType;
import com.cloud.baremetal.PxeServerProfile;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter;
import com.cloud.dc.Pod; import com.cloud.dc.Pod;
@ -64,14 +63,11 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.VpnUserDao; import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.server.ManagementServer;
import org.apache.cloudstack.api.response.NetworkDeviceResponse;
import com.cloud.server.api.response.NwDeviceDhcpResponse; import com.cloud.server.api.response.NwDeviceDhcpResponse;
import com.cloud.server.api.response.PxePingResponse; import com.cloud.server.api.response.PxePingResponse;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserStatisticsDao; import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.NicDao;
@ -112,16 +108,16 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa
// obsolete // obsolete
// 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); private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalNetworkDeviceManagerImpl.class);
protected String _name; protected String _name;
@Override @Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name; _name = name;
return true; return true;
} }
@Override @Override
public boolean start() { public boolean start() {
return true; return true;
@ -136,21 +132,21 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa
public String getName() { public String getName() {
return _name; return _name;
} }
@Override @Override
public Host addNetworkDevice(AddNetworkDeviceCmd cmd) { public Host addNetworkDevice(AddNetworkDeviceCmd cmd) {
Map paramList = cmd.getParamList(); Map paramList = cmd.getParamList();
if (paramList == null) { if (paramList == null) {
throw new CloudRuntimeException("Parameter list is null"); throw new CloudRuntimeException("Parameter list is null");
} }
Collection paramsCollection = paramList.values(); Collection paramsCollection = paramList.values();
HashMap params = (HashMap) (paramsCollection.toArray())[0]; HashMap params = (HashMap) (paramsCollection.toArray())[0];
if (cmd.getDeviceType().equalsIgnoreCase(NetworkDevice.ExternalDhcp.getName())) { if (cmd.getDeviceType().equalsIgnoreCase(NetworkDevice.ExternalDhcp.getName())) {
//Long zoneId = _identityService.getIdentityId("data_center", (String) params.get(ApiConstants.ZONE_ID)); //Long zoneId = _identityService.getIdentityId("data_center", (String) params.get(ApiConstants.ZONE_ID));
//Long podId = _identityService.getIdentityId("host_pod_ref", (String)params.get(ApiConstants.POD_ID)); //Long podId = _identityService.getIdentityId("host_pod_ref", (String)params.get(ApiConstants.POD_ID));
Long zoneId = Long.valueOf((String) params.get(ApiConstants.ZONE_ID)); Long zoneId = Long.valueOf((String) params.get(ApiConstants.ZONE_ID));
Long podId = Long.valueOf((String)params.get(ApiConstants.POD_ID)); Long podId = Long.valueOf((String)params.get(ApiConstants.POD_ID));
String type = (String) params.get(ApiConstants.DHCP_SERVER_TYPE); String type = (String) params.get(ApiConstants.DHCP_SERVER_TYPE);
String url = (String) params.get(ApiConstants.URL); String url = (String) params.get(ApiConstants.URL);
String username = (String) params.get(ApiConstants.USERNAME); String username = (String) params.get(ApiConstants.USERNAME);
@ -217,7 +213,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa
} else { } else {
throw new CloudRuntimeException("Unsupported network device type:" + host.getType()); throw new CloudRuntimeException("Unsupported network device type:" + host.getType());
} }
response.setId(device.getUuid()); response.setId(device.getUuid());
return response; return response;
} }
@ -234,19 +230,19 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa
// } else { // } else {
// List<HostVO> devs = _hostDao.listBy(type, zoneId); // List<HostVO> devs = _hostDao.listBy(type, zoneId);
// res.addAll(devs); // res.addAll(devs);
// } // }
// return res; // return res;
return null; return null;
} }
@Override @Override
public List<Host> listNetworkDevice(ListNetworkDeviceCmd cmd) { public List<Host> listNetworkDevice(ListNetworkDeviceCmd cmd) {
Map paramList = cmd.getParamList(); Map paramList = cmd.getParamList();
if (paramList == null) { if (paramList == null) {
throw new CloudRuntimeException("Parameter list is null"); throw new CloudRuntimeException("Parameter list is null");
} }
List<Host> res; List<Host> res;
Collection paramsCollection = paramList.values(); Collection paramsCollection = paramList.values();
HashMap params = (HashMap) (paramsCollection.toArray())[0]; HashMap params = (HashMap) (paramsCollection.toArray())[0];
@ -275,13 +271,13 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa
} else { } else {
throw new CloudRuntimeException("Unknown network device type:" + cmd.getDeviceType()); throw new CloudRuntimeException("Unknown network device type:" + cmd.getDeviceType());
} }
return res; return res;
} }
@Override @Override
public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd) { public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd) {
HostVO device = _hostDao.findById(cmd.getId()); HostVO device = _hostDao.findById(cmd.getId());
return true; return true;
} }
} }

View File

@ -23,27 +23,31 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import javax.ejb.Local; import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import org.apache.cloudstack.acl.ControlledEntity; 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 org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiDispatcher;
import org.apache.cloudstack.api.BaseListAccountResourcesCmd; import org.apache.cloudstack.api.BaseListAccountResourcesCmd;
import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd;
import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; 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.CreateAutoScaleVmGroupCmd;
import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmProfileCmd;
import org.apache.cloudstack.api.command.user.autoscale.CreateConditionCmd; 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.ListAutoScalePoliciesCmd;
import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmGroupsCmd; import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmGroupsCmd;
import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmProfilesCmd;
import org.apache.cloudstack.api.command.user.autoscale.ListConditionsCmd; import org.apache.cloudstack.api.command.user.autoscale.ListConditionsCmd;
import org.apache.cloudstack.api.command.user.autoscale.ListCountersCmd;
import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd;
import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmGroupCmd;
import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd; import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd;
import org.apache.cloudstack.api.command.user.vm.DeployVMCmd;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiDispatcher;
import com.cloud.configuration.Config; import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.configuration.dao.ConfigurationDao;
@ -81,7 +85,6 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;

View File

@ -32,7 +32,6 @@ import com.cloud.network.rules.FirewallRule.TrafficType;
import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;
@ -286,11 +285,12 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
if (purpose != null) { if (purpose != null) {
sc.setParameters("purpose", purpose); sc.setParameters("purpose", purpose);
} }
sc.setParameters("trafficType", trafficType); sc.setParameters("trafficType", trafficType);
return listBy(sc); return listBy(sc);
} }
@Override
@DB @DB
public boolean remove(Long id) { public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn(); Transaction txn = Transaction.currentTxn();
@ -316,7 +316,7 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
public List<FirewallRuleVO> listByIpAndPurposeWithState(Long ipId, Purpose purpose, State state) { public List<FirewallRuleVO> listByIpAndPurposeWithState(Long ipId, Purpose purpose, State state) {
SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create(); SearchCriteria<FirewallRuleVO> sc = AllFieldsSearch.create();
sc.setParameters("ipId", ipId); sc.setParameters("ipId", ipId);
if (state != null) { if (state != null) {
sc.setParameters("state", state); sc.setParameters("state", state);
} }

View File

@ -35,7 +35,6 @@ import com.cloud.network.IPAddressVO;
import com.cloud.network.IpAddress.State; import com.cloud.network.IpAddress.State;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;
@ -62,11 +61,11 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
@Inject protected VlanDaoImpl _vlanDao; @Inject protected VlanDaoImpl _vlanDao;
protected GenericSearchBuilder<IPAddressVO, Long> CountFreePublicIps; protected GenericSearchBuilder<IPAddressVO, Long> CountFreePublicIps;
@Inject ResourceTagsDaoImpl _tagsDao; @Inject ResourceTagsDaoImpl _tagsDao;
// make it public for JUnit test // make it public for JUnit test
public IPAddressDaoImpl() { public IPAddressDaoImpl() {
} }
@PostConstruct @PostConstruct
public void init() { public void init() {
AllFieldsSearch = createSearchBuilder(); AllFieldsSearch = createSearchBuilder();
@ -101,7 +100,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
AllocatedIpCount.and("vlan", AllocatedIpCount.entity().getVlanId(), Op.EQ); AllocatedIpCount.and("vlan", AllocatedIpCount.entity().getVlanId(), Op.EQ);
AllocatedIpCount.and("allocated", AllocatedIpCount.entity().getAllocatedTime(), Op.NNULL); AllocatedIpCount.and("allocated", AllocatedIpCount.entity().getAllocatedTime(), Op.NNULL);
AllocatedIpCount.done(); AllocatedIpCount.done();
AllIpCountForDashboard = createSearchBuilder(Integer.class); AllIpCountForDashboard = createSearchBuilder(Integer.class);
AllIpCountForDashboard.select(null, Func.COUNT, AllIpCountForDashboard.entity().getAddress()); AllIpCountForDashboard.select(null, Func.COUNT, AllIpCountForDashboard.entity().getAddress());
AllIpCountForDashboard.and("dc", AllIpCountForDashboard.entity().getDataCenterId(), Op.EQ); AllIpCountForDashboard.and("dc", AllIpCountForDashboard.entity().getDataCenterId(), Op.EQ);
@ -111,7 +110,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
virtaulNetworkVlan.and("vlanType", virtaulNetworkVlan.entity().getVlanType(), SearchCriteria.Op.EQ); virtaulNetworkVlan.and("vlanType", virtaulNetworkVlan.entity().getVlanType(), SearchCriteria.Op.EQ);
AllIpCountForDashboard.join("vlan", virtaulNetworkVlan, virtaulNetworkVlan.entity().getId(), AllIpCountForDashboard.join("vlan", virtaulNetworkVlan, virtaulNetworkVlan.entity().getId(),
AllIpCountForDashboard.entity().getVlanId(), JoinBuilder.JoinType.INNER); AllIpCountForDashboard.entity().getVlanId(), JoinBuilder.JoinType.INNER);
virtaulNetworkVlan.done(); virtaulNetworkVlan.done();
AllIpCountForDashboard.done(); AllIpCountForDashboard.done();
@ -121,7 +120,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
AllocatedIpCountForAccount.and("allocated", AllocatedIpCountForAccount.entity().getAllocatedTime(), Op.NNULL); AllocatedIpCountForAccount.and("allocated", AllocatedIpCountForAccount.entity().getAllocatedTime(), Op.NNULL);
AllocatedIpCountForAccount.and("network", AllocatedIpCountForAccount.entity().getAssociatedWithNetworkId(), Op.NNULL); AllocatedIpCountForAccount.and("network", AllocatedIpCountForAccount.entity().getAssociatedWithNetworkId(), Op.NNULL);
AllocatedIpCountForAccount.done(); AllocatedIpCountForAccount.done();
CountFreePublicIps = createSearchBuilder(Long.class); CountFreePublicIps = createSearchBuilder(Long.class);
CountFreePublicIps.select(null, Func.COUNT, null); CountFreePublicIps.select(null, Func.COUNT, null);
CountFreePublicIps.and("state", CountFreePublicIps.entity().getState(), SearchCriteria.Op.EQ); CountFreePublicIps.and("state", CountFreePublicIps.entity().getState(), SearchCriteria.Op.EQ);
@ -167,14 +166,14 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
sc.setParameters("accountId", accountId); sc.setParameters("accountId", accountId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<IPAddressVO> listByVlanId(long vlanId) { public List<IPAddressVO> listByVlanId(long vlanId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("vlan", vlanId); sc.setParameters("vlan", vlanId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public IPAddressVO findByIpAndSourceNetworkId(long networkId, String ipAddress) { public IPAddressVO findByIpAndSourceNetworkId(long networkId, String ipAddress) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
@ -197,7 +196,7 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
sc.setParameters("dataCenterId", dcId); sc.setParameters("dataCenterId", dcId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<IPAddressVO> listByDcIdIpAddress(long dcId, String ipAddress) { public List<IPAddressVO> listByDcIdIpAddress(long dcId, String ipAddress) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
@ -205,19 +204,19 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
sc.setParameters("ipAddress", ipAddress); sc.setParameters("ipAddress", ipAddress);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<IPAddressVO> listByAssociatedNetwork(long networkId, Boolean isSourceNat) { public List<IPAddressVO> listByAssociatedNetwork(long networkId, Boolean isSourceNat) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId); sc.setParameters("network", networkId);
if (isSourceNat != null) { if (isSourceNat != null) {
sc.setParameters("sourceNat", isSourceNat); sc.setParameters("sourceNat", isSourceNat);
} }
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<IPAddressVO> listStaticNatPublicIps(long networkId) { public List<IPAddressVO> listStaticNatPublicIps(long networkId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
@ -225,12 +224,12 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
sc.setParameters("oneToOneNat", true); sc.setParameters("oneToOneNat", true);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public IPAddressVO findByAssociatedVmId(long vmId) { public IPAddressVO findByAssociatedVmId(long vmId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("associatedWithVmId", vmId); sc.setParameters("associatedWithVmId", vmId);
return findOneBy(sc); return findOneBy(sc);
} }
@ -248,13 +247,13 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
SearchCriteria<Integer> sc = AllIpCountForDashboard.create(); SearchCriteria<Integer> sc = AllIpCountForDashboard.create();
sc.setParameters("dc", dcId); sc.setParameters("dc", dcId);
if (onlyCountAllocated){ if (onlyCountAllocated){
sc.setParameters("state", State.Free); sc.setParameters("state", State.Free);
} }
sc.setJoinParameters("vlan", "vlanType", vlanType.toString()); sc.setJoinParameters("vlan", "vlanType", vlanType.toString());
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@Override @Override
@DB @DB
public int countIPs(long dcId, Long accountId, String vlanId, String vlanGateway, String vlanNetmask) { public int countIPs(long dcId, Long accountId, String vlanId, String vlanGateway, String vlanNetmask) {
@ -285,35 +284,35 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
public IPAddressVO markAsUnavailable(long ipAddressId) { public IPAddressVO markAsUnavailable(long ipAddressId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("id", ipAddressId); sc.setParameters("id", ipAddressId);
IPAddressVO ip = createForUpdate(); IPAddressVO ip = createForUpdate();
ip.setState(State.Releasing); ip.setState(State.Releasing);
if (update(ip, sc) != 1) { if (update(ip, sc) != 1) {
return null; return null;
} }
return findOneBy(sc); return findOneBy(sc);
} }
@Override @Override
public long countAllocatedIPsForAccount(long accountId) { public long countAllocatedIPsForAccount(long accountId) {
SearchCriteria<Long> sc = AllocatedIpCountForAccount.create(); SearchCriteria<Long> sc = AllocatedIpCountForAccount.create();
sc.setParameters("account", accountId); sc.setParameters("account", accountId);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@Override @Override
public List<IPAddressVO> listByPhysicalNetworkId(long physicalNetworkId) { public List<IPAddressVO> listByPhysicalNetworkId(long physicalNetworkId) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("physicalNetworkId", physicalNetworkId); sc.setParameters("physicalNetworkId", physicalNetworkId);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public long countFreePublicIPs() { public long countFreePublicIPs() {
SearchCriteria<Long> sc = CountFreePublicIps.create(); SearchCriteria<Long> sc = CountFreePublicIps.create();
sc.setParameters("state", State.Free); sc.setParameters("state", State.Free);
sc.setJoinParameters("vlans", "vlanType", VlanType.VirtualNetwork); sc.setJoinParameters("vlans", "vlanType", VlanType.VirtualNetwork);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@ -321,21 +320,22 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
public List<IPAddressVO> listByAssociatedVpc(long vpcId, Boolean isSourceNat) { public List<IPAddressVO> listByAssociatedVpc(long vpcId, Boolean isSourceNat) {
SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create(); SearchCriteria<IPAddressVO> sc = AllFieldsSearch.create();
sc.setParameters("vpcId", vpcId); sc.setParameters("vpcId", vpcId);
if (isSourceNat != null) { if (isSourceNat != null) {
sc.setParameters("sourceNat", isSourceNat); sc.setParameters("sourceNat", isSourceNat);
} }
return listBy(sc); return listBy(sc);
} }
@Override
public long countFreeIPsInNetwork(long networkId) { public long countFreeIPsInNetwork(long networkId) {
SearchCriteria<Long> sc = CountFreePublicIps.create(); SearchCriteria<Long> sc = CountFreePublicIps.create();
sc.setParameters("state", State.Free); sc.setParameters("state", State.Free);
sc.setParameters("networkId", networkId); sc.setParameters("networkId", networkId);
return customSearch(sc, null).get(0); return customSearch(sc, null).get(0);
} }
@Override @Override
@DB @DB
public boolean remove(Long id) { public boolean remove(Long id) {

View File

@ -29,7 +29,6 @@ import org.springframework.stereotype.Component;
import com.cloud.network.LoadBalancerVO; import com.cloud.network.LoadBalancerVO;
import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.FirewallRule.State;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -135,5 +134,5 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
sc.setParameters("state", State.Add.toString(), State.Revoke.toString()); sc.setParameters("state", State.Add.toString(), State.Revoke.toString());
return listBy(sc); return listBy(sc);
} }
} }

View File

@ -45,7 +45,6 @@ import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDaoImpl; import com.cloud.offerings.dao.NetworkOfferingDaoImpl;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -25,23 +25,20 @@ import org.springframework.stereotype.Component;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PhysicalNetworkVO;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria.Op;
@Component @Component
@Local(value=PhysicalNetworkDao.class) @DB(txn=false) @Local(value=PhysicalNetworkDao.class) @DB(txn=false)
public class PhysicalNetworkDaoImpl extends GenericDaoBase<PhysicalNetworkVO, Long> implements PhysicalNetworkDao { public class PhysicalNetworkDaoImpl extends GenericDaoBase<PhysicalNetworkVO, Long> implements PhysicalNetworkDao {
final SearchBuilder<PhysicalNetworkVO> ZoneSearch; final SearchBuilder<PhysicalNetworkVO> ZoneSearch;
@Inject protected PhysicalNetworkTrafficTypeDaoImpl _trafficTypeDao; @Inject protected PhysicalNetworkTrafficTypeDaoImpl _trafficTypeDao;
protected PhysicalNetworkDaoImpl() { protected PhysicalNetworkDaoImpl() {
super(); super();
ZoneSearch = createSearchBuilder(); ZoneSearch = createSearchBuilder();
@ -65,7 +62,7 @@ public class PhysicalNetworkDaoImpl extends GenericDaoBase<PhysicalNetworkVO, Lo
@Override @Override
public List<PhysicalNetworkVO> listByZoneAndTrafficType(long dataCenterId, TrafficType trafficType) { public List<PhysicalNetworkVO> listByZoneAndTrafficType(long dataCenterId, TrafficType trafficType) {
SearchBuilder<PhysicalNetworkTrafficTypeVO> trafficTypeSearch = _trafficTypeDao.createSearchBuilder(); SearchBuilder<PhysicalNetworkTrafficTypeVO> trafficTypeSearch = _trafficTypeDao.createSearchBuilder();
PhysicalNetworkTrafficTypeVO trafficTypeEntity = trafficTypeSearch.entity(); PhysicalNetworkTrafficTypeVO trafficTypeEntity = trafficTypeSearch.entity();
trafficTypeSearch.and("trafficType", trafficTypeSearch.entity().getTrafficType(), SearchCriteria.Op.EQ); trafficTypeSearch.and("trafficType", trafficTypeSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);

View File

@ -25,10 +25,8 @@ import javax.inject.Inject;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.network.IPAddressVO;
import com.cloud.network.Site2SiteVpnConnectionVO; import com.cloud.network.Site2SiteVpnConnectionVO;
import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.Site2SiteVpnGatewayVO;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.JoinBuilder.JoinType; import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
@ -41,35 +39,35 @@ public class Site2SiteVpnConnectionDaoImpl extends GenericDaoBase<Site2SiteVpnCo
@Inject protected IPAddressDaoImpl _addrDao; @Inject protected IPAddressDaoImpl _addrDao;
@Inject protected Site2SiteVpnGatewayDaoImpl _vpnGatewayDao; @Inject protected Site2SiteVpnGatewayDaoImpl _vpnGatewayDao;
private SearchBuilder<Site2SiteVpnConnectionVO> AllFieldsSearch; private SearchBuilder<Site2SiteVpnConnectionVO> AllFieldsSearch;
private SearchBuilder<Site2SiteVpnConnectionVO> VpcSearch; private SearchBuilder<Site2SiteVpnConnectionVO> VpcSearch;
private SearchBuilder<Site2SiteVpnGatewayVO> VpnGatewaySearch; private SearchBuilder<Site2SiteVpnGatewayVO> VpnGatewaySearch;
public Site2SiteVpnConnectionDaoImpl() { public Site2SiteVpnConnectionDaoImpl() {
} }
@PostConstruct @PostConstruct
protected void init() { protected void init() {
AllFieldsSearch = createSearchBuilder(); AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("customerGatewayId", AllFieldsSearch.entity().getCustomerGatewayId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("customerGatewayId", AllFieldsSearch.entity().getCustomerGatewayId(), SearchCriteria.Op.EQ);
AllFieldsSearch.and("vpnGatewayId", AllFieldsSearch.entity().getVpnGatewayId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("vpnGatewayId", AllFieldsSearch.entity().getVpnGatewayId(), SearchCriteria.Op.EQ);
AllFieldsSearch.done(); AllFieldsSearch.done();
VpcSearch = createSearchBuilder(); VpcSearch = createSearchBuilder();
VpnGatewaySearch = _vpnGatewayDao.createSearchBuilder(); VpnGatewaySearch = _vpnGatewayDao.createSearchBuilder();
VpnGatewaySearch.and("vpcId", VpnGatewaySearch.entity().getVpcId(), SearchCriteria.Op.EQ); VpnGatewaySearch.and("vpcId", VpnGatewaySearch.entity().getVpcId(), SearchCriteria.Op.EQ);
VpcSearch.join("vpnGatewaySearch", VpnGatewaySearch, VpnGatewaySearch.entity().getId(), VpcSearch.entity().getVpnGatewayId(), JoinType.INNER); VpcSearch.join("vpnGatewaySearch", VpnGatewaySearch, VpnGatewaySearch.entity().getId(), VpcSearch.entity().getVpnGatewayId(), JoinType.INNER);
VpcSearch.done(); VpcSearch.done();
} }
@Override @Override
public List<Site2SiteVpnConnectionVO> listByCustomerGatewayId(long id) { public List<Site2SiteVpnConnectionVO> listByCustomerGatewayId(long id) {
SearchCriteria<Site2SiteVpnConnectionVO> sc = AllFieldsSearch.create(); SearchCriteria<Site2SiteVpnConnectionVO> sc = AllFieldsSearch.create();
sc.setParameters("customerGatewayId", id); sc.setParameters("customerGatewayId", id);
return listBy(sc); return listBy(sc);
} }
@Override @Override
public List<Site2SiteVpnConnectionVO> listByVpnGatewayId(long id) { public List<Site2SiteVpnConnectionVO> listByVpnGatewayId(long id) {
SearchCriteria<Site2SiteVpnConnectionVO> sc = AllFieldsSearch.create(); SearchCriteria<Site2SiteVpnConnectionVO> sc = AllFieldsSearch.create();

View File

@ -23,7 +23,6 @@ import org.apache.log4j.Logger;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.Site2SiteVpnGatewayVO;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;
@ -32,9 +31,9 @@ import com.cloud.utils.db.SearchCriteria;
@Local(value={Site2SiteVpnGatewayDao.class}) @Local(value={Site2SiteVpnGatewayDao.class})
public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase<Site2SiteVpnGatewayVO, Long> implements Site2SiteVpnGatewayDao { public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase<Site2SiteVpnGatewayVO, Long> implements Site2SiteVpnGatewayDao {
@Inject protected IPAddressDaoImpl _addrDao; @Inject protected IPAddressDaoImpl _addrDao;
private static final Logger s_logger = Logger.getLogger(Site2SiteVpnGatewayDaoImpl.class); private static final Logger s_logger = Logger.getLogger(Site2SiteVpnGatewayDaoImpl.class);
private final SearchBuilder<Site2SiteVpnGatewayVO> AllFieldsSearch; private final SearchBuilder<Site2SiteVpnGatewayVO> AllFieldsSearch;
protected Site2SiteVpnGatewayDaoImpl() { protected Site2SiteVpnGatewayDaoImpl() {
@ -42,7 +41,7 @@ public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase<Site2SiteVpnGatew
AllFieldsSearch.and("vpcId", AllFieldsSearch.entity().getVpcId(), SearchCriteria.Op.EQ); AllFieldsSearch.and("vpcId", AllFieldsSearch.entity().getVpcId(), SearchCriteria.Op.EQ);
AllFieldsSearch.done(); AllFieldsSearch.done();
} }
@Override @Override
public Site2SiteVpnGatewayVO findByVpcId(long vpcId) { public Site2SiteVpnGatewayVO findByVpcId(long vpcId) {
SearchCriteria<Site2SiteVpnGatewayVO> sc = AllFieldsSearch.create(); SearchCriteria<Site2SiteVpnGatewayVO> sc = AllFieldsSearch.create();

View File

@ -46,7 +46,7 @@ import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType; import com.cloud.network.Networks.TrafficType;
import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import com.cloud.vm.Nic; import com.cloud.vm.Nic;

View File

@ -206,7 +206,7 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.StringUtils; import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;

View File

@ -27,7 +27,7 @@ import com.cloud.network.dao.FirewallRulesCidrsDaoImpl;
import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.PortForwardingRuleVO; import com.cloud.network.rules.PortForwardingRuleVO;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria;

View File

@ -87,7 +87,7 @@ import com.cloud.uservm.UserVm;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;

View File

@ -26,7 +26,7 @@ import org.springframework.stereotype.Component;
import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.SecurityGroupVO;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchBuilder;

View File

@ -99,7 +99,7 @@ import com.cloud.user.UserContext;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;

View File

@ -27,7 +27,7 @@ import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.StaticRouteVO; import com.cloud.network.vpc.StaticRouteVO;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -27,7 +27,7 @@ import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.VpcVO;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -70,7 +70,7 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator; import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;

View File

@ -70,7 +70,7 @@ import com.cloud.user.dao.AccountDao;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter; import com.cloud.utils.db.Filter;

View File

@ -28,7 +28,7 @@ import com.cloud.projects.Project;
import com.cloud.projects.ProjectVO; import com.cloud.projects.ProjectVO;
import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl; import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GenericSearchBuilder;

View File

@ -34,7 +34,7 @@ import com.cloud.dc.dao.ClusterDao;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.network.NetworkManager; import com.cloud.network.NetworkManager;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.net.UrlUtil; import com.cloud.utils.net.UrlUtil;
public abstract class DiscovererBase implements Discoverer { public abstract class DiscovererBase implements Discoverer {

View File

@ -46,7 +46,7 @@ import com.cloud.user.User;
import com.cloud.uservm.UserVm; import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.Ternary; import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine;

View File

@ -37,7 +37,7 @@ import com.cloud.user.User;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.utils.SerialVersionUID; import com.cloud.utils.SerialVersionUID;
import com.cloud.utils.component.ComponentLocator;
public class RegisterCompleteServlet extends HttpServlet implements ServletContextListener { public class RegisterCompleteServlet extends HttpServlet implements ServletContextListener {
public static final Logger s_logger = Logger.getLogger(RegisterCompleteServlet.class.getName()); public static final Logger s_logger = Logger.getLogger(RegisterCompleteServlet.class.getName());

View File

@ -173,7 +173,7 @@ import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import com.cloud.utils.UriUtils; import com.cloud.utils.UriUtils;
import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Manager; import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB; import com.cloud.utils.db.DB;

View File

@ -25,7 +25,7 @@ import com.cloud.cluster.CheckPointManager;
import com.cloud.cluster.CleanupMaid; import com.cloud.cluster.CleanupMaid;
import com.cloud.server.ManagementServer; import com.cloud.server.ManagementServer;
import com.cloud.storage.dao.VolumeDao; import com.cloud.storage.dao.VolumeDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Transaction; import com.cloud.utils.db.Transaction;
import com.cloud.utils.fsm.NoTransitionException; import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateMachine2;

Some files were not shown because too many files have changed in this diff Show More