@Override
 public boolean configure(Map<String, Object> params) {
   lifeCycle = ComponentContext.inject(SimulatorImageStoreLifeCycleImpl.class);
   driver = ComponentContext.inject(SimulatorImageStoreDriverImpl.class);
   storeMgr.registerDriver(this.getName(), driver);
   return true;
 }
  @Before
  public void testSetUp() {
    ComponentContext.initComponentsLifeCycle();

    PlannerHostReservationVO reservationVO =
        new PlannerHostReservationVO(200L, 1L, 2L, 3L, PlannerResourceUsage.Shared);
    Mockito.when(_plannerHostReserveDao.persist(Matchers.any(PlannerHostReservationVO.class)))
        .thenReturn(reservationVO);
    Mockito.when(_plannerHostReserveDao.findById(Matchers.anyLong())).thenReturn(reservationVO);
    Mockito.when(_affinityGroupVMMapDao.countAffinityGroupsForVm(Matchers.anyLong()))
        .thenReturn(0L);

    VMInstanceVO vm = new VMInstanceVO();
    Mockito.when(vmProfile.getVirtualMachine()).thenReturn(vm);

    Mockito.when(_dcDao.findById(Matchers.anyLong())).thenReturn(dc);
    Mockito.when(dc.getId()).thenReturn(dataCenterId);

    ClusterVO clusterVO = new ClusterVO();
    clusterVO.setHypervisorType(HypervisorType.XenServer.toString());
    Mockito.when(_clusterDao.findById(Matchers.anyLong())).thenReturn(clusterVO);

    Mockito.when(_planner.getName()).thenReturn("FirstFitPlanner");
    List<DeploymentPlanner> planners = new ArrayList<DeploymentPlanner>();
    planners.add(_planner);
    _dpm.setPlanners(planners);
  }
Example #3
0
  private static void publishOnMessageBus(
      String eventCategory, String eventType, String details, Event.State state) {

    if (state != com.cloud.event.Event.State.Completed) {
      return;
    }

    try {
      _messageBus = ComponentContext.getComponent(MessageBusBase.class);
    } catch (NoSuchBeanDefinitionException nbe) {
      return; // no provider is configured to provide events bus, so just return
    }

    org.apache.cloudstack.framework.events.Event event =
        new org.apache.cloudstack.framework.events.Event(
            ManagementService.Name,
            eventCategory,
            eventType,
            EventTypes.getEntityForEvent(eventType),
            null);

    Map<String, String> eventDescription = new HashMap<String, String>();
    eventDescription.put("event", eventType);
    eventDescription.put("status", state.toString());
    eventDescription.put("details", details);
    event.setDescription(eventDescription);
    try {
      _messageBus.publish(EventTypes.getEntityForEvent(eventType), eventType, null, event);
    } catch (Exception e) {
      s_logger.warn("Failed to publish action event on the the event bus.");
    }
  }
  @Override
  public boolean configure(Map<String, Object> params) {

    lifecycle = ComponentContext.inject(ElastistorPrimaryDataStoreLifeCycle.class);
    driver = ComponentContext.inject(ElastistorPrimaryDataStoreDriver.class);
    listener = ComponentContext.inject(ElastistorHostListener.class);

    ElastistorUtil.setElastistorAccountId(esaccountid);
    ElastistorUtil.setElastistorApiKey(esapikey);
    ElastistorUtil.setElastistorManagementIp(esmanagementip);
    ElastistorUtil.setElastistorPoolId(espoolid);
    ElastistorUtil.setElastistorGateway(esdefaultgateway);
    ElastistorUtil.setElastistorInterface(estntinterface);
    ElastistorUtil.setElastistorSubnet(essubnet);

    return true;
  }
 public void sendCommandAsync(
     HypervisorHostEndPoint host,
     final Command command,
     final AsyncCompletionCallback<Answer> callback) {
   // new MockRpcCallBack(host.getHostId(), command, callback);
   MockRpcCallBack run = ComponentContext.inject(MockRpcCallBack.class);
   run.setCallback(callback);
   run.setCmd(command);
   run.setHostId(host.getId());
   executor.schedule(run, 10, TimeUnit.SECONDS);
 }
  @Override
  public boolean configure(String name, Map<String, Object> params) {
    final Map<String, String> configs = _configDao.getConfiguration("management-server", params);
    _proxy = configs.get(Config.SecStorageProxy.key());

    String cert = configs.get("secstorage.ssl.cert.domain");
    if (!"realhostip.com".equalsIgnoreCase(cert)) {
      s_logger.warn(
          "Only realhostip.com ssl cert is supported, ignoring self-signed and other certs");
    }

    _copyAuthPasswd = configs.get("secstorage.copy.password");

    DownloadListener dl = new DownloadListener(this);
    ComponentContext.inject(dl);
    _agentMgr.registerForHostEvents(dl, true, false, false);

    return true;
  }
  @Before
  public void setUp() {
    ComponentContext.initComponentsLifeCycle();

    acct.setType(Account.ACCOUNT_TYPE_NORMAL);
    acct.setAccountName("user1");
    acct.setDomainId(domainId);
    acct.setId(accountId);

    UserVO user =
        new UserVO(
            1,
            "testuser",
            "password",
            "firstname",
            "lastName",
            "email",
            "timezone",
            UUID.randomUUID().toString());

    CallContext.register(user, acct);
  }
  @Override
  public String reserveVirtualMachine(
      VMEntityVO vmEntityVO, String plannerToUse, DeploymentPlan planToDeploy, ExcludeList exclude)
      throws InsufficientCapacityException, ResourceUnavailableException {

    // call planner and get the deployDestination.
    // load vm instance and offerings and call virtualMachineManagerImpl
    // FIXME: profile should work on VirtualMachineEntity
    VMInstanceVO vm = _vmDao.findByUuid(vmEntityVO.getUuid());
    VirtualMachineProfileImpl<VMInstanceVO> vmProfile =
        new VirtualMachineProfileImpl<VMInstanceVO>(vm);
    DataCenterDeployment plan =
        new DataCenterDeployment(
            vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null);
    if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
      plan =
          new DataCenterDeployment(
              planToDeploy.getDataCenterId(),
              planToDeploy.getPodId(),
              planToDeploy.getClusterId(),
              planToDeploy.getHostId(),
              planToDeploy.getPoolId(),
              planToDeploy.getPhysicalNetworkId());
    }

    List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
    if (!vols.isEmpty()) {
      VolumeVO vol = vols.get(0);
      StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId());
      if (!pool.isInMaintenance()) {
        long rootVolDcId = pool.getDataCenterId();
        Long rootVolPodId = pool.getPodId();
        Long rootVolClusterId = pool.getClusterId();
        if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
          Long clusterIdSpecified = planToDeploy.getClusterId();
          if (clusterIdSpecified != null && rootVolClusterId != null) {
            if (rootVolClusterId.longValue() != clusterIdSpecified.longValue()) {
              // cannot satisfy the plan passed in to the
              // planner
              throw new ResourceUnavailableException(
                  "Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for "
                      + vm,
                  Cluster.class,
                  clusterIdSpecified);
            }
          }
          plan =
              new DataCenterDeployment(
                  planToDeploy.getDataCenterId(),
                  planToDeploy.getPodId(),
                  planToDeploy.getClusterId(),
                  planToDeploy.getHostId(),
                  vol.getPoolId(),
                  null,
                  null);
        } else {
          plan =
              new DataCenterDeployment(
                  rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null, null);
        }
      }
    }

    DeploymentPlanner planner = ComponentContext.getComponent(plannerToUse);
    DeployDestination dest = null;

    if (planner.canHandle(vmProfile, plan, exclude)) {
      dest = planner.plan(vmProfile, plan, exclude);
    }

    if (dest != null) {
      // save destination with VMEntityVO
      VMReservationVO vmReservation =
          new VMReservationVO(
              vm.getId(),
              dest.getDataCenter().getId(),
              dest.getPod().getId(),
              dest.getCluster().getId(),
              dest.getHost().getId());
      Map<Long, Long> volumeReservationMap = new HashMap<Long, Long>();
      for (Volume vo : dest.getStorageForDisks().keySet()) {
        volumeReservationMap.put(vo.getId(), dest.getStorageForDisks().get(vo).getId());
      }
      vmReservation.setVolumeReservation(volumeReservationMap);

      vmEntityVO.setVmReservation(vmReservation);
      _vmEntityDao.persist(vmEntityVO);

      return vmReservation.getUuid();
    } else {
      throw new InsufficientServerCapacityException(
          "Unable to create a deployment for " + vmProfile,
          DataCenter.class,
          plan.getDataCenterId());
    }
  }
Example #9
0
  @Override
  @SuppressWarnings("rawtypes")
  public String handleRequest(Map params, String responseType, StringBuffer auditTrailSb)
      throws ServerApiException {
    String response = null;
    String[] command = null;

    try {
      command = (String[]) params.get("command");
      if (command == null) {
        s_logger.error("invalid request, no command sent");
        if (s_logger.isTraceEnabled()) {
          s_logger.trace("dumping request parameters");
          for (Object key : params.keySet()) {
            String keyStr = (String) key;
            String[] value = (String[]) params.get(key);
            s_logger.trace(
                "   key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
          }
        }
        throw new ServerApiException(
            ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
      } else {
        Map<String, String> paramMap = new HashMap<String, String>();
        Set keys = params.keySet();
        Iterator keysIter = keys.iterator();
        while (keysIter.hasNext()) {
          String key = (String) keysIter.next();
          if ("command".equalsIgnoreCase(key)) {
            continue;
          }
          String[] value = (String[]) params.get(key);
          // fail if parameter value contains ASCII control (non-printable) characters
          if (value[0] != null) {
            Pattern pattern = Pattern.compile(controlCharacters);
            Matcher matcher = pattern.matcher(value[0]);
            if (matcher.find()) {
              throw new ServerApiException(
                  ApiErrorCode.PARAM_ERROR,
                  "Received value "
                      + value[0]
                      + " for parameter "
                      + key
                      + " is invalid, contains illegal ASCII non-printable characters");
            }
          }
          paramMap.put(key, value[0]);
        }

        Class<?> cmdClass = getCmdClass(command[0]);
        if (cmdClass != null) {
          BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
          cmdObj = ComponentContext.inject(cmdObj);
          cmdObj.configure();
          cmdObj.setFullUrlParams(paramMap);
          cmdObj.setResponseType(responseType);
          cmdObj.setHttpMethod(paramMap.get("httpmethod").toString());

          // This is where the command is either serialized, or directly dispatched
          response = queueCommand(cmdObj, paramMap);
          buildAuditTrail(auditTrailSb, command[0], response);
        } else {
          if (!command[0].equalsIgnoreCase("login") && !command[0].equalsIgnoreCase("logout")) {
            String errorString =
                "Unknown API command: " + ((command == null) ? "null" : command[0]);
            s_logger.warn(errorString);
            auditTrailSb.append(" " + errorString);
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
          }
        }
      }
    } catch (InvalidParameterValueException ex) {
      s_logger.info(ex.getMessage());
      throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (IllegalArgumentException ex) {
      s_logger.info(ex.getMessage());
      throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (PermissionDeniedException ex) {
      ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
      if (idList != null) {
        StringBuffer buf = new StringBuffer();
        for (ExceptionProxyObject obj : idList) {
          buf.append(obj.getDescription());
          buf.append(":");
          buf.append(obj.getUuid());
          buf.append(" ");
        }
        s_logger.info(
            "PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
      } else {
        s_logger.info("PermissionDenied: " + ex.getMessage());
      }
      throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
    } catch (AccountLimitException ex) {
      s_logger.info(ex.getMessage());
      throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
    } catch (InsufficientCapacityException ex) {
      s_logger.info(ex.getMessage());
      String errorMsg = ex.getMessage();
      if (CallContext.current().getCallingAccount().getType() != Account.ACCOUNT_TYPE_ADMIN) {
        // hide internal details to non-admin user for security reason
        errorMsg = BaseCmd.USER_ERROR_MESSAGE;
      }
      throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
    } catch (ResourceAllocationException ex) {
      s_logger.info(ex.getMessage());
      throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
    } catch (ResourceUnavailableException ex) {
      s_logger.info(ex.getMessage());
      String errorMsg = ex.getMessage();
      if (CallContext.current().getCallingAccount().getType() != Account.ACCOUNT_TYPE_ADMIN) {
        // hide internal details to non-admin user for security reason
        errorMsg = BaseCmd.USER_ERROR_MESSAGE;
      }
      throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
    } catch (ServerApiException ex) {
      s_logger.info(ex.getDescription());
      throw ex;
    } catch (Exception ex) {
      s_logger.error(
          "unhandled exception executing api command: " + ((command == null) ? "null" : command[0]),
          ex);
      String errorMsg = ex.getMessage();
      if (CallContext.current().getCallingAccount().getType() != Account.ACCOUNT_TYPE_ADMIN) {
        // hide internal details to non-admin user for security reason
        errorMsg = BaseCmd.USER_ERROR_MESSAGE;
      }
      throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
    }

    return response;
  }
 @Before
 public void setup() throws Exception {
   ComponentContext.initComponentsLifeCycle();
 }
  @Override
  public void downloadVolumeToStorage(
      DataObject volume, AsyncCompletionCallback<DownloadAnswer> callback) {
    boolean downloadJobExists = false;
    VolumeDataStoreVO volumeHost = null;
    DataStore store = volume.getDataStore();
    VolumeInfo volInfo = (VolumeInfo) volume;
    RegisterVolumePayload payload = (RegisterVolumePayload) volInfo.getpayload();
    String url = payload.getUrl();
    String checkSum = payload.getChecksum();
    ImageFormat format = ImageFormat.valueOf(payload.getFormat());

    volumeHost = _volumeStoreDao.findByStoreVolume(store.getId(), volume.getId());
    if (volumeHost == null) {
      volumeHost =
          new VolumeDataStoreVO(
              store.getId(),
              volume.getId(),
              new Date(),
              0,
              Status.NOT_DOWNLOADED,
              null,
              null,
              "jobid0000",
              null,
              url,
              checkSum);
      _volumeStoreDao.persist(volumeHost);
    } else if ((volumeHost.getJobId() != null) && (volumeHost.getJobId().length() > 2)) {
      downloadJobExists = true;
    }

    Long maxVolumeSizeInBytes = getMaxVolumeSizeInBytes();
    if (volumeHost != null) {
      start();
      Volume vol = _volumeDao.findById(volume.getId());
      DownloadCommand dcmd =
          new DownloadCommand(
              (VolumeObjectTO) (volume.getTO()), maxVolumeSizeInBytes, checkSum, url, format);
      dcmd.setProxy(getHttpProxy());
      if (downloadJobExists) {
        dcmd = new DownloadProgressCommand(dcmd, volumeHost.getJobId(), RequestType.GET_OR_RESTART);
        dcmd.setResourceType(ResourceType.VOLUME);
      }

      EndPoint ep = _epSelector.select(volume);
      if (ep == null) {
        s_logger.warn("There is no secondary storage VM for image store " + store.getName());
        return;
      }
      DownloadListener dl = new DownloadListener(ep, store, volume, _timer, this, dcmd, callback);
      ComponentContext.inject(dl); // auto-wired those injected fields in DownloadListener

      if (downloadJobExists) {
        dl.setCurrState(volumeHost.getDownloadState());
      }

      try {
        ep.sendMessageAsync(dcmd, new UploadListener.Callback(ep.getId(), dl));
      } catch (Exception e) {
        s_logger.warn(
            "Unable to start /resume download of volume "
                + volume.getId()
                + " to "
                + store.getName(),
            e);
        dl.setDisconnected();
        dl.scheduleStatusCheck(RequestType.GET_OR_RESTART);
      }
    }
  }
  private void initiateTemplateDownload(
      DataObject template, AsyncCompletionCallback<DownloadAnswer> callback) {
    boolean downloadJobExists = false;
    TemplateDataStoreVO vmTemplateStore = null;
    DataStore store = template.getDataStore();

    vmTemplateStore = _vmTemplateStoreDao.findByStoreTemplate(store.getId(), template.getId());
    if (vmTemplateStore == null) {
      vmTemplateStore =
          new TemplateDataStoreVO(
              store.getId(),
              template.getId(),
              new Date(),
              0,
              Status.NOT_DOWNLOADED,
              null,
              null,
              "jobid0000",
              null,
              template.getUri());
      vmTemplateStore.setDataStoreRole(store.getRole());
      vmTemplateStore = _vmTemplateStoreDao.persist(vmTemplateStore);
    } else if ((vmTemplateStore.getJobId() != null) && (vmTemplateStore.getJobId().length() > 2)) {
      downloadJobExists = true;
    }

    Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes();
    if (vmTemplateStore != null) {
      start();
      VirtualMachineTemplate tmpl = _templateDao.findById(template.getId());
      DownloadCommand dcmd =
          new DownloadCommand((TemplateObjectTO) (template.getTO()), maxTemplateSizeInBytes);
      dcmd.setProxy(getHttpProxy());
      if (downloadJobExists) {
        dcmd =
            new DownloadProgressCommand(
                dcmd, vmTemplateStore.getJobId(), RequestType.GET_OR_RESTART);
      }
      if (vmTemplateStore.isCopy()) {
        dcmd.setCreds(TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd);
      }
      EndPoint ep = _epSelector.select(template);
      if (ep == null) {
        String errMsg =
            "There is no secondary storage VM for downloading template to image store "
                + store.getName();
        s_logger.warn(errMsg);
        throw new CloudRuntimeException(errMsg);
      }
      DownloadListener dl = new DownloadListener(ep, store, template, _timer, this, dcmd, callback);
      ComponentContext.inject(dl); // initialize those auto-wired field in download listener.
      if (downloadJobExists) {
        // due to handling existing download job issues, we still keep
        // downloadState in template_store_ref to avoid big change in
        // DownloadListener to use
        // new ObjectInDataStore.State transition. TODO: fix this later
        // to be able to remove downloadState from template_store_ref.
        s_logger.info("found existing download job");
        dl.setCurrState(vmTemplateStore.getDownloadState());
      }

      try {
        ep.sendMessageAsync(dcmd, new UploadListener.Callback(ep.getId(), dl));
      } catch (Exception e) {
        s_logger.warn(
            "Unable to start /resume download of template "
                + template.getId()
                + " to "
                + store.getName(),
            e);
        dl.setDisconnected();
        dl.scheduleStatusCheck(RequestType.GET_OR_RESTART);
      }
    }
  }
Example #13
0
  @Test(priority = -1)
  public void setUp() {
    ComponentContext.initComponentsLifeCycle();

    host = hostDao.findByGuid(this.getHostGuid());
    if (host != null) {
      dcId = host.getDataCenterId();
      clusterId = host.getClusterId();
      podId = host.getPodId();
      return;
    }
    // create data center
    DataCenterVO dc =
        new DataCenterVO(
            UUID.randomUUID().toString(),
            "test",
            "8.8.8.8",
            null,
            "10.0.0.1",
            null,
            "10.0.0.1/24",
            null,
            null,
            NetworkType.Basic,
            null,
            null,
            true,
            true,
            null,
            null);
    dc = dcDao.persist(dc);
    dcId = dc.getId();
    // create pod

    HostPodVO pod =
        new HostPodVO(
            UUID.randomUUID().toString(),
            dc.getId(),
            this.getHostGateway(),
            this.getHostCidr(),
            8,
            "test");
    pod = podDao.persist(pod);
    podId = pod.getId();
    // create xen cluster
    ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster");
    cluster.setHypervisorType(HypervisorType.XenServer.toString());
    cluster.setClusterType(ClusterType.CloudManaged);
    cluster.setManagedState(ManagedState.Managed);
    cluster = clusterDao.persist(cluster);
    clusterId = cluster.getId();
    // create xen host

    host = new HostVO(this.getHostGuid());
    host.setName("devcloud xen host");
    host.setType(Host.Type.Routing);
    host.setPrivateIpAddress(this.getHostIp());
    host.setDataCenterId(dc.getId());
    host.setVersion("6.0.1");
    host.setAvailable(true);
    host.setSetup(true);
    host.setPodId(podId);
    host.setLastPinged(0);
    host.setResourceState(ResourceState.Enabled);
    host.setHypervisorType(HypervisorType.XenServer);
    host.setClusterId(cluster.getId());

    host = hostDao.persist(host);

    imageStore = new ImageStoreVO();
    imageStore.setName("test");
    imageStore.setDataCenterId(dcId);
    imageStore.setProviderName("CloudStack ImageStore Provider");
    imageStore.setRole(DataStoreRole.Image);
    imageStore.setUrl(this.getSecondaryStorage());
    imageStore.setUuid(UUID.randomUUID().toString());
    imageStore = imageStoreDao.persist(imageStore);
  }
  @Test(priority = -1)
  public void setUp() {
    ComponentContext.initComponentsLifeCycle();

    host = hostDao.findByGuid(this.getHostGuid());
    if (host != null) {
      dcId = host.getDataCenterId();
      clusterId = host.getClusterId();
      podId = host.getPodId();
      imageStore = this.imageStoreDao.findByName(imageStoreName);
    } else {
      // create data center
      DataCenterVO dc =
          new DataCenterVO(
              UUID.randomUUID().toString(),
              "test",
              "8.8.8.8",
              null,
              "10.0.0.1",
              null,
              "10.0.0.1/24",
              null,
              null,
              NetworkType.Basic,
              null,
              null,
              true,
              true,
              null,
              null);
      dc = dcDao.persist(dc);
      dcId = dc.getId();
      // create pod

      HostPodVO pod =
          new HostPodVO(
              UUID.randomUUID().toString(),
              dc.getId(),
              this.getHostGateway(),
              this.getHostCidr(),
              8,
              "test");
      pod = podDao.persist(pod);
      podId = pod.getId();
      // create xen cluster
      ClusterVO cluster = new ClusterVO(dc.getId(), pod.getId(), "devcloud cluster");
      cluster.setHypervisorType(HypervisorType.VMware.toString());
      cluster.setClusterType(ClusterType.ExternalManaged);
      cluster.setManagedState(ManagedState.Managed);
      cluster = clusterDao.persist(cluster);
      clusterId = cluster.getId();

      // setup vcenter
      ClusterDetailsVO clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "url", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "username", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      clusterDetailVO = new ClusterDetailsVO(cluster.getId(), "password", null);
      this.clusterDetailsDao.persist(clusterDetailVO);
      // create xen host

      host = new HostVO(this.getHostGuid());
      host.setName("devcloud vmware host");
      host.setType(Host.Type.Routing);
      host.setPrivateIpAddress(this.getHostIp());
      host.setDataCenterId(dc.getId());
      host.setVersion("6.0.1");
      host.setAvailable(true);
      host.setSetup(true);
      host.setPodId(podId);
      host.setLastPinged(0);
      host.setResourceState(ResourceState.Enabled);
      host.setHypervisorType(HypervisorType.VMware);
      host.setClusterId(cluster.getId());

      host = hostDao.persist(host);

      imageStore = new ImageStoreVO();
      imageStore.setName(imageStoreName);
      imageStore.setDataCenterId(dcId);
      imageStore.setProviderName("CloudStack ImageStore Provider");
      imageStore.setRole(DataStoreRole.Image);
      imageStore.setUrl(this.getSecondaryStorage());
      imageStore.setUuid(UUID.randomUUID().toString());
      imageStore.setProtocol("nfs");
      imageStore = imageStoreDao.persist(imageStore);
    }

    image = new VMTemplateVO();
    image.setTemplateType(TemplateType.USER);
    image.setUrl(this.getTemplateUrl());
    image.setUniqueName(UUID.randomUUID().toString());
    image.setName(UUID.randomUUID().toString());
    image.setPublicTemplate(true);
    image.setFeatured(true);
    image.setRequiresHvm(true);
    image.setBits(64);
    image.setFormat(Storage.ImageFormat.VHD);
    image.setEnablePassword(true);
    image.setEnableSshKey(true);
    image.setGuestOSId(1);
    image.setBootable(true);
    image.setPrepopulate(true);
    image.setCrossZones(true);
    image.setExtractable(true);

    image = imageDataDao.persist(image);

    /*
     * TemplateDataStoreVO templateStore = new TemplateDataStoreVO();
     *
     * templateStore.setDataStoreId(imageStore.getId());
     * templateStore.setDownloadPercent(100);
     * templateStore.setDownloadState(Status.DOWNLOADED);
     * templateStore.setDownloadUrl(imageStore.getUrl());
     * templateStore.setInstallPath(this.getImageInstallPath());
     * templateStore.setTemplateId(image.getId());
     * templateStoreDao.persist(templateStore);
     */

    DataStore store = this.dataStoreMgr.getDataStore(imageStore.getId(), DataStoreRole.Image);
    TemplateInfo template = templateFactory.getTemplate(image.getId(), DataStoreRole.Image);
    DataObject templateOnStore = store.create(template);
    TemplateObjectTO to = new TemplateObjectTO();
    to.setPath(this.getImageInstallPath());
    CopyCmdAnswer answer = new CopyCmdAnswer(to);
    templateOnStore.processEvent(Event.CreateOnlyRequested);
    templateOnStore.processEvent(Event.OperationSuccessed, answer);
  }