Program: 107446
Project: 107446
Buggy source:
@Override public void attachVolumeToVM(AttachVolumeCmd command) throws InternalErrorException, InvalidParameterValueException, PermissionDeniedException {
  Long vmId=command.getVirtualMachineId();
  Long volumeId=command.getId();
  Long deviceId=command.getDeviceId();
  Account account=UserContext.current().getAccount();
  VolumeVO volume=_volsDao.findById(volumeId);
  if (volume == null || volume.getVolumeType() != VolumeType.DATADISK) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (!_storageMgr.volumeOnSharedStoragePool(volume)) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getInstanceId() != null) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getDestroyed()) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  UserVmVO vm=_vmDao.findById(vmId);
  if (vm == null || vm.getType() != VirtualMachine.Type.User) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (deviceId != null) {
    if (deviceId.longValue() == 0) {
      throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR,"String_Node_Str");
    }
  }
  List<VolumeVO> existingDataVolumes=_volsDao.findByInstanceAndType(vmId,VolumeType.DATADISK);
  if (existingDataVolumes.size() >= 6) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (vm.getDataCenterId() != volume.getDataCenterId()) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getAccountId() != vm.getAccountId()) {
    throw new PermissionDeniedException("String_Node_Str");
  }
  if (account != null) {
    if (!isAdmin(account.getType())) {
      if (account.getId() != volume.getAccountId())       throw new PermissionDeniedException("String_Node_Str" + volumeId + "String_Node_Str"+ account.getAccountName()+ "String_Node_Str");
      if (account.getId() != vm.getAccountId())       throw new PermissionDeniedException("String_Node_Str" + vmId + "String_Node_Str"+ account.getAccountName()+ "String_Node_Str");
    }
 else {
      if (!_domainDao.isChildDomain(account.getDomainId(),volume.getDomainId()) || !_domainDao.isChildDomain(account.getDomainId(),vm.getDomainId())) {
        throw new PermissionDeniedException("String_Node_Str" + volumeId + "String_Node_Str"+ vmId+ "String_Node_Str");
      }
    }
  }
  long startEventId=EventUtils.saveScheduledEvent(1L,volume.getAccountId(),EventTypes.EVENT_VOLUME_ATTACH,"String_Node_Str" + volumeId + "String_Node_Str"+ vmId);
  EventVO event=new EventVO();
  event.setType(EventTypes.EVENT_VOLUME_ATTACH);
  event.setUserId(1L);
  event.setAccountId(volume.getAccountId());
  event.setState(EventState.Started);
  event.setStartId(startEventId);
  event.setDescription("String_Node_Str" + volumeId + "String_Node_Str"+ vmId);
  _eventDao.persist(event);
  VolumeVO rootVolumeOfVm=null;
  List<VolumeVO> rootVolumesOfVm=_volsDao.findByInstanceAndType(vmId,VolumeType.ROOT);
  if (rootVolumesOfVm.size() != 1) {
    throw new InternalErrorException("String_Node_Str" + vm.getName() + "String_Node_Str");
  }
 else {
    rootVolumeOfVm=rootVolumesOfVm.get(0);
  }
  if (volume.getState().equals(Volume.State.Allocated)) {
    VMTemplateVO rootDiskTmplt=_templateDao.findById(vm.getTemplateId());
    DataCenterVO dcVO=_dcDao.findById(vm.getDataCenterId());
    HostPodVO pod=_podDao.findById(vm.getPodId());
    StoragePoolVO rootDiskPool=_storagePoolDao.findById(rootVolumeOfVm.getPoolId());
    ServiceOfferingVO svo=_serviceOfferingDao.findById(vm.getServiceOfferingId());
    DiskOfferingVO diskVO=_diskOfferingDao.findById(volume.getDiskOfferingId());
    HypervisorType rootDiskHyperType=_volsDao.getHypervisorType(rootVolumeOfVm.getId());
    volume=_storageMgr.createVolume(volume,vm,rootDiskTmplt,dcVO,pod,rootDiskPool.getClusterId(),svo,diskVO,new ArrayList<StoragePoolVO>(),volume.getSize(),rootDiskHyperType);
    if (volume == null) {
      throw new InternalErrorException("String_Node_Str" + vm.getName());
    }
  }
  List<VolumeVO> vols=_volsDao.findByInstance(vmId);
  if (deviceId != null) {
    if (deviceId.longValue() > 15 || deviceId.longValue() == 0 || deviceId.longValue() == 3) {
      throw new RuntimeException("String_Node_Str");
    }
    for (    VolumeVO vol : vols) {
      if (vol.getDeviceId().equals(deviceId)) {
        throw new RuntimeException("String_Node_Str" + deviceId + "String_Node_Str"+ vm.getName());
      }
    }
  }
 else {
    List<String> devIds=new ArrayList<String>();
    for (int i=1; i < 15; i++) {
      devIds.add(String.valueOf(i));
    }
    devIds.remove("String_Node_Str");
    for (    VolumeVO vol : vols) {
      devIds.remove(vol.getDeviceId().toString().trim());
    }
    deviceId=Long.parseLong(devIds.iterator().next());
  }
  StoragePoolVO vmRootVolumePool=_storagePoolDao.findById(rootVolumeOfVm.getPoolId());
  DiskOfferingVO volumeDiskOffering=_diskOfferingDao.findById(volume.getDiskOfferingId());
  String[] volumeTags=volumeDiskOffering.getTagsArray();
  StoragePoolVO sourcePool=_storagePoolDao.findById(volume.getPoolId());
  List<StoragePoolVO> sharedVMPools=_storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(),vmRootVolumePool.getPodId(),vmRootVolumePool.getClusterId(),volumeTags,true);
  boolean moveVolumeNeeded=true;
  if (sharedVMPools.size() == 0) {
    String poolType;
    if (vmRootVolumePool.getClusterId() != null) {
      poolType="String_Node_Str";
    }
 else     if (vmRootVolumePool.getPodId() != null) {
      poolType="String_Node_Str";
    }
 else {
      poolType="String_Node_Str";
    }
    throw new InternalErrorException("String_Node_Str" + poolType + "String_Node_Str"+ volumeDiskOffering.getTags()+ "String_Node_Str");
  }
 else {
    Long sourcePoolDcId=sourcePool.getDataCenterId();
    Long sourcePoolPodId=sourcePool.getPodId();
    Long sourcePoolClusterId=sourcePool.getClusterId();
    for (    StoragePoolVO vmPool : sharedVMPools) {
      Long vmPoolDcId=vmPool.getDataCenterId();
      Long vmPoolPodId=vmPool.getPodId();
      Long vmPoolClusterId=vmPool.getClusterId();
      if (sourcePoolDcId == vmPoolDcId && sourcePoolPodId == vmPoolPodId && sourcePoolClusterId == vmPoolClusterId) {
        moveVolumeNeeded=false;
        break;
      }
    }
  }
  if (moveVolumeNeeded) {
    volume=_storageMgr.moveVolume(volume,vmRootVolumePool.getDataCenterId(),vmRootVolumePool.getPodId(),vmRootVolumePool.getClusterId());
  }
  AsyncJobExecutor asyncExecutor=BaseAsyncJobExecutor.getCurrentExecutor();
  if (asyncExecutor != null) {
    AsyncJobVO job=asyncExecutor.getJob();
    if (s_logger.isInfoEnabled())     s_logger.info("String_Node_Str" + volumeId + "String_Node_Str"+ vm.getId()+ "String_Node_Str"+ job.getId()+ "String_Node_Str");
    _asyncMgr.updateAsyncJobAttachment(job.getId(),"String_Node_Str",volumeId);
    _asyncMgr.updateAsyncJobStatus(job.getId(),BaseCmd.PROGRESS_INSTANCE_CREATED,volumeId);
  }
  String errorMsg="String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName();
  boolean sendCommand=(vm.getState() == State.Running);
  AttachVolumeAnswer answer=null;
  Long hostId=vm.getHostId();
  if (sendCommand) {
    StoragePoolVO volumePool=_storagePoolDao.findById(volume.getPoolId());
    AttachVolumeCommand cmd=new AttachVolumeCommand(true,vm.getInstanceName(),volume.getPoolType(),volume.getFolder(),volume.getPath(),volume.getName(),deviceId);
    cmd.setPoolUuid(volumePool.getUuid());
    try {
      answer=(AttachVolumeAnswer)_agentMgr.send(hostId,cmd);
    }
 catch (    Exception e) {
      throw new InternalErrorException(errorMsg + "String_Node_Str" + e.getMessage());
    }
  }
  event=new EventVO();
  event.setAccountId(volume.getAccountId());
  event.setUserId(1L);
  event.setType(EventTypes.EVENT_VOLUME_ATTACH);
  event.setState(EventState.Completed);
  event.setStartId(startEventId);
  if (!sendCommand || (answer != null && answer.getResult())) {
    if (sendCommand) {
      _volsDao.attachVolume(volume.getId(),vmId,answer.getDeviceId());
    }
 else {
      _volsDao.attachVolume(volume.getId(),vmId,deviceId);
    }
    if (!vm.getName().equals(vm.getDisplayName()))     event.setDescription("String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName()+ "String_Node_Str"+ vm.getDisplayName()+ "String_Node_Str");
 else     event.setDescription("String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName());
    event.setLevel(EventVO.LEVEL_INFO);
    _eventDao.persist(event);
  }
 else {
    if (answer != null) {
      String details=answer.getDetails();
      if (details != null && !details.isEmpty())       errorMsg+="String_Node_Str" + details;
    }
    throw new InternalErrorException(errorMsg);
  }
}

Fixed version (ground truth):
@Override public void attachVolumeToVM(AttachVolumeCmd command) throws InternalErrorException, InvalidParameterValueException, PermissionDeniedException {
  Long vmId=command.getVirtualMachineId();
  Long volumeId=command.getId();
  Long deviceId=command.getDeviceId();
  Account account=UserContext.current().getAccount();
  VolumeVO volume=_volsDao.findById(volumeId);
  if (volume == null || volume.getVolumeType() != VolumeType.DATADISK) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (!Volume.State.Allocated.equals(volume.getState()) && !_storageMgr.volumeOnSharedStoragePool(volume)) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getInstanceId() != null) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getDestroyed()) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  UserVmVO vm=_vmDao.findById(vmId);
  if (vm == null || vm.getType() != VirtualMachine.Type.User) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (deviceId != null) {
    if (deviceId.longValue() == 0) {
      throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR,"String_Node_Str");
    }
  }
  List<VolumeVO> existingDataVolumes=_volsDao.findByInstanceAndType(vmId,VolumeType.DATADISK);
  if (existingDataVolumes.size() >= 6) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (vm.getDataCenterId() != volume.getDataCenterId()) {
    throw new InvalidParameterValueException("String_Node_Str");
  }
  if (volume.getAccountId() != vm.getAccountId()) {
    throw new PermissionDeniedException("String_Node_Str");
  }
  if (account != null) {
    if (!isAdmin(account.getType())) {
      if (account.getId() != volume.getAccountId())       throw new PermissionDeniedException("String_Node_Str" + volumeId + "String_Node_Str"+ account.getAccountName()+ "String_Node_Str");
      if (account.getId() != vm.getAccountId())       throw new PermissionDeniedException("String_Node_Str" + vmId + "String_Node_Str"+ account.getAccountName()+ "String_Node_Str");
    }
 else {
      if (!_domainDao.isChildDomain(account.getDomainId(),volume.getDomainId()) || !_domainDao.isChildDomain(account.getDomainId(),vm.getDomainId())) {
        throw new PermissionDeniedException("String_Node_Str" + volumeId + "String_Node_Str"+ vmId+ "String_Node_Str");
      }
    }
  }
  long startEventId=EventUtils.saveScheduledEvent(1L,volume.getAccountId(),EventTypes.EVENT_VOLUME_ATTACH,"String_Node_Str" + volumeId + "String_Node_Str"+ vmId);
  EventVO event=new EventVO();
  event.setType(EventTypes.EVENT_VOLUME_ATTACH);
  event.setUserId(1L);
  event.setAccountId(volume.getAccountId());
  event.setState(EventState.Started);
  event.setStartId(startEventId);
  event.setDescription("String_Node_Str" + volumeId + "String_Node_Str"+ vmId);
  _eventDao.persist(event);
  VolumeVO rootVolumeOfVm=null;
  List<VolumeVO> rootVolumesOfVm=_volsDao.findByInstanceAndType(vmId,VolumeType.ROOT);
  if (rootVolumesOfVm.size() != 1) {
    throw new InternalErrorException("String_Node_Str" + vm.getName() + "String_Node_Str");
  }
 else {
    rootVolumeOfVm=rootVolumesOfVm.get(0);
  }
  if (volume.getState().equals(Volume.State.Allocated)) {
    VMTemplateVO rootDiskTmplt=_templateDao.findById(vm.getTemplateId());
    DataCenterVO dcVO=_dcDao.findById(vm.getDataCenterId());
    HostPodVO pod=_podDao.findById(vm.getPodId());
    StoragePoolVO rootDiskPool=_storagePoolDao.findById(rootVolumeOfVm.getPoolId());
    ServiceOfferingVO svo=_serviceOfferingDao.findById(vm.getServiceOfferingId());
    DiskOfferingVO diskVO=_diskOfferingDao.findById(volume.getDiskOfferingId());
    HypervisorType rootDiskHyperType=_volsDao.getHypervisorType(rootVolumeOfVm.getId());
    volume=_storageMgr.createVolume(volume,vm,rootDiskTmplt,dcVO,pod,rootDiskPool.getClusterId(),svo,diskVO,new ArrayList<StoragePoolVO>(),volume.getSize(),rootDiskHyperType);
    if (volume == null) {
      throw new InternalErrorException("String_Node_Str" + vm.getName());
    }
  }
  List<VolumeVO> vols=_volsDao.findByInstance(vmId);
  if (deviceId != null) {
    if (deviceId.longValue() > 15 || deviceId.longValue() == 0 || deviceId.longValue() == 3) {
      throw new RuntimeException("String_Node_Str");
    }
    for (    VolumeVO vol : vols) {
      if (vol.getDeviceId().equals(deviceId)) {
        throw new RuntimeException("String_Node_Str" + deviceId + "String_Node_Str"+ vm.getName());
      }
    }
  }
 else {
    List<String> devIds=new ArrayList<String>();
    for (int i=1; i < 15; i++) {
      devIds.add(String.valueOf(i));
    }
    devIds.remove("String_Node_Str");
    for (    VolumeVO vol : vols) {
      devIds.remove(vol.getDeviceId().toString().trim());
    }
    deviceId=Long.parseLong(devIds.iterator().next());
  }
  StoragePoolVO vmRootVolumePool=_storagePoolDao.findById(rootVolumeOfVm.getPoolId());
  DiskOfferingVO volumeDiskOffering=_diskOfferingDao.findById(volume.getDiskOfferingId());
  String[] volumeTags=volumeDiskOffering.getTagsArray();
  StoragePoolVO sourcePool=_storagePoolDao.findById(volume.getPoolId());
  List<StoragePoolVO> sharedVMPools=_storagePoolDao.findPoolsByTags(vmRootVolumePool.getDataCenterId(),vmRootVolumePool.getPodId(),vmRootVolumePool.getClusterId(),volumeTags,true);
  boolean moveVolumeNeeded=true;
  if (sharedVMPools.size() == 0) {
    String poolType;
    if (vmRootVolumePool.getClusterId() != null) {
      poolType="String_Node_Str";
    }
 else     if (vmRootVolumePool.getPodId() != null) {
      poolType="String_Node_Str";
    }
 else {
      poolType="String_Node_Str";
    }
    throw new InternalErrorException("String_Node_Str" + poolType + "String_Node_Str"+ volumeDiskOffering.getTags()+ "String_Node_Str");
  }
 else {
    Long sourcePoolDcId=sourcePool.getDataCenterId();
    Long sourcePoolPodId=sourcePool.getPodId();
    Long sourcePoolClusterId=sourcePool.getClusterId();
    for (    StoragePoolVO vmPool : sharedVMPools) {
      Long vmPoolDcId=vmPool.getDataCenterId();
      Long vmPoolPodId=vmPool.getPodId();
      Long vmPoolClusterId=vmPool.getClusterId();
      if (sourcePoolDcId == vmPoolDcId && sourcePoolPodId == vmPoolPodId && sourcePoolClusterId == vmPoolClusterId) {
        moveVolumeNeeded=false;
        break;
      }
    }
  }
  if (moveVolumeNeeded) {
    volume=_storageMgr.moveVolume(volume,vmRootVolumePool.getDataCenterId(),vmRootVolumePool.getPodId(),vmRootVolumePool.getClusterId());
  }
  AsyncJobExecutor asyncExecutor=BaseAsyncJobExecutor.getCurrentExecutor();
  if (asyncExecutor != null) {
    AsyncJobVO job=asyncExecutor.getJob();
    if (s_logger.isInfoEnabled())     s_logger.info("String_Node_Str" + volumeId + "String_Node_Str"+ vm.getId()+ "String_Node_Str"+ job.getId()+ "String_Node_Str");
    _asyncMgr.updateAsyncJobAttachment(job.getId(),"String_Node_Str",volumeId);
    _asyncMgr.updateAsyncJobStatus(job.getId(),BaseCmd.PROGRESS_INSTANCE_CREATED,volumeId);
  }
  String errorMsg="String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName();
  boolean sendCommand=(vm.getState() == State.Running);
  AttachVolumeAnswer answer=null;
  Long hostId=vm.getHostId();
  if (sendCommand) {
    StoragePoolVO volumePool=_storagePoolDao.findById(volume.getPoolId());
    AttachVolumeCommand cmd=new AttachVolumeCommand(true,vm.getInstanceName(),volume.getPoolType(),volume.getFolder(),volume.getPath(),volume.getName(),deviceId);
    cmd.setPoolUuid(volumePool.getUuid());
    try {
      answer=(AttachVolumeAnswer)_agentMgr.send(hostId,cmd);
    }
 catch (    Exception e) {
      throw new InternalErrorException(errorMsg + "String_Node_Str" + e.getMessage());
    }
  }
  event=new EventVO();
  event.setAccountId(volume.getAccountId());
  event.setUserId(1L);
  event.setType(EventTypes.EVENT_VOLUME_ATTACH);
  event.setState(EventState.Completed);
  event.setStartId(startEventId);
  if (!sendCommand || (answer != null && answer.getResult())) {
    if (sendCommand) {
      _volsDao.attachVolume(volume.getId(),vmId,answer.getDeviceId());
    }
 else {
      _volsDao.attachVolume(volume.getId(),vmId,deviceId);
    }
    if (!vm.getName().equals(vm.getDisplayName()))     event.setDescription("String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName()+ "String_Node_Str"+ vm.getDisplayName()+ "String_Node_Str");
 else     event.setDescription("String_Node_Str" + volume.getName() + "String_Node_Str"+ vm.getName());
    event.setLevel(EventVO.LEVEL_INFO);
    _eventDao.persist(event);
  }
 else {
    if (answer != null) {
      String details=answer.getDetails();
      if (details != null && !details.isEmpty())       errorMsg+="String_Node_Str" + details;
    }
    throw new InternalErrorException(errorMsg);
  }
}