protected HashMap<String, Object> buildConfigParams(HostVO host) {
    HashMap<String, Object> params = new HashMap<String, Object>(host.getDetails().size() + 5);
    params.putAll(host.getDetails());

    params.put("guid", host.getGuid());
    params.put("zone", Long.toString(host.getDataCenterId()));
    if (host.getPodId() != null) {
      params.put("pod", Long.toString(host.getPodId()));
    }
    if (host.getClusterId() != null) {
      params.put("cluster", Long.toString(host.getClusterId()));
      String guid = null;
      ClusterVO cluster = _clusterDao.findById(host.getClusterId());
      if (cluster.getGuid() == null) {
        guid = host.getDetail("pool");
      } else {
        guid = cluster.getGuid();
      }
      if (guid != null && !guid.isEmpty()) {
        params.put("pool", guid);
      }
    }

    params.put("ipaddress", host.getPrivateIpAddress());
    params.put("secondary.storage.vm", "false");
    params.put(
        "max.template.iso.size", _configDao.getValue(Config.MaxTemplateAndIsoSize.toString()));
    params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
    return params;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    _configDao = locator.getDao(ConfigurationDao.class);
    _setupAgentPath = Script.findScript(getPatchPath(), "setup_agent.sh");
    _kvmPrivateNic = _configDao.getValue(Config.KvmPrivateNetwork.key());
    if (_kvmPrivateNic == null) {
      _kvmPrivateNic = "cloudbr0";
    }

    _kvmPublicNic = _configDao.getValue(Config.KvmPublicNetwork.key());
    if (_kvmPublicNic == null) {
      _kvmPublicNic = _kvmPrivateNic;
    }

    _kvmGuestNic = _configDao.getValue(Config.KvmGuestNetwork.key());
    if (_kvmGuestNic == null) {
      _kvmGuestNic = _kvmPrivateNic;
    }

    if (_setupAgentPath == null) {
      throw new ConfigurationException("Can't find setup_agent.sh");
    }
    _hostIp = _configDao.getValue("host");
    if (_hostIp == null) {
      throw new ConfigurationException("Can't get host IP");
    }
    _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    ConfigurationDao dao = ComponentLocator.getCurrentLocator().getDao(ConfigurationDao.class);
    _params = dao.getConfiguration(params);
    _name = name;

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    Map<String, String> configs = _configDao.getConfiguration(params);

    _userLimit = NumbersUtil.parseInt(configs.get(Config.RemoteAccessVpnUserLimit.key()), 8);

    _clientIpRange = configs.get(Config.RemoteAccessVpnClientIpRange.key());

    _pskLength = NumbersUtil.parseInt(configs.get(Config.RemoteAccessVpnPskLength.key()), 24);

    validateRemoteAccessVpnConfiguration();

    VpnSearch = _remoteAccessVpnDao.createSearchBuilder();
    VpnSearch.and("accountId", VpnSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
    SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
    domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
    VpnSearch.join(
        "domainSearch",
        domainSearch,
        VpnSearch.entity().getDomainId(),
        domainSearch.entity().getId(),
        JoinBuilder.JoinType.INNER);
    VpnSearch.done();

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {

    Map<String, String> configs = _configDao.getConfiguration("Network", params);
    _numWorkerThreads =
        NumbersUtil.parseInt(
            configs.get(Config.SecurityGroupWorkerThreads.key()), WORKER_THREAD_COUNT);
    _timeBetweenCleanups =
        NumbersUtil.parseInt(
            configs.get(Config.SecurityGroupWorkCleanupInterval.key()), TIME_BETWEEN_CLEANUPS);
    _globalWorkLockTimeout =
        NumbersUtil.parseInt(configs.get(Config.SecurityGroupWorkGlobalLockTimeout.key()), 300);
    /* register state listener, no matter security group is enabled or not */
    VirtualMachine.State.getStateMachine().registerListener(this);

    _answerListener = new SecurityGroupListener(this, _agentMgr, _workDao);
    _agentMgr.registerForHostEvents(_answerListener, true, true, true);

    _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId();

    s_logger.info(
        "SecurityGroupManager: num worker threads="
            + _numWorkerThreads
            + ", time between cleanups="
            + _timeBetweenCleanups
            + " global lock timeout="
            + _globalWorkLockTimeout);
    createThreadPools();

    return true;
  }
 protected Long getMaxTemplateSizeInBytes() {
   try {
     return Long.parseLong(configDao.getValue("max.template.iso.size")) * 1024L * 1024L * 1024L;
   } catch (NumberFormatException e) {
     return null;
   }
 }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {

    if (s_logger.isInfoEnabled()) {
      s_logger.info("Start configuring AgentBasedConsoleProxyManager");
    }

    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      throw new ConfigurationException("Unable to get the configuration dao.");
    }

    Map<String, String> configs = configDao.getConfiguration("management-server", params);
    String value = configs.get("consoleproxy.url.port");
    if (value != null) {
      _consoleProxyUrlPort =
          NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_URL_PORT);
    }

    value = configs.get("consoleproxy.port");
    if (value != null) {
      _consoleProxyPort = NumbersUtil.parseInt(value, ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT);
    }

    value = configs.get("consoleproxy.sslEnabled");
    if (value != null && value.equalsIgnoreCase("true")) {
      _sslEnabled = true;
    }

    _instance = configs.get("instance.name");

    _consoleProxyUrlDomain = configs.get("consoleproxy.url.domain");

    _listener = new ConsoleProxyListener(this);
    _agentMgr.registerForHostEvents(_listener, true, true, false);

    _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);

    if (s_logger.isInfoEnabled()) {
      s_logger.info(
          "AgentBasedConsoleProxyManager has been configured. SSL enabled: " + _sslEnabled);
    }
    return true;
  }
  @Override
  public boolean generateVMSetupCommand(Long ssAHostId) {
    HostVO ssAHost = _hostDao.findById(ssAHostId);
    if (ssAHost.getType() != Host.Type.SecondaryStorageVM) {
      return false;
    }
    SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findByInstanceName(ssAHost.getName());
    if (secStorageVm == null) {
      s_logger.warn("secondary storage VM " + ssAHost.getName() + " doesn't exist");
      return false;
    }

    SecStorageVMSetupCommand setupCmd = new SecStorageVMSetupCommand();
    if (_allowedInternalSites != null) {
      List<String> allowedCidrs = new ArrayList<String>();
      String[] cidrs = _allowedInternalSites.split(",");
      for (String cidr : cidrs) {
        if (NetUtils.isValidCIDR(cidr) || NetUtils.isValidIp(cidr)) {
          allowedCidrs.add(cidr);
        }
      }
      List<? extends Nic> nics =
          _networkMgr.getNicsForTraffic(secStorageVm.getId(), TrafficType.Management);
      Nic privateNic = nics.get(0);
      String privateCidr =
          NetUtils.ipAndNetMaskToCidr(privateNic.getIp4Address(), privateNic.getNetmask());
      String publicCidr =
          NetUtils.ipAndNetMaskToCidr(
              secStorageVm.getPublicIpAddress(), secStorageVm.getPublicNetmask());
      if (NetUtils.isNetworkAWithinNetworkB(privateCidr, publicCidr)
          || NetUtils.isNetworkAWithinNetworkB(publicCidr, privateCidr)) {
        s_logger.info(
            "private and public interface overlaps, add a default route through private interface. privateCidr: "
                + privateCidr
                + ", publicCidr: "
                + publicCidr);
        allowedCidrs.add(NetUtils.ALL_CIDRS);
      }
      setupCmd.setAllowedInternalSites(allowedCidrs.toArray(new String[allowedCidrs.size()]));
    }
    String copyPasswd = _configDao.getValue("secstorage.copy.password");
    setupCmd.setCopyPassword(copyPasswd);
    setupCmd.setCopyUserName(TemplateConstants.DEFAULT_HTTP_AUTH_USER);
    Answer answer = _agentMgr.easySend(ssAHostId, setupCmd);
    if (answer != null && answer.getResult()) {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully programmed http auth into " + secStorageVm.getHostName());
      }
      return true;
    } else {
      if (s_logger.isDebugEnabled()) {
        s_logger.debug(
            "failed to program http auth into secondary storage vm : "
                + secStorageVm.getHostName());
      }
      return false;
    }
  }
  public void init() {
    BaseCmd.setComponents(new ApiResponseHelper());
    BaseListCmd.configure();

    _systemAccount = _accountMgr.getSystemAccount();
    _systemUser = _accountMgr.getSystemUser();
    _dispatcher = ApiDispatcher.getInstance();

    Integer apiPort = null; // api port, null by default
    ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria();
    sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port");
    List<ConfigurationVO> values = configDao.search(sc, null);
    if ((values != null) && (values.size() > 0)) {
      ConfigurationVO apiPortConfig = values.get(0);
      if (apiPortConfig.getValue() != null) {
        apiPort = Integer.parseInt(apiPortConfig.getValue());
      }
    }

    Set<Class<?>> cmdClasses =
        ReflectUtil.getClassesWithAnnotation(
            APICommand.class, new String[] {"org.apache.cloudstack.api", "com.cloud.api"});

    for (Class<?> cmdClass : cmdClasses) {
      String apiName = cmdClass.getAnnotation(APICommand.class).name();
      if (_apiNameCmdClassMap.containsKey(apiName)) {
        s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName);
        continue;
      }
      _apiNameCmdClassMap.put(apiName, cmdClass);
    }

    encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key()));
    String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key());
    if (jsonType != null) {
      jsonContentType = jsonType;
    }

    if (apiPort != null) {
      ListenerThread listenerThread = new ListenerThread(this, apiPort);
      listenerThread.start();
    }
  }
 private Long getMaxVolumeSizeInBytes() {
   try {
     return Long.parseLong(_configDao.getValue("storage.max.volume.upload.size"))
         * 1024L
         * 1024L
         * 1024L;
   } catch (NumberFormatException e) {
     return null;
   }
 }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _vmCapacityReleaseInterval =
        NumbersUtil.parseInt(_configDao.getValue(Config.CapacitySkipcountingHours.key()), 3600);
    _storageOverProvisioningFactor =
        NumbersUtil.parseFloat(
            _configDao.getValue(Config.StorageOverprovisioningFactor.key()), 1.0f);

    _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("HostCapacity-Checker"));
    VirtualMachine.State.getStateMachine().registerListener(this);
    _agentManager.registerForHostEvents(
        new StorageCapacityListener(_capacityDao, _storageOverProvisioningFactor),
        true,
        false,
        false);
    _agentManager.registerForHostEvents(
        new ComputeCapacityListener(_capacityDao, this), true, false, false);

    return true;
  }
  private void createApplyLoadBalancingRulesCommands(
      List<LoadBalancingRule> rules, DomainRouterVO elbVm, Commands cmds, long guestNetworkId) {

    LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
    int i = 0;
    for (LoadBalancingRule rule : rules) {
      boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke));
      String protocol = rule.getProtocol();
      String algorithm = rule.getAlgorithm();

      String elbIp = _networkModel.getIp(rule.getSourceIpAddressId()).getAddress().addr();
      int srcPort = rule.getSourcePortStart();
      String uuid = rule.getUuid();
      List<LbDestination> destinations = rule.getDestinations();
      LoadBalancerTO lb =
          new LoadBalancerTO(
              uuid, elbIp, srcPort, protocol, algorithm, revoked, false, false, destinations);
      lbs[i++] = lb;
    }

    LoadBalancerConfigCommand cmd =
        new LoadBalancerConfigCommand(
            lbs,
            elbVm.getPublicIpAddress(),
            _nicDao.getIpAddress(guestNetworkId, elbVm.getId()),
            elbVm.getPrivateIpAddress(),
            null,
            null);
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, elbVm.getPrivateIpAddress());
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, elbVm.getInstanceName());
    // FIXME: why are we setting attributes directly? Ick!! There should be accessors and
    // the constructor should set defaults.
    cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
    cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
    cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key());
    cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key());

    cmds.addCommand(cmd);
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _name = name;
    _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));

    if (_isEnabled) {
      _executorPool = Executors.newScheduledThreadPool(10, new NamedThreadFactory("OVS"));
      _cleanupExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("OVS-Cleanup"));
      _listener = new OvsTunnelListener(_tunnelDao, _hostDao);
      _agentMgr.registerForHostEvents(_listener, true, true, true);
    }

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    super.configure(name, params);

    ComponentLocator locator = ComponentLocator.getCurrentLocator();

    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    Map<String, String> dbParams = configDao.getConfiguration(params);

    _cidr = dbParams.get(Config.ControlCidr);
    if (_cidr == null) {
      _cidr = "169.254.0.0/16";
    }

    _gateway = dbParams.get(Config.ControlGateway);
    if (_gateway == null) {
      _gateway = NetUtils.getLinkLocalGateway();
    }

    s_logger.info("Control network setup: cidr=" + _cidr + "; gateway = " + _gateway);

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    AllocatedIpSearch = _ipAddressDao.createSearchBuilder();
    AllocatedIpSearch.and("allocated", AllocatedIpSearch.entity().getAllocatedTime(), Op.NNULL);
    AllocatedIpSearch.and("dc", AllocatedIpSearch.entity().getDataCenterId(), Op.EQ);
    SearchBuilder<NetworkVO> networkJoin = _networksDao.createSearchBuilder();
    networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ);
    AllocatedIpSearch.join(
        "network",
        networkJoin,
        AllocatedIpSearch.entity().getSourceNetworkId(),
        networkJoin.entity().getId(),
        JoinBuilder.JoinType.INNER);
    AllocatedIpSearch.done();

    _networkStatsInterval =
        NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400);
    _TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key());
    _TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key());
    _agentMgr.registerForHostEvents(
        new DirectNetworkStatsListener(_networkStatsInterval), true, false, false);
    _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
    return true;
  }
  private String getOrderByLimit(Long pageSize, Long startIndex) {
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? true : isAscending);

    String sql;
    if (isAscending) {
      sql = " ORDER BY t.sort_key ASC";
    } else {
      sql = " ORDER BY t.sort_key DESC";
    }

    if ((pageSize != null) && (startIndex != null)) {
      sql += " LIMIT " + startIndex.toString() + "," + pageSize.toString();
    }
    return sql;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();

    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      s_logger.error("Unable to get the configuration dao. " + ConfigurationDao.class.getName());
      return false;
    }
    _snapshotPollInterval = NumbersUtil.parseInt(configDao.getValue("snapshot.poll.interval"), 300);
    boolean snapshotsRecurringTest =
        Boolean.parseBoolean(configDao.getValue("snapshot.recurring.test"));
    if (snapshotsRecurringTest) {
      // look for some test values in the configuration table so that snapshots can be taken more
      // frequently (QA test code)
      int minutesPerHour =
          NumbersUtil.parseInt(configDao.getValue("snapshot.test.minutes.per.hour"), 60);
      int hoursPerDay = NumbersUtil.parseInt(configDao.getValue("snapshot.test.hours.per.day"), 24);
      int daysPerWeek = NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.week"), 7);
      int daysPerMonth =
          NumbersUtil.parseInt(configDao.getValue("snapshot.test.days.per.month"), 30);
      int weeksPerMonth =
          NumbersUtil.parseInt(configDao.getValue("snapshot.test.weeks.per.month"), 4);
      int monthsPerYear =
          NumbersUtil.parseInt(configDao.getValue("snapshot.test.months.per.year"), 12);

      _testTimerTask =
          new TestClock(
              this,
              minutesPerHour,
              hoursPerDay,
              daysPerWeek,
              daysPerMonth,
              weeksPerMonth,
              monthsPerYear);
    }
    _currentTimestamp = new Date();
    s_logger.info("Snapshot Scheduler is configured.");

    return true;
  }
 @Override
 public List<VolumeJoinVO> searchByIds(Long... volIds) {
   // set detail batch query size
   int DETAILS_BATCH_SIZE = 2000;
   String batchCfg = _configDao.getValue("detail.batch.query.size");
   if (batchCfg != null) {
     DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg);
   }
   // query details by batches
   List<VolumeJoinVO> uvList = new ArrayList<VolumeJoinVO>();
   // query details by batches
   int curr_index = 0;
   if (volIds.length > DETAILS_BATCH_SIZE) {
     while ((curr_index + DETAILS_BATCH_SIZE) <= volIds.length) {
       Long[] ids = new Long[DETAILS_BATCH_SIZE];
       for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) {
         ids[k] = volIds[j];
       }
       SearchCriteria<VolumeJoinVO> sc = volSearch.create();
       sc.setParameters("idIN", ids);
       List<VolumeJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
       if (vms != null) {
         uvList.addAll(vms);
       }
       curr_index += DETAILS_BATCH_SIZE;
     }
   }
   if (curr_index < volIds.length) {
     int batch_size = (volIds.length - curr_index);
     // set the ids value
     Long[] ids = new Long[batch_size];
     for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) {
       ids[k] = volIds[j];
     }
     SearchCriteria<VolumeJoinVO> sc = volSearch.create();
     sc.setParameters("idIN", ids);
     List<VolumeJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
     if (vms != null) {
       uvList.addAll(vms);
     }
   }
   return uvList;
 }
  @Override
  public boolean configure(String name, Map<String, Object> params) {
    final Map<String, String> configs = _configDao.getConfiguration("ManagementServer", params);
    _sslCopy = Boolean.parseBoolean(configs.get("secstorage.encrypt.copy"));
    _proxy = configs.get(Config.SecStorageProxy.key());

    _ssvmUrlDomain = configs.get("secstorage.ssl.cert.domain");

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

    _agentMgr.registerForHostEvents(new DownloadListener(this), true, false, false);

    ReadyTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder();
    ReadyTemplateStatesSearch.and(
        "download_state",
        ReadyTemplateStatesSearch.entity().getDownloadState(),
        SearchCriteria.Op.EQ);
    ReadyTemplateStatesSearch.and(
        "destroyed", ReadyTemplateStatesSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
    ReadyTemplateStatesSearch.and(
        "host_id", ReadyTemplateStatesSearch.entity().getHostId(), SearchCriteria.Op.EQ);

    SearchBuilder<VMTemplateVO> TemplatesWithNoChecksumSearch = _templateDao.createSearchBuilder();
    TemplatesWithNoChecksumSearch.and(
        "checksum", TemplatesWithNoChecksumSearch.entity().getChecksum(), SearchCriteria.Op.NULL);

    ReadyTemplateStatesSearch.join(
        "vm_template",
        TemplatesWithNoChecksumSearch,
        TemplatesWithNoChecksumSearch.entity().getId(),
        ReadyTemplateStatesSearch.entity().getTemplateId(),
        JoinBuilder.JoinType.INNER);
    TemplatesWithNoChecksumSearch.done();
    ReadyTemplateStatesSearch.done();

    return true;
  }
  @Override
  public boolean finalizeVirtualMachineProfile(
      VirtualMachineProfile<SecondaryStorageVmVO> profile,
      DeployDestination dest,
      ReservationContext context) {

    SecondaryStorageVmVO vm = profile.getVirtualMachine();
    Map<String, String> details = _vmDetailsDao.findDetails(vm.getId());
    vm.setDetails(details);

    HostVO secHost = _hostDao.findSecondaryStorageHost(dest.getDataCenter().getId());
    assert (secHost != null);

    StringBuilder buf = profile.getBootArgsBuilder();
    buf.append(" template=domP type=secstorage");
    buf.append(" host=").append(_mgmt_host);
    buf.append(" port=").append(_mgmt_port);
    buf.append(" name=").append(profile.getVirtualMachine().getHostName());

    buf.append(" zone=").append(dest.getDataCenter().getId());
    buf.append(" pod=").append(dest.getPod().getId());

    buf.append(" guid=").append(profile.getVirtualMachine().getHostName());

    if (_configDao.isPremium()) {
      if (profile.getHypervisorType() == HypervisorType.Hyperv) {
        buf.append(" resource=com.cloud.storage.resource.CifsSecondaryStorageResource");
      } else {
        buf.append(" resource=com.cloud.storage.resource.PremiumSecondaryStorageResource");
      }
    } else {
      buf.append(" resource=com.cloud.storage.resource.NfsSecondaryStorageResource");
    }
    buf.append(" instance=SecStorage");
    buf.append(" sslcopy=").append(Boolean.toString(_useSSlCopy));
    buf.append(" role=").append(profile.getVirtualMachine().getRole().toString());

    boolean externalDhcp = false;
    String externalDhcpStr =
        _configDao.getValue("direct.attach.network.externalIpAllocator.enabled");
    if (externalDhcpStr != null && externalDhcpStr.equalsIgnoreCase("true")) {
      externalDhcp = true;
    }

    for (NicProfile nic : profile.getNics()) {
      int deviceId = nic.getDeviceId();
      if (nic.getIp4Address() == null) {
        buf.append(" eth").append(deviceId).append("mask=").append("0.0.0.0");
        buf.append(" eth").append(deviceId).append("ip=").append("0.0.0.0");
      } else {
        buf.append(" eth").append(deviceId).append("ip=").append(nic.getIp4Address());
        buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
      }

      buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
      if (nic.isDefaultNic()) {
        buf.append(" gateway=").append(nic.getGateway());
      }
      if (nic.getTrafficType() == TrafficType.Management) {
        String mgmt_cidr = _configDao.getValue(Config.ManagementNetwork.key());
        if (NetUtils.isValidCIDR(mgmt_cidr)) {
          buf.append(" mgmtcidr=").append(mgmt_cidr);
        }
        buf.append(" localgw=").append(dest.getPod().getGateway());
        buf.append(" private.network.device=").append("eth").append(deviceId);
      } else if (nic.getTrafficType() == TrafficType.Public) {
        buf.append(" public.network.device=").append("eth").append(deviceId);
      }
    }

    /* External DHCP mode */
    if (externalDhcp) {
      buf.append(" bootproto=dhcp");
    }

    DataCenterVO dc = _dcDao.findById(profile.getVirtualMachine().getDataCenterIdToDeployIn());
    buf.append(" internaldns1=").append(dc.getInternalDns1());
    if (dc.getInternalDns2() != null) {
      buf.append(" internaldns2=").append(dc.getInternalDns2());
    }
    buf.append(" dns1=").append(dc.getDns1());
    if (dc.getDns2() != null) {
      buf.append(" dns2=").append(dc.getDns2());
    }

    String bootArgs = buf.toString();
    if (s_logger.isDebugEnabled()) {
      s_logger.debug("Boot Args for " + profile + ": " + bootArgs);
    }

    return true;
  }
  @Override
  public boolean configure(final String name, final Map<String, Object> xmlParams)
      throws ConfigurationException {
    _name = name;
    ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);

    _serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId();

    _investigators = locator.getAdapters(Investigator.class);
    _fenceBuilders = locator.getAdapters(FenceBuilder.class);

    Map<String, String> params = new HashMap<String, String>();
    final ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao != null) {
      params = configDao.getConfiguration(Long.toHexString(_serverId), xmlParams);
    }

    String value = params.get("workers");
    final int count = NumbersUtil.parseInt(value, 1);
    _workers = new WorkerThread[count];
    for (int i = 0; i < _workers.length; i++) {
      _workers[i] = new WorkerThread("HA-Worker-" + i);
    }

    value = params.get("force.ha");
    _forceHA = Boolean.parseBoolean(value);

    value = params.get("time.to.sleep");
    _timeToSleep = NumbersUtil.parseInt(value, 60) * 1000;

    value = params.get("max.retries");
    _maxRetries = NumbersUtil.parseInt(value, 5);

    value = params.get("time.between.failures");
    _timeBetweenFailures = NumbersUtil.parseLong(value, 3600) * 1000;

    value = params.get("time.between.cleanup");
    _timeBetweenCleanups = NumbersUtil.parseLong(value, 3600 * 24);

    value = params.get("stop.retry.interval");
    _stopRetryInterval = NumbersUtil.parseInt(value, 10 * 60);

    value = params.get("restart.retry.interval");
    _restartRetryInterval = NumbersUtil.parseInt(value, 10 * 60);

    value = params.get("investigate.retry.interval");
    _investigateRetryInterval = NumbersUtil.parseInt(value, 1 * 60);

    value = params.get("migrate.retry.interval");
    _migrateRetryInterval = NumbersUtil.parseInt(value, 2 * 60);

    _instance = params.get("instance");
    if (_instance == null) {
      _instance = "VMOPS";
    }

    _haDao.releaseWorkItems(_serverId);

    _stopped = true;

    _executor = Executors.newScheduledThreadPool(count, new NamedThreadFactory("HA"));

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
    _systemAcct = _accountService.getSystemAccount();
    _instance = configs.get("instance.name");
    if (_instance == null) {
      _instance = "VM";
    }
    _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
    _mgmtHost = _configDao.getValue(Config.ManagementHostIPAdr.key());

    boolean useLocalStorage =
        Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));

    _elasticLbVmRamSize =
        NumbersUtil.parseInt(
            configs.get(Config.ElasticLoadBalancerVmMemory.key()), DEFAULT_ELB_VM_RAMSIZE);
    _elasticLbvmCpuMHz =
        NumbersUtil.parseInt(
            configs.get(Config.ElasticLoadBalancerVmCpuMhz.key()), DEFAULT_ELB_VM_CPU_MHZ);
    _elasticLbvmNumCpu =
        NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmNumVcpu.key()), 1);
    _elasticLbVmOffering =
        new ServiceOfferingVO(
            "System Offering For Elastic LB VM",
            _elasticLbvmNumCpu,
            _elasticLbVmRamSize,
            _elasticLbvmCpuMHz,
            0,
            0,
            true,
            null,
            useLocalStorage,
            true,
            null,
            true,
            VirtualMachine.Type.ElasticLoadBalancerVm,
            true);
    _elasticLbVmOffering.setUniqueName(ServiceOffering.elbVmDefaultOffUniqueName);
    _elasticLbVmOffering = _serviceOfferingDao.persistSystemServiceOffering(_elasticLbVmOffering);

    String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key());
    _enabled = (enabled == null) ? false : Boolean.parseBoolean(enabled);
    s_logger.info("Elastic Load balancer enabled: " + _enabled);
    if (_enabled) {
      String traffType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key());
      if ("guest".equalsIgnoreCase(traffType)) {
        _frontendTrafficType = TrafficType.Guest;
      } else if ("public".equalsIgnoreCase(traffType)) {
        _frontendTrafficType = TrafficType.Public;
      } else
        throw new ConfigurationException(
            "ELB: Traffic type for front end of load balancer has to be guest or public; found : "
                + traffType);
      s_logger.info("ELB: Elastic Load Balancer: will balance on " + traffType);
      int gcIntervalMinutes =
          NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmGcInterval.key()), 5);
      if (gcIntervalMinutes < 5) gcIntervalMinutes = 5;
      s_logger.info(
          "ELB: Elastic Load Balancer: scheduling GC to run every "
              + gcIntervalMinutes
              + " minutes");
      _gcThreadPool = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ELBVM-GC"));
      _gcThreadPool.scheduleAtFixedRate(
          new CleanupThread(), gcIntervalMinutes, gcIntervalMinutes, TimeUnit.MINUTES);
      _itMgr.registerGuru(VirtualMachine.Type.ElasticLoadBalancerVm, this);
    }

    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    s_logger.info("Configure VmwareManagerImpl, manager name: " + name);

    if (!_configDao.isPremium()) {
      s_logger.error("Vmware component can only run under premium distribution");
      throw new ConfigurationException("Vmware component can only run under premium distribution");
    }

    _instance = _configDao.getValue(Config.InstanceName.key());
    if (_instance == null) {
      _instance = "DEFAULT";
    }
    s_logger.info("VmwareManagerImpl config - instance.name: " + _instance);

    _mountParent = _configDao.getValue(Config.MountParent.key());
    if (_mountParent == null) {
      _mountParent = File.separator + "mnt";
    }

    if (_instance != null) {
      _mountParent = _mountParent + File.separator + _instance;
    }
    s_logger.info("VmwareManagerImpl config - _mountParent: " + _mountParent);

    String value = (String) params.get("scripts.timeout");
    _timeout = NumbersUtil.parseInt(value, 1440) * 1000;

    _storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey);
    if (_storage == null) {
      _storage = new JavaStorageLayer();
      _storage.configure("StorageLayer", params);
    }

    value = _configDao.getValue(Config.VmwareCreateFullClone.key());
    if (value == null) {
      _fullCloneFlag = false;
    } else {
      _fullCloneFlag = Boolean.parseBoolean(value);
    }
    _portsPerDvPortGroup =
        NumbersUtil.parseInt(
            _configDao.getValue(Config.VmwarePortsPerDVPortGroup.key()), _portsPerDvPortGroup);

    _serviceConsoleName = _configDao.getValue(Config.VmwareServiceConsole.key());
    if (_serviceConsoleName == null) {
      _serviceConsoleName = "Service Console";
    }

    _managemetPortGroupName = _configDao.getValue(Config.VmwareManagementPortGroup.key());
    if (_managemetPortGroupName == null) {
      _managemetPortGroupName = "Management Network";
    }

    _defaultSystemVmNicAdapterType = _configDao.getValue(Config.VmwareSystemVmNicDeviceType.key());
    if (_defaultSystemVmNicAdapterType == null) {
      _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString();
    }

    _additionalPortRangeStart =
        NumbersUtil.parseInt(
            _configDao.getValue(Config.VmwareAdditionalVncPortRangeStart.key()), 59000);
    if (_additionalPortRangeStart > 65535) {
      s_logger.warn(
          "Invalid port range start port ("
              + _additionalPortRangeStart
              + ") for additional VNC port allocation, reset it to default start port 59000");
      _additionalPortRangeStart = 59000;
    }

    _additionalPortRangeSize =
        NumbersUtil.parseInt(
            _configDao.getValue(Config.VmwareAdditionalVncPortRangeSize.key()), 1000);
    if (_additionalPortRangeSize < 0
        || _additionalPortRangeStart + _additionalPortRangeSize > 65535) {
      s_logger.warn(
          "Invalid port range size ("
              + _additionalPortRangeSize
              + " for range starts at "
              + _additionalPortRangeStart);
      _additionalPortRangeSize = Math.min(1000, 65535 - _additionalPortRangeStart);
    }

    _routerExtraPublicNics =
        NumbersUtil.parseInt(_configDao.getValue(Config.RouterExtraPublicNics.key()), 2);

    _reserveCpu = _configDao.getValue(Config.VmwareReserveCpu.key());
    if (_reserveCpu == null || _reserveCpu.isEmpty()) {
      _reserveCpu = "false";
    }
    _reserveMem = _configDao.getValue(Config.VmwareReserveMem.key());
    if (_reserveMem == null || _reserveMem.isEmpty()) {
      _reserveMem = "false";
    }

    _recycleHungWorker = _configDao.getValue(Config.VmwareRecycleHungWorker.key());
    if (_recycleHungWorker == null || _recycleHungWorker.isEmpty()) {
      _recycleHungWorker = "false";
    }

    _rootDiskController = _configDao.getValue(Config.VmwareRootDiskControllerType.key());
    if (_rootDiskController == null || _rootDiskController.isEmpty()) {
      _rootDiskController = DiskControllerType.ide.toString();
    }

    s_logger.info(
        "Additional VNC port allocation range is settled at "
            + _additionalPortRangeStart
            + " to "
            + (_additionalPortRangeStart + _additionalPortRangeSize));

    value = _configDao.getValue("vmware.host.scan.interval");
    _hostScanInterval = NumbersUtil.parseLong(value, DEFAULT_HOST_SCAN_INTERVAL);
    s_logger.info("VmwareManagerImpl config - vmware.host.scan.interval: " + _hostScanInterval);

    ((VmwareStorageManagerImpl) _storageMgr).configure(params);

    _agentMgr.registerForHostEvents(this, true, true, true);

    s_logger.info("VmwareManagerImpl has been successfully configured");
    return true;
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    if (s_logger.isInfoEnabled()) {
      s_logger.info("Start configuring secondary storage vm manager : " + name);
    }

    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      throw new ConfigurationException("Unable to get the configuration dao.");
    }

    Map<String, String> configs = configDao.getConfiguration("management-server", params);

    _secStorageVmRamSize =
        NumbersUtil.parseInt(configs.get("secstorage.vm.ram.size"), DEFAULT_SS_VM_RAMSIZE);
    _secStorageVmCpuMHz =
        NumbersUtil.parseInt(configs.get("secstorage.vm.cpu.mhz"), DEFAULT_SS_VM_CPUMHZ);
    String useServiceVM = configDao.getValue("secondary.storage.vm");
    boolean _useServiceVM = false;
    if ("true".equalsIgnoreCase(useServiceVM)) {
      _useServiceVM = true;
    }

    String sslcopy = configDao.getValue("secstorage.encrypt.copy");
    if ("true".equalsIgnoreCase(sslcopy)) {
      _useSSlCopy = true;
    }

    _allowedInternalSites = configDao.getValue("secstorage.allowed.internal.sites");

    String value = configs.get("secstorage.capacityscan.interval");
    _capacityScanInterval = NumbersUtil.parseLong(value, DEFAULT_CAPACITY_SCAN_INTERVAL);

    _instance = configs.get("instance.name");
    if (_instance == null) {
      _instance = "DEFAULT";
    }

    Map<String, String> agentMgrConfigs = configDao.getConfiguration("AgentManager", params);
    _mgmt_host = agentMgrConfigs.get("host");
    if (_mgmt_host == null) {
      s_logger.warn(
          "Critical warning! Please configure your management server host address right after you have started your management server and then restart it, otherwise you won't have access to secondary storage");
    }

    value = agentMgrConfigs.get("port");
    _mgmt_port = NumbersUtil.parseInt(value, 8250);

    _listener = new SecondaryStorageListener(this, _agentMgr);
    _agentMgr.registerForHostEvents(_listener, true, false, true);

    _itMgr.registerGuru(VirtualMachine.Type.SecondaryStorageVm, this);

    _useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
    _serviceOffering =
        new ServiceOfferingVO(
            "System Offering For Secondary Storage VM",
            1,
            _secStorageVmRamSize,
            _secStorageVmCpuMHz,
            null,
            null,
            false,
            null,
            _useLocalStorage,
            true,
            null,
            true,
            VirtualMachine.Type.SecondaryStorageVm,
            true);
    _serviceOffering.setUniqueName("Cloud.com-SecondaryStorage");
    _serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering);

    // this can sometimes happen, if DB is manually or programmatically manipulated
    if (_serviceOffering == null) {
      String msg =
          "Data integrity problem : System Offering For Secondary Storage VM has been removed?";
      s_logger.error(msg);
      throw new ConfigurationException(msg);
    }

    if (_useServiceVM) {
      _loadScanner = new SystemVmLoadScanner<Long>(this);
      _loadScanner.initScan(STARTUP_DELAY, _capacityScanInterval);
    }
    if (s_logger.isInfoEnabled()) {
      s_logger.info("Secondary storage vm Manager is configured.");
    }
    return true;
  }
  public TemplateProfile prepare(
      boolean isIso,
      Long userId,
      String name,
      String displayText,
      Integer bits,
      Boolean passwordEnabled,
      Boolean requiresHVM,
      String url,
      Boolean isPublic,
      Boolean featured,
      Boolean isExtractable,
      String format,
      Long guestOSId,
      Long zoneId,
      HypervisorType hypervisorType,
      String chksum,
      Boolean bootable,
      String templateTag,
      Account templateOwner,
      Map details)
      throws ResourceAllocationException {
    // Long accountId = null;
    // parameters verification

    if (isPublic == null) {
      isPublic = Boolean.FALSE;
    }

    if (zoneId.longValue() == -1) {
      zoneId = null;
    }

    if (isIso) {
      if (bootable == null) {
        bootable = Boolean.TRUE;
      }
      GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
      if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
        throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
      }
      if (bootable == false) {
        guestOSId = noneGuestOs.getId(); // Guest os id of None.
      }
    } else {
      if (bits == null) {
        bits = Integer.valueOf(64);
      }
      if (passwordEnabled == null) {
        passwordEnabled = false;
      }
      if (requiresHVM == null) {
        requiresHVM = true;
      }
    }

    if (isExtractable == null) {
      isExtractable = Boolean.FALSE;
    }

    boolean isAdmin =
        _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN;

    if (!isAdmin && zoneId == null) {
      throw new InvalidParameterValueException("Please specify a valid zone Id.");
    }

    if (url.toLowerCase().contains("file://")) {
      throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }

    boolean allowPublicUserTemplates =
        Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates"));
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
      throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }

    if (!isAdmin || featured == null) {
      featured = Boolean.FALSE;
    }

    // If command is executed via 8096 port, set userId to the id of System
    // account (1)
    if (userId == null) {
      userId = Long.valueOf(1);
    }

    ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase());
    if (imgfmt == null) {
      throw new IllegalArgumentException(
          "Image format is incorrect "
              + format
              + ". Supported formats are "
              + EnumUtils.listValues(ImageFormat.values()));
    }

    // Check that the resource limit for templates/ISOs won't be exceeded
    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new IllegalArgumentException("Unable to find user with id " + userId);
    }

    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);

    if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) {
      throw new IllegalArgumentException("Only admins can create templates in all zones");
    }

    // If a zoneId is specified, make sure it is valid
    if (zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      if (zone == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
      }
      Account caller = UserContext.current().getCaller();
      if (Grouping.AllocationState.Disabled == zone.getAllocationState()
          && !_accountMgr.isRootAdmin(caller.getType())) {
        throw new PermissionDeniedException(
            "Cannot perform this operation, Zone is currently disabled: " + zoneId);
      }
    }

    List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (VMTemplateVO template : systemvmTmplts) {
      if (template.getName().equalsIgnoreCase(name)
          || template.getDisplayText().equalsIgnoreCase(displayText)) {
        throw new IllegalArgumentException("Cannot use reserved names for templates");
      }
    }

    Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    UserContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(
        id,
        userId,
        name,
        displayText,
        bits,
        passwordEnabled,
        requiresHVM,
        url,
        isPublic,
        featured,
        isExtractable,
        imgfmt,
        guestOSId,
        zoneId,
        hypervisorType,
        templateOwner.getAccountName(),
        templateOwner.getDomainId(),
        templateOwner.getAccountId(),
        chksum,
        bootable,
        templateTag,
        details);
  }
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    s_logger.info("Configure VmwareManagerImpl, manager name: " + name);

    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      throw new ConfigurationException("Unable to get the configuration dao.");
    }

    if (!configDao.isPremium()) {
      s_logger.error("Vmware component can only run under premium distribution");
      throw new ConfigurationException("Vmware component can only run under premium distribution");
    }

    _instance = configDao.getValue(Config.InstanceName.key());
    if (_instance == null) {
      _instance = "DEFAULT";
    }
    s_logger.info("VmwareManagerImpl config - instance.name: " + _instance);

    _mountParent = configDao.getValue(Config.MountParent.key());
    if (_mountParent == null) {
      _mountParent = File.separator + "mnt";
    }

    if (_instance != null) {
      _mountParent = _mountParent + File.separator + _instance;
    }
    s_logger.info("VmwareManagerImpl config - _mountParent: " + _mountParent);

    String value = (String) params.get("scripts.timeout");
    _timeout = NumbersUtil.parseInt(value, 1440) * 1000;

    _storage = (StorageLayer) params.get(StorageLayer.InstanceConfigKey);
    if (_storage == null) {
      value = (String) params.get(StorageLayer.ClassConfigKey);
      if (value == null) {
        value = "com.cloud.storage.JavaStorageLayer";
      }

      try {
        Class<?> clazz = Class.forName(value);
        _storage = (StorageLayer) ComponentLocator.inject(clazz);
        _storage.configure("StorageLayer", params);
      } catch (ClassNotFoundException e) {
        throw new ConfigurationException("Unable to find class " + value);
      }
    }

    _privateNetworkVSwitchName = configDao.getValue(Config.VmwarePrivateNetworkVSwitch.key());
    if (_privateNetworkVSwitchName == null) {
      _privateNetworkVSwitchName = "vSwitch0";
    }

    _publicNetworkVSwitchName = configDao.getValue(Config.VmwarePublicNetworkVSwitch.key());
    if (_publicNetworkVSwitchName == null) {
      _publicNetworkVSwitchName = "vSwitch0";
    }

    _guestNetworkVSwitchName = configDao.getValue(Config.VmwareGuestNetworkVSwitch.key());
    if (_guestNetworkVSwitchName == null) {
      _guestNetworkVSwitchName = "vSwitch0";
    }

    _serviceConsoleName = configDao.getValue(Config.VmwareServiceConsole.key());
    if (_serviceConsoleName == null) {
      _serviceConsoleName = "Service Console";
    }

    _managemetPortGroupName = configDao.getValue(Config.VmwareManagementPortGroup.key());
    if (_managemetPortGroupName == null) {
      _managemetPortGroupName = "Management Network";
    }

    configDao.getValue(Config.VmwareServiceConsole.key());
    _additionalPortRangeStart =
        NumbersUtil.parseInt(
            configDao.getValue(Config.VmwareAdditionalVncPortRangeStart.key()), 59000);
    if (_additionalPortRangeStart > 65535) {
      s_logger.warn(
          "Invalid port range start port ("
              + _additionalPortRangeStart
              + ") for additional VNC port allocation, reset it to default start port 59000");
      _additionalPortRangeStart = 59000;
    }

    _additionalPortRangeSize =
        NumbersUtil.parseInt(
            configDao.getValue(Config.VmwareAdditionalVncPortRangeSize.key()), 1000);
    if (_additionalPortRangeSize < 0
        || _additionalPortRangeStart + _additionalPortRangeSize > 65535) {
      s_logger.warn(
          "Invalid port range size ("
              + _additionalPortRangeSize
              + " for range starts at "
              + _additionalPortRangeStart);
      _additionalPortRangeSize = Math.min(1000, 65535 - _additionalPortRangeStart);
    }

    _maxHostsPerCluster =
        NumbersUtil.parseInt(
            configDao.getValue(Config.VmwarePerClusterHostMax.key()),
            VmwareManager.MAX_HOSTS_PER_CLUSTER);
    _cpuOverprovisioningFactor = configDao.getValue(Config.CPUOverprovisioningFactor.key());
    if (_cpuOverprovisioningFactor == null || _cpuOverprovisioningFactor.isEmpty())
      _cpuOverprovisioningFactor = "1";

    _memOverprovisioningFactor = configDao.getValue(Config.MemOverprovisioningFactor.key());
    if (_memOverprovisioningFactor == null || _memOverprovisioningFactor.isEmpty())
      _memOverprovisioningFactor = "1";

    _reserveCpu = configDao.getValue(Config.VmwareReserveCpu.key());
    if (_reserveCpu == null || _reserveCpu.isEmpty()) _reserveCpu = "false";
    _reserveMem = configDao.getValue(Config.VmwareReserveMem.key());
    if (_reserveMem == null || _reserveMem.isEmpty()) _reserveMem = "false";

    s_logger.info(
        "Additional VNC port allocation range is settled at "
            + _additionalPortRangeStart
            + " to "
            + (_additionalPortRangeStart + _additionalPortRangeSize));

    value = configDao.getValue(Config.VmwareGuestNicDeviceType.key());
    if (value == null || "E1000".equalsIgnoreCase(value))
      this._guestNicDeviceType = VirtualEthernetCardType.E1000;
    else if ("PCNet32".equalsIgnoreCase(value))
      this._guestNicDeviceType = VirtualEthernetCardType.PCNet32;
    else if ("Vmxnet2".equalsIgnoreCase(value))
      this._guestNicDeviceType = VirtualEthernetCardType.Vmxnet2;
    else if ("Vmxnet3".equalsIgnoreCase(value))
      this._guestNicDeviceType = VirtualEthernetCardType.Vmxnet3;
    else this._guestNicDeviceType = VirtualEthernetCardType.E1000;

    value = configDao.getValue("vmware.host.scan.interval");
    _hostScanInterval = NumbersUtil.parseLong(value, DEFAULT_HOST_SCAN_INTERVAL);
    s_logger.info("VmwareManagerImpl config - vmware.host.scan.interval: " + _hostScanInterval);

    ((VmwareStorageManagerImpl) _storageMgr).configure(params);

    _agentMgr.registerForHostEvents(this, true, true, true);

    s_logger.info("VmwareManagerImpl has been successfully configured");
    return true;
  }
Beispiel #27
0
  @Override
  public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    _name = name;

    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
      s_logger.error("Unable to get the configuration dao.");
      return false;
    }

    Map<String, String> configs = configDao.getConfiguration("management-server", params);

    // set up the email system for alerts
    String emailAddressList = configs.get("alert.email.addresses");
    String[] emailAddresses = null;
    if (emailAddressList != null) {
      emailAddresses = emailAddressList.split(",");
    }

    String smtpHost = configs.get("alert.smtp.host");
    int smtpPort = NumbersUtil.parseInt(configs.get("alert.smtp.port"), 25);
    String useAuthStr = configs.get("alert.smtp.useAuth");
    boolean useAuth = ((useAuthStr == null) ? false : Boolean.parseBoolean(useAuthStr));
    String smtpUsername = configs.get("alert.smtp.username");
    String smtpPassword = configs.get("alert.smtp.password");
    String emailSender = configs.get("alert.email.sender");
    String smtpDebugStr = configs.get("alert.smtp.debug");
    boolean smtpDebug = false;
    if (smtpDebugStr != null) {
      smtpDebug = Boolean.parseBoolean(smtpDebugStr);
    }

    _emailAlert =
        new EmailAlert(
            emailAddresses,
            smtpHost,
            smtpPort,
            useAuth,
            smtpUsername,
            smtpPassword,
            emailSender,
            smtpDebug);

    String storageCapacityThreshold = _configDao.getValue(Config.StorageCapacityThreshold.key());
    String cpuCapacityThreshold = _configDao.getValue(Config.CPUCapacityThreshold.key());
    String memoryCapacityThreshold = _configDao.getValue(Config.MemoryCapacityThreshold.key());
    String storageAllocCapacityThreshold =
        _configDao.getValue(Config.StorageAllocatedCapacityThreshold.key());
    String publicIPCapacityThreshold = _configDao.getValue(Config.PublicIpCapacityThreshold.key());
    String privateIPCapacityThreshold =
        _configDao.getValue(Config.PrivateIpCapacityThreshold.key());
    String secondaryStorageCapacityThreshold =
        _configDao.getValue(Config.SecondaryStorageCapacityThreshold.key());
    String vlanCapacityThreshold = _configDao.getValue(Config.VlanCapacityThreshold.key());
    String directNetworkPublicIpCapacityThreshold =
        _configDao.getValue(Config.DirectNetworkPublicIpCapacityThreshold.key());
    String localStorageCapacityThreshold =
        _configDao.getValue(Config.LocalStorageCapacityThreshold.key());

    if (storageCapacityThreshold != null) {
      _storageCapacityThreshold = Double.parseDouble(storageCapacityThreshold);
    }
    if (storageAllocCapacityThreshold != null) {
      _storageAllocCapacityThreshold = Double.parseDouble(storageAllocCapacityThreshold);
    }
    if (cpuCapacityThreshold != null) {
      _cpuCapacityThreshold = Double.parseDouble(cpuCapacityThreshold);
    }
    if (memoryCapacityThreshold != null) {
      _memoryCapacityThreshold = Double.parseDouble(memoryCapacityThreshold);
    }
    if (publicIPCapacityThreshold != null) {
      _publicIPCapacityThreshold = Double.parseDouble(publicIPCapacityThreshold);
    }
    if (privateIPCapacityThreshold != null) {
      _privateIPCapacityThreshold = Double.parseDouble(privateIPCapacityThreshold);
    }
    if (secondaryStorageCapacityThreshold != null) {
      _secondaryStorageCapacityThreshold = Double.parseDouble(secondaryStorageCapacityThreshold);
    }
    if (vlanCapacityThreshold != null) {
      _vlanCapacityThreshold = Double.parseDouble(vlanCapacityThreshold);
    }
    if (directNetworkPublicIpCapacityThreshold != null) {
      _directNetworkPublicIpCapacityThreshold =
          Double.parseDouble(directNetworkPublicIpCapacityThreshold);
    }
    if (localStorageCapacityThreshold != null) {
      _localStorageCapacityThreshold = Double.parseDouble(localStorageCapacityThreshold);
    }

    _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_STORAGE, _storageCapacityThreshold);
    _capacityTypeThresholdMap.put(
        Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, _storageAllocCapacityThreshold);
    _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, _cpuCapacityThreshold);
    _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, _memoryCapacityThreshold);
    _capacityTypeThresholdMap.put(
        Capacity.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP, _publicIPCapacityThreshold);
    _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_PRIVATE_IP, _privateIPCapacityThreshold);
    _capacityTypeThresholdMap.put(
        Capacity.CAPACITY_TYPE_SECONDARY_STORAGE, _secondaryStorageCapacityThreshold);
    _capacityTypeThresholdMap.put(Capacity.CAPACITY_TYPE_VLAN, _vlanCapacityThreshold);
    _capacityTypeThresholdMap.put(
        Capacity.CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP, _directNetworkPublicIpCapacityThreshold);
    _capacityTypeThresholdMap.put(
        Capacity.CAPACITY_TYPE_LOCAL_STORAGE, _localStorageCapacityThreshold);

    String capacityCheckPeriodStr = configs.get("capacity.check.period");
    if (capacityCheckPeriodStr != null) {
      _capacityCheckPeriod = Long.parseLong(capacityCheckPeriodStr);
      if (_capacityCheckPeriod <= 0)
        _capacityCheckPeriod = Long.parseLong(Config.CapacityCheckPeriod.getDefaultValue());
    }

    String cpuOverProvisioningFactorStr = configs.get("cpu.overprovisioning.factor");
    if (cpuOverProvisioningFactorStr != null) {
      _cpuOverProvisioningFactor = NumbersUtil.parseFloat(cpuOverProvisioningFactorStr, 1);
      if (_cpuOverProvisioningFactor < 1) {
        _cpuOverProvisioningFactor = 1;
      }
    }

    _timer = new Timer("CapacityChecker");

    return true;
  }