Search in sources :

Example 26 with Ternary

use of com.cloud.utils.Ternary in project cloudstack by apache.

the class VirtualMachineMO method backupCurrentSnapshot.

// destName does not contain extension name
public void backupCurrentSnapshot(String deviceName, ManagedObjectReference morDestDs, String destDsDirectory, String destName, boolean includeBase) throws Exception {
    SnapshotDescriptor descriptor = getSnapshotDescriptor();
    SnapshotInfo[] snapshotInfo = descriptor.getCurrentDiskChain();
    if (snapshotInfo.length == 0) {
        String msg = "No snapshot found in this VM";
        throw new Exception(msg);
    }
    HostMO hostMo = getRunningHost();
    DatacenterMO dcMo = getOwnerDatacenter().first();
    List<Pair<ManagedObjectReference, String>> mounts = hostMo.getDatastoreMountsOnHost();
    VirtualMachineFileInfo vmFileInfo = getFileInfo();
    List<Ternary<String, String, String>> backupInfo = new ArrayList<Ternary<String, String, String>>();
    for (int i = 0; i < snapshotInfo.length; i++) {
        if (!includeBase && i == snapshotInfo.length - 1) {
            break;
        }
        SnapshotDescriptor.DiskInfo[] disks = snapshotInfo[i].getDisks();
        if (disks != null) {
            String destBaseFileName;
            String destFileName;
            String destParentFileName;
            for (SnapshotDescriptor.DiskInfo disk : disks) {
                if (deviceName == null || deviceName.equals(disk.getDeviceName())) {
                    String srcVmdkFullDsPath = getSnapshotDiskFileDatastorePath(vmFileInfo, mounts, disk.getDiskFileName());
                    Pair<DatastoreMO, String> srcDsInfo = getOwnerDatastore(srcVmdkFullDsPath);
                    Pair<VmdkFileDescriptor, byte[]> vmdkInfo = getVmdkFileInfo(srcVmdkFullDsPath);
                    String srcVmdkBaseFilePath = DatastoreFile.getCompanionDatastorePath(srcVmdkFullDsPath, vmdkInfo.first().getBaseFileName());
                    destFileName = destName + (snapshotInfo.length - i - 1) + ".vmdk";
                    if (vmdkInfo.first().getParentFileName() != null) {
                        destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-delta.vmdk";
                        destParentFileName = destName + (snapshotInfo.length - i - 2) + ".vmdk";
                    } else {
                        destBaseFileName = destName + (snapshotInfo.length - i - 1) + "-flat.vmdk";
                        destParentFileName = null;
                    }
                    s_logger.info("Copy VMDK base file " + srcVmdkBaseFilePath + " to " + destDsDirectory + "/" + destBaseFileName);
                    srcDsInfo.first().copyDatastoreFile(srcVmdkBaseFilePath, dcMo.getMor(), morDestDs, destDsDirectory + "/" + destBaseFileName, dcMo.getMor(), true);
                    byte[] newVmdkContent = VmdkFileDescriptor.changeVmdkContentBaseInfo(vmdkInfo.second(), destBaseFileName, destParentFileName);
                    String vmdkUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destFileName);
                    s_logger.info("Upload VMDK content file to " + destDsDirectory + "/" + destFileName);
                    getContext().uploadResourceContent(vmdkUploadUrl, newVmdkContent);
                    backupInfo.add(new Ternary<String, String, String>(destFileName, destBaseFileName, destParentFileName));
                }
            }
        }
    }
    byte[] vdiskInfo = VmwareHelper.composeDiskInfo(backupInfo, snapshotInfo.length, includeBase);
    String vdiskUploadUrl = getContext().composeDatastoreBrowseUrl(dcMo.getName(), destDsDirectory + "/" + destName + ".vdisk");
    getContext().uploadResourceContent(vdiskUploadUrl, vdiskInfo);
}
Also used : Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) VirtualMachineSnapshotInfo(com.vmware.vim25.VirtualMachineSnapshotInfo) SnapshotInfo(com.cloud.hypervisor.vmware.mo.SnapshotDescriptor.SnapshotInfo) VirtualMachineFileInfo(com.vmware.vim25.VirtualMachineFileInfo) Pair(com.cloud.utils.Pair)

Example 27 with Ternary

use of com.cloud.utils.Ternary in project CloudStack-archive by CloudStack-extras.

the class GenericDaoBase method update.

public int update(UpdateBuilder ub, final SearchCriteria<?> sc, Integer rows) {
    StringBuilder sql = null;
    PreparedStatement pstmt = null;
    final Transaction txn = Transaction.currentTxn();
    try {
        final String searchClause = sc.getWhereClause();
        sql = ub.toSql(_tables);
        if (sql == null) {
            return 0;
        }
        sql.append(searchClause);
        if (rows != null) {
            sql.append(" LIMIT ").append(rows);
        }
        txn.start();
        pstmt = txn.prepareAutoCloseStatement(sql.toString());
        Collection<Ternary<Attribute, Boolean, Object>> changes = ub.getChanges();
        int i = 1;
        for (final Ternary<Attribute, Boolean, Object> value : changes) {
            prepareAttribute(i++, pstmt, value.first(), value.third());
        }
        for (Pair<Attribute, Object> value : sc.getValues()) {
            prepareAttribute(i++, pstmt, value.first(), value.second());
        }
        int result = pstmt.executeUpdate();
        txn.commit();
        ub.clear();
        return result;
    } catch (final SQLException e) {
        if (e.getSQLState().equals("23000") && e.getErrorCode() == 1062) {
            throw new EntityExistsException("Entity already exists ", e);
        }
        throw new CloudRuntimeException("DB Exception on: " + pstmt, e);
    }
}
Also used : Ternary(com.cloud.utils.Ternary) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) EntityExistsException(javax.persistence.EntityExistsException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 28 with Ternary

use of com.cloud.utils.Ternary in project CloudStack-archive by CloudStack-extras.

the class Merovingian method doAcquire.

protected boolean doAcquire(String key) {
    Connection conn = getConnection(key, true);
    PreparedStatement pstmt = null;
    Savepoint sp = null;
    try {
        sp = conn.setSavepoint(key);
    } catch (SQLException e) {
        s_logger.warn("Unable to set save point " + key);
        return false;
    }
    try {
        long startTime = InaccurateClock.getTime();
        try {
            pstmt = conn.prepareStatement(ACQUIRE_SQL);
            pstmt.setString(1, key);
            pstmt.setString(2, s_macAddress);
            pstmt.setString(3, s_ipAddress);
            pstmt.setString(4, Thread.currentThread().getName());
            String exceptionMessage = null;
            int rows = pstmt.executeUpdate();
            if (rows == 1) {
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Lock: lock acquired for " + key);
                }
                Ternary<Savepoint, Integer, Long> lock = new Ternary<Savepoint, Integer, Long>(sp, 1, InaccurateClock.getTime());
                _locks.put(key, lock);
                return true;
            }
        } catch (SQLException e) {
            s_logger.warn("Lock: Retrying lock " + key + ".  Waited " + (InaccurateClock.getTime() - startTime), e);
        }
        conn.rollback(sp);
        s_logger.trace("Lock: Unable to acquire DB lock " + key);
    } catch (SQLException e) {
        s_logger.warn("Lock: Unable to acquire db connection for locking " + key, e);
    } finally {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
            }
        }
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) Ternary(com.cloud.utils.Ternary) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Savepoint(java.sql.Savepoint) Savepoint(java.sql.Savepoint)

Example 29 with Ternary

use of com.cloud.utils.Ternary in project cloudstack by apache.

the class VirtualMachineManagerImpl method changeToStartState.

@DB
protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> changeToStartState(final VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User caller, final Account account) throws ConcurrentOperationException {
    final long vmId = vm.getId();
    ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
    int retry = VmOpLockStateRetry.value();
    while (retry-- != 0) {
        try {
            final ItWorkVO workFinal = work;
            final Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result = Transaction.execute(new TransactionCallbackWithException<Ternary<VMInstanceVO, ReservationContext, ItWorkVO>, NoTransitionException>() {

                @Override
                public Ternary<VMInstanceVO, ReservationContext, ItWorkVO> doInTransaction(final TransactionStatus status) throws NoTransitionException {
                    final Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
                    final ItWorkVO work = _workDao.persist(workFinal);
                    final ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
                    if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
                        }
                        return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(vm, context, work);
                    }
                    return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(null, null, work);
                }
            });
            work = result.third();
            if (result.first() != null) {
                return result;
            }
        } catch (final NoTransitionException e) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
            }
        }
        final VMInstanceVO instance = _vmDao.findById(vmId);
        if (instance == null) {
            throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ".  Retry=" + retry);
        }
        final State state = instance.getState();
        if (state == State.Running) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("VM is already started: " + vm);
            }
            return null;
        }
        if (state.isTransitional()) {
            if (!checkWorkItems(vm, state)) {
                throw new ConcurrentOperationException("There are concurrent operations on " + vm);
            } else {
                continue;
            }
        }
        if (state != State.Stopped) {
            s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
            return null;
        }
    }
    throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
Also used : Ternary(com.cloud.utils.Ternary) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) PowerState(com.cloud.vm.VirtualMachine.PowerState) State(com.cloud.vm.VirtualMachine.State) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) DB(com.cloud.utils.db.DB)

Example 30 with Ternary

use of com.cloud.utils.Ternary in project cloudstack by apache.

the class GenericDaoBase method update.

public int update(UpdateBuilder ub, final SearchCriteria<?> sc, Integer rows) {
    StringBuilder sql = null;
    PreparedStatement pstmt = null;
    final TransactionLegacy txn = TransactionLegacy.currentTxn();
    try {
        final String searchClause = sc.getWhereClause();
        sql = ub.toSql(_tables);
        if (sql == null) {
            return 0;
        }
        sql.append(searchClause);
        if (rows != null) {
            sql.append(" LIMIT ").append(rows);
        }
        txn.start();
        pstmt = txn.prepareAutoCloseStatement(sql.toString());
        Collection<Ternary<Attribute, Boolean, Object>> changes = ub.getChanges();
        int i = 1;
        for (final Ternary<Attribute, Boolean, Object> value : changes) {
            prepareAttribute(i++, pstmt, value.first(), value.third());
        }
        for (Pair<Attribute, Object> value : sc.getValues()) {
            prepareAttribute(i++, pstmt, value.first(), value.second());
        }
        int result = pstmt.executeUpdate();
        txn.commit();
        ub.clear();
        return result;
    } catch (final SQLException e) {
        if (e.getSQLState().equals("23000") && e.getErrorCode() == 1062) {
            throw new EntityExistsException("Entity already exists ", e);
        }
        throw new CloudRuntimeException("DB Exception on: " + pstmt, e);
    }
}
Also used : Ternary(com.cloud.utils.Ternary) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) EntityExistsException(javax.persistence.EntityExistsException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Aggregations

Ternary (com.cloud.utils.Ternary)53 ArrayList (java.util.ArrayList)40 Account (com.cloud.user.Account)34 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)32 Filter (com.cloud.utils.db.Filter)30 List (java.util.List)29 Pair (com.cloud.utils.Pair)28 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)15 TemplateFilter (com.cloud.template.VirtualMachineTemplate.TemplateFilter)13 ResourceTagVO (com.cloud.tags.ResourceTagVO)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 IPAddressVO (com.cloud.network.dao.IPAddressVO)6 HashMap (java.util.HashMap)6 OVAProcessor (com.cloud.storage.template.OVAProcessor)4 Script (com.cloud.utils.script.Script)4 File (java.io.File)4 RemoteException (java.rmi.RemoteException)4 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)3 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)3 SSHKeyPair (com.cloud.user.SSHKeyPair)3