@Override
  public boolean finalizeDeployment(
      Commands cmds,
      VirtualMachineProfile<SecondaryStorageVmVO> profile,
      DeployDestination dest,
      ReservationContext context) {

    finalizeCommandsOnStart(cmds, profile);

    SecondaryStorageVmVO secVm = profile.getVirtualMachine();
    DataCenter dc = dest.getDataCenter();
    List<NicProfile> nics = profile.getNics();
    for (NicProfile nic : nics) {
      if ((nic.getTrafficType() == TrafficType.Public
              && dc.getNetworkType() == NetworkType.Advanced)
          || (nic.getTrafficType() == TrafficType.Guest
              && (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()))) {
        secVm.setPublicIpAddress(nic.getIp4Address());
        secVm.setPublicNetmask(nic.getNetmask());
        secVm.setPublicMacAddress(nic.getMacAddress());
      } else if (nic.getTrafficType() == TrafficType.Management) {
        secVm.setPrivateIpAddress(nic.getIp4Address());
        secVm.setPrivateMacAddress(nic.getMacAddress());
      }
    }
    _secStorageVmDao.update(secVm.getId(), secVm);
    return true;
  }
  @Override
  public Network design(
      final NetworkOffering offering,
      final DeploymentPlan plan,
      final Network userSpecified,
      final Account owner) {
    // Check of the isolation type of the related physical network is supported
    final PhysicalNetworkVO physnet = physicalNetworkDao.findById(plan.getPhysicalNetworkId());
    final DataCenter dc = _dcDao.findById(plan.getDataCenterId());
    if (!canHandle(offering, dc.getNetworkType(), physnet)) {
      s_logger.debug("Refusing to design this network");
      return null;
    }

    final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(physnet.getId());
    if (devices.isEmpty()) {
      s_logger.error("No NiciraNvp Controller on physical network " + physnet.getName());
      return null;
    }
    s_logger.debug(
        "Nicira Nvp " + devices.get(0).getUuid() + " found on physical network " + physnet.getId());

    s_logger.debug(
        "Physical isolation type is supported, asking GuestNetworkGuru to design this network");
    final NetworkVO networkObject = (NetworkVO) super.design(offering, plan, userSpecified, owner);
    if (networkObject == null) {
      return null;
    }
    networkObject.setBroadcastDomainType(BroadcastDomainType.Lswitch);

    return networkObject;
  }
 @Override
 public void updateNicProfile(NicProfile profile, Network network) {
   DataCenter dc = _dcDao.findById(network.getDataCenterId());
   if (profile != null) {
     profile.setDns1(dc.getDns1());
     profile.setDns2(dc.getDns2());
   }
 }
 public NetworkType getNetworkType() {
   Network ntwk = _entityMgr.findById(Network.class, getNetworkId());
   if (ntwk != null) {
     DataCenter dc = _entityMgr.findById(DataCenter.class, ntwk.getDataCenterId());
     return dc.getNetworkType();
   }
   return null;
 }
  @Override
  public Network design(
      NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {
    DataCenter dc = _dcDao.findById(plan.getDataCenterId());

    if (!canHandle(offering, dc)) {
      return null;
    }

    State state = State.Allocated;
    if (dc.getNetworkType() == NetworkType.Basic) {
      state = State.Setup;
    }

    NetworkVO config =
        new NetworkVO(
            offering.getTrafficType(),
            Mode.Dhcp,
            BroadcastDomainType.Vlan,
            offering.getId(),
            state,
            plan.getDataCenterId(),
            plan.getPhysicalNetworkId());

    if (userSpecified != null) {
      if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null)
          || (userSpecified.getCidr() != null && userSpecified.getGateway() == null)) {
        throw new InvalidParameterValueException("cidr and gateway must be specified together.");
      }

      if (userSpecified.getCidr() != null) {
        config.setCidr(userSpecified.getCidr());
        config.setGateway(userSpecified.getGateway());
      }

      if (userSpecified.getBroadcastUri() != null) {
        config.setBroadcastUri(userSpecified.getBroadcastUri());
        config.setState(State.Setup);
      }

      if (userSpecified.getBroadcastDomainType() != null) {
        config.setBroadcastDomainType(userSpecified.getBroadcastDomainType());
      }
    }

    boolean isSecurityGroupEnabled =
        _networkMgr.areServicesSupportedByNetworkOffering(offering.getId(), Service.SecurityGroup);
    if (isSecurityGroupEnabled) {
      config.setName("SecurityGroupEnabledNetwork");
      config.setDisplayText("SecurityGroupEnabledNetwork");
    }

    return config;
  }
  private boolean canHandle(Network config) {
    DataCenter zone = _configMgr.getZone(config.getDataCenterId());
    if ((zone.getNetworkType() == NetworkType.Advanced
            && config.getGuestType() != Network.GuestType.Isolated)
        || (zone.getNetworkType() == NetworkType.Basic
            && config.getGuestType() != Network.GuestType.Shared)) {
      s_logger.trace("Not handling network type = " + config.getGuestType());
      return false;
    }

    return _networkManager.networkIsConfiguredForExternalNetworking(zone.getId(), config.getId());
  }
  @Override
  public void reserve(
      NicProfile nic,
      Network config,
      VirtualMachineProfile<? extends VirtualMachine> vm,
      DeployDestination dest,
      ReservationContext context)
      throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
    assert (nic.getReservationStrategy() == ReservationStrategy.Start)
        : "What can I do for nics that are not allocated at start? ";
    boolean _isEnabled = Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()));
    if (_isEnabled) {
      return;
    }

    DataCenter dc = _dcDao.findById(config.getDataCenterId());

    if (_networkModel.networkIsConfiguredForExternalNetworking(
        config.getDataCenterId(), config.getId())) {
      nic.setBroadcastUri(config.getBroadcastUri());
      nic.setIsolationUri(config.getBroadcastUri());
      nic.setDns1(dc.getDns1());
      nic.setDns2(dc.getDns2());
      nic.setNetmask(NetUtils.cidr2Netmask(config.getCidr()));
      long cidrAddress = NetUtils.ip2Long(config.getCidr().split("/")[0]);
      int cidrSize = getGloballyConfiguredCidrSize();
      nic.setGateway(config.getGateway());

      if (nic.getIp4Address() == null) {
        String guestIp = _networkMgr.acquireGuestIpAddress(config, null);
        if (guestIp == null) {
          throw new InsufficientVirtualNetworkCapcityException(
              "Unable to acquire guest IP address for network " + config,
              DataCenter.class,
              dc.getId());
        }

        nic.setIp4Address(guestIp);
      } else {
        long ipMask =
            NetUtils.ip2Long(nic.getIp4Address()) & ~(0xffffffffffffffffl << (32 - cidrSize));
        nic.setIp4Address(NetUtils.long2Ip(cidrAddress | ipMask));
      }
    } else {
      super.reserve(nic, config, vm, dest, context);
    }
  }
  @Override
  public Network design(
      NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) {

    PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId());
    DataCenter dc = _dcDao.findById(plan.getDataCenterId());
    if (!canHandle(offering, dc.getNetworkType(), physnet)) {
      s_logger.debug("Refusing to design this network");
      return null;
    }
    NetworkVO config = (NetworkVO) super.design(offering, plan, userSpecified, owner);
    if (config == null) {
      return null;
    }

    config.setBroadcastDomainType(BroadcastDomainType.Vswitch);

    return config;
  }
 protected boolean canHandle(NetworkOffering offering, DataCenter dc) {
   // this guru handles only Guest networks in Advance zone with source nat service disabled
   if (dc.getNetworkType() == NetworkType.Advanced
       && isMyTrafficType(offering.getTrafficType())
       && offering.getGuestType() == GuestType.Shared) {
     return true;
   } else {
     s_logger.trace("We only take care of Guest networks of type " + GuestType.Shared);
     return false;
   }
 }
  @Override
  public boolean shutdown(Network network, ReservationContext context, boolean cleanup)
      throws ResourceUnavailableException, ConcurrentOperationException {
    DataCenter zone = _configMgr.getZone(network.getDataCenterId());

    // don't have to implement network is Basic zone
    if (zone.getNetworkType() == NetworkType.Basic) {
      s_logger.debug("Not handling network shutdown in zone of type " + NetworkType.Basic);
      return false;
    }

    if (!canHandle(network)) {
      return false;
    }
    try {
      return _externalNetworkManager.manageGuestNetworkWithExternalFirewall(false, network);
    } catch (InsufficientCapacityException capacityException) {
      // TODO: handle out of capacity exception
      return false;
    }
  }
  protected void getIp(
      NicProfile nic,
      DataCenter dc,
      VirtualMachineProfile<? extends VirtualMachine> vm,
      Network network)
      throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
          ConcurrentOperationException {
    if (nic.getIp4Address() == null) {
      PublicIp ip =
          _networkMgr.assignPublicIpAddress(
              dc.getId(),
              vm.getOwner(),
              dc.getNetworkType().equals(NetworkType.Basic)
                  ? VlanType.DirectAttached
                  : VlanType.VirtualNetwork,
              null);
      nic.setIp4Address(ip.getAddress().toString());
      nic.setGateway(ip.getGateway());
      nic.setNetmask(ip.getNetmask());
      if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase("untagged")) {
        nic.setIsolationUri(URI.create("vlan://untagged"));
        nic.setBroadcastUri(URI.create("vlan://untagged"));
        nic.setBroadcastType(BroadcastDomainType.Native);
      } else if (ip.getVlanTag() != null) {
        nic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
        nic.setBroadcastUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
        nic.setBroadcastType(BroadcastDomainType.Vlan);
      }

      nic.setFormat(AddressFormat.Ip4);
      nic.setReservationId(String.valueOf(ip.getVlanTag()));
      nic.setMacAddress(ip.getMacAddress());
    }
    nic.setDns1(dc.getDns1());
    nic.setDns2(dc.getDns2());
  }
  @Override
  public boolean implement(
      Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
      throws ConcurrentOperationException, ResourceUnavailableException,
          InsufficientCapacityException {
    DataCenter zone = _configMgr.getZone(network.getDataCenterId());

    if (zone.getNetworkType() == NetworkType.Basic) {
      s_logger.debug("Not handling network implement in zone of type " + NetworkType.Basic);
      return false;
    }

    if (!canHandle(network)) {
      return false;
    }

    List<CiscoVnmcControllerVO> devices =
        _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
    if (devices.isEmpty()) {
      s_logger.error("No Cisco Vnmc device on network " + network.getName());
      return false;
    }

    List<CiscoAsa1000vDeviceVO> asaList =
        _ciscoAsa1000vDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
    if (asaList.isEmpty()) {
      s_logger.debug("No Cisco ASA 1000v device on network " + network.getName());
      return false;
    }

    NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId());
    if (asaForNetwork != null) {
      s_logger.debug("Cisco ASA 1000v device already associated with network " + network.getName());
      return true;
    }

    if (!_networkModel.isProviderSupportServiceInNetwork(
        network.getId(), Service.SourceNat, Provider.CiscoVnmc)) {
      s_logger.error(
          "SourceNat service is not provided by Cisco Vnmc device on network " + network.getName());
      return false;
    }

    Transaction txn = Transaction.currentTxn();
    boolean status = false;
    try {
      txn.start();

      // ensure that there is an ASA 1000v assigned to this network
      CiscoAsa1000vDevice assignedAsa = assignAsa1000vToNetwork(network);
      if (assignedAsa == null) {
        s_logger.error("Unable to assign ASA 1000v device to network " + network.getName());
        return false;
      }

      ClusterVO asaCluster = _clusterDao.findById(assignedAsa.getClusterId());
      ClusterVSMMapVO clusterVsmMap = _clusterVsmMapDao.findByClusterId(assignedAsa.getClusterId());
      if (clusterVsmMap == null) {
        s_logger.error(
            "Vmware cluster "
                + asaCluster.getName()
                + " has no Cisco Nexus VSM device associated with it");
        return false;
      }

      CiscoNexusVSMDeviceVO vsmDevice = _vsmDeviceDao.findById(clusterVsmMap.getVsmId());
      if (vsmDevice == null) {
        s_logger.error(
            "Unable to load details of Cisco Nexus VSM device associated with cluster "
                + asaCluster.getName());
        return false;
      }

      CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0);
      HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId());
      _hostDao.loadDetails(ciscoVnmcHost);
      Account owner = context.getAccount();
      PublicIp sourceNatIp = _ipAddrMgr.assignSourceNatIpAddressToGuestNetwork(owner, network);
      String vlan = network.getBroadcastUri().getHost();
      long vlanId = Long.parseLong(vlan);

      List<VlanVO> vlanVOList =
          _vlanDao.listVlansByPhysicalNetworkId(network.getPhysicalNetworkId());
      List<String> publicGateways = new ArrayList<String>();
      for (VlanVO vlanVO : vlanVOList) {
        publicGateways.add(vlanVO.getVlanGateway());
      }

      // due to VNMC limitation of not allowing source NAT ip as the outside ip of firewall,
      // an additional public ip needs to acquired for assigning as firewall outside ip.
      // In case there are already additional ip addresses available (network restart) use one
      // of them such that it is not the source NAT ip
      IpAddress outsideIp = null;
      List<IPAddressVO> publicIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
      for (IPAddressVO ip : publicIps) {
        if (!ip.isSourceNat()) {
          outsideIp = ip;
          break;
        }
      }
      if (outsideIp == null) { // none available, acquire one
        try {
          Account caller = CallContext.current().getCallingAccount();
          long callerUserId = CallContext.current().getCallingUserId();
          outsideIp = _ipAddrMgr.allocateIp(owner, false, caller, callerUserId, zone);
        } catch (ResourceAllocationException e) {
          s_logger.error("Unable to allocate additional public Ip address. Exception details " + e);
          return false;
        }

        try {
          outsideIp =
              _ipAddrMgr.associateIPToGuestNetwork(outsideIp.getId(), network.getId(), true);
        } catch (ResourceAllocationException e) {
          s_logger.error(
              "Unable to assign allocated additional public Ip "
                  + outsideIp.getAddress().addr()
                  + " to network with vlan "
                  + vlanId
                  + ". Exception details "
                  + e);
          return false;
        }
      }

      // create logical edge firewall in VNMC
      String gatewayNetmask = NetUtils.getCidrNetmask(network.getCidr());
      // due to ASA limitation of allowing single subnet to be assigned to firewall interfaces,
      // all public ip addresses must be from same subnet, this essentially means single public
      // subnet in zone
      if (!createLogicalEdgeFirewall(
          vlanId,
          network.getGateway(),
          gatewayNetmask,
          outsideIp.getAddress().addr(),
          sourceNatIp.getNetmask(),
          publicGateways,
          ciscoVnmcHost.getId())) {
        s_logger.error(
            "Failed to create logical edge firewall in Cisco VNMC device for network "
                + network.getName());
        return false;
      }

      // create stuff in VSM for ASA device
      if (!configureNexusVsmForAsa(
          vlanId,
          network.getGateway(),
          vsmDevice.getUserName(),
          vsmDevice.getPassword(),
          vsmDevice.getipaddr(),
          assignedAsa.getInPortProfile(),
          ciscoVnmcHost.getId())) {
        s_logger.error(
            "Failed to configure Cisco Nexus VSM "
                + vsmDevice.getipaddr()
                + " for ASA device for network "
                + network.getName());
        return false;
      }

      // configure source NAT
      if (!configureSourceNat(vlanId, network.getCidr(), sourceNatIp, ciscoVnmcHost.getId())) {
        s_logger.error(
            "Failed to configure source NAT in Cisco VNMC device for network " + network.getName());
        return false;
      }

      // associate Asa 1000v instance with logical edge firewall
      if (!associateAsaWithLogicalEdgeFirewall(
          vlanId, assignedAsa.getManagementIp(), ciscoVnmcHost.getId())) {
        s_logger.error(
            "Failed to associate Cisco ASA 1000v ("
                + assignedAsa.getManagementIp()
                + ") with logical edge firewall in VNMC for network "
                + network.getName());
        return false;
      }

      status = true;
      txn.commit();
    } finally {
      if (!status) {
        txn.rollback();
        // FIXME: also undo changes in VNMC, VSM if anything failed
      }
    }

    return true;
  }
  protected Map<String, Object> createSecStorageVmInstance(
      long dataCenterId, SecondaryStorageVm.Role role) {
    HostVO secHost = _hostDao.findSecondaryStorageHost(dataCenterId);
    if (secHost == null) {
      String msg =
          "No secondary storage available in zone "
              + dataCenterId
              + ", cannot create secondary storage vm";
      s_logger.warn(msg);
      throw new CloudRuntimeException(msg);
    }

    long id = _secStorageVmDao.getNextInSequence(Long.class, "id");
    String name = VirtualMachineName.getSystemVmName(id, _instance, "s").intern();
    Account systemAcct = _accountMgr.getSystemAccount();

    DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
    DataCenter dc = _dcDao.findById(plan.getDataCenterId());

    List<NetworkOfferingVO> defaultOffering =
        _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemPublicNetwork);

    if (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()) {
      defaultOffering =
          _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemGuestNetwork);
    }

    List<NetworkOfferingVO> offerings =
        _networkMgr.getSystemAccountNetworkOfferings(
            NetworkOfferingVO.SystemControlNetwork, NetworkOfferingVO.SystemManagementNetwork);
    List<Pair<NetworkVO, NicProfile>> networks =
        new ArrayList<Pair<NetworkVO, NicProfile>>(offerings.size() + 1);
    NicProfile defaultNic = new NicProfile();
    defaultNic.setDefaultNic(true);
    defaultNic.setDeviceId(2);
    try {
      networks.add(
          new Pair<NetworkVO, NicProfile>(
              _networkMgr
                  .setupNetwork(systemAcct, defaultOffering.get(0), plan, null, null, false, false)
                  .get(0),
              defaultNic));
      for (NetworkOfferingVO offering : offerings) {
        networks.add(
            new Pair<NetworkVO, NicProfile>(
                _networkMgr
                    .setupNetwork(systemAcct, offering, plan, null, null, false, false)
                    .get(0),
                null));
      }
    } catch (ConcurrentOperationException e) {
      s_logger.info("Unable to setup due to concurrent operation. " + e);
      return new HashMap<String, Object>();
    }

    VMTemplateVO template = _templateDao.findSystemVMTemplate(dataCenterId);
    if (template == null) {
      s_logger.debug("Can't find a template to start");
      throw new CloudRuntimeException("Insufficient capacity exception");
    }

    SecondaryStorageVmVO secStorageVm =
        new SecondaryStorageVmVO(
            id,
            _serviceOffering.getId(),
            name,
            template.getId(),
            template.getHypervisorType(),
            template.getGuestOSId(),
            dataCenterId,
            systemAcct.getDomainId(),
            systemAcct.getId(),
            role,
            _serviceOffering.getOfferHA());
    try {
      secStorageVm =
          _itMgr.allocate(
              secStorageVm, template, _serviceOffering, networks, plan, null, systemAcct);
    } catch (InsufficientCapacityException e) {
      s_logger.warn("InsufficientCapacity", e);
      throw new CloudRuntimeException("Insufficient capacity exception", e);
    }

    Map<String, Object> context = new HashMap<String, Object>();
    context.put("secStorageVmId", secStorageVm.getId());
    return context;
  }
  public long getNetworkId() {
    if (networkId != null) {
      return networkId;
    }
    Long zoneId = getZoneId();

    if (zoneId == null) {
      Long ipId = getSourceIpAddressId();
      if (ipId == null) {
        throw new InvalidParameterValueException(
            "Either networkId or zoneId or publicIpId has to be specified");
      }
    }

    if (zoneId != null) {
      DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
      if (zone.getNetworkType() == NetworkType.Advanced) {
        List<? extends Network> networks =
            _networkService.getIsolatedNetworksOwnedByAccountInZone(
                getZoneId(), _accountService.getAccount(getEntityOwnerId()));
        if (networks.size() == 0) {
          String domain = _domainService.getDomain(getDomainId()).getName();
          throw new InvalidParameterValueException(
              "Account name="
                  + getAccountName()
                  + " domain="
                  + domain
                  + " doesn't have virtual networks in zone="
                  + zone.getName());
        }

        if (networks.size() < 1) {
          throw new InvalidParameterValueException(
              "Account doesn't have any Isolated networks in the zone");
        } else if (networks.size() > 1) {
          throw new InvalidParameterValueException(
              "Account has more than one Isolated network in the zone");
        }

        return networks.get(0).getId();
      } else {
        Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId);
        if (defaultGuestNetwork == null) {
          throw new InvalidParameterValueException(
              "Unable to find a default Guest network for account "
                  + getAccountName()
                  + " in domain id="
                  + getDomainId());
        } else {
          return defaultGuestNetwork.getId();
        }
      }
    } else {
      IpAddress ipAddr = _networkService.getIp(publicIpId);
      if (ipAddr.getAssociatedWithNetworkId() != null) {
        return ipAddr.getAssociatedWithNetworkId();
      } else {
        throw new InvalidParameterValueException(
            "Ip address id=" + publicIpId + " is not associated with any network");
      }
    }
  }
  @Override
  public boolean finalizeVirtualMachineProfile(
      VirtualMachineProfile<DomainRouterVO> profile,
      DeployDestination dest,
      ReservationContext context) {
    DomainRouterVO elbVm = profile.getVirtualMachine();

    List<NicProfile> elbNics = profile.getNics();
    Long guestNtwkId = null;
    for (NicProfile routerNic : elbNics) {
      if (routerNic.getTrafficType() == TrafficType.Guest) {
        guestNtwkId = routerNic.getNetworkId();
        break;
      }
    }

    NetworkVO guestNetwork = _networkDao.findById(guestNtwkId);

    DataCenter dc = dest.getDataCenter();

    StringBuilder buf = profile.getBootArgsBuilder();
    buf.append(" template=domP type=" + _systemVmType);
    buf.append(" name=").append(profile.getHostName());
    NicProfile controlNic = null;
    String defaultDns1 = null;
    String defaultDns2 = null;

    for (NicProfile nic : profile.getNics()) {
      int deviceId = nic.getDeviceId();
      buf.append(" eth").append(deviceId).append("ip=").append(nic.getIp4Address());
      buf.append(" eth").append(deviceId).append("mask=").append(nic.getNetmask());
      if (nic.isDefaultNic()) {
        buf.append(" gateway=").append(nic.getGateway());
        defaultDns1 = nic.getDns1();
        defaultDns2 = nic.getDns2();
      }
      if (nic.getTrafficType() == TrafficType.Management) {
        buf.append(" localgw=").append(dest.getPod().getGateway());
      } else if (nic.getTrafficType() == TrafficType.Control) {
        //  control command is sent over management network in VMware
        if (dest.getHost().getHypervisorType() == HypervisorType.VMware) {
          if (s_logger.isInfoEnabled()) {
            s_logger.info(
                "Check if we need to add management server explicit route to ELB vm. pod cidr: "
                    + dest.getPod().getCidrAddress()
                    + "/"
                    + dest.getPod().getCidrSize()
                    + ", pod gateway: "
                    + dest.getPod().getGateway()
                    + ", management host: "
                    + _mgmtHost);
          }

          if (s_logger.isDebugEnabled()) {
            s_logger.debug("Added management server explicit route to ELB vm.");
          }
          // always add management explicit route, for basic networking setup
          buf.append(" mgmtcidr=").append(_mgmtCidr);
          buf.append(" localgw=").append(dest.getPod().getGateway());

          if (dc.getNetworkType() == NetworkType.Basic) {
            // ask elb vm to setup SSH on guest network
            buf.append(" sshonguest=true");
          }
        }

        controlNic = nic;
      }
    }
    String domain = guestNetwork.getNetworkDomain();
    if (domain != null) {
      buf.append(" domain=" + domain);
    }

    buf.append(" dns1=").append(defaultDns1);
    if (defaultDns2 != null) {
      buf.append(" dns2=").append(defaultDns2);
    }

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

    if (controlNic == null) {
      throw new CloudRuntimeException("Didn't start a control port");
    }

    return true;
  }
Beispiel #16
0
  @Override
  public void create() throws ResourceAllocationException {
    try {
      // Verify that all objects exist before passing them to the service
      Account owner = _accountService.getActiveAccountById(getEntityOwnerId());

      DataCenter zone = _configService.getZone(zoneId);
      if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId);
      }

      ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId);
      if (serviceOffering == null) {
        throw new InvalidParameterValueException(
            "Unable to find service offering: " + serviceOfferingId);
      }

      VirtualMachineTemplate template = _templateService.getTemplate(templateId);
      // Make sure a valid template ID was specified
      if (template == null) {
        throw new InvalidParameterValueException("Unable to use template " + templateId);
      }

      if (diskOfferingId != null) {
        DiskOffering diskOffering = _configService.getDiskOffering(diskOfferingId);
        if (diskOffering == null) {
          throw new InvalidParameterValueException(
              "Unable to find disk offering " + diskOfferingId);
        }
      }

      UserVm vm = null;
      if (getHypervisor() == HypervisorType.BareMetal) {
        vm = _bareMetalVmService.createVirtualMachine(this);
      } else {
        if (zone.getNetworkType() == NetworkType.Basic) {
          if (getNetworkIds() != null) {
            throw new InvalidParameterValueException("Can't specify network Ids in Basic zone");
          } else {
            vm =
                _userVmService.createBasicSecurityGroupVirtualMachine(
                    zone,
                    serviceOffering,
                    template,
                    getSecurityGroupIdList(),
                    owner,
                    name,
                    displayName,
                    diskOfferingId,
                    size,
                    group,
                    getHypervisor(),
                    userData,
                    sshKeyPairName,
                    getIpToNetworkMap(),
                    ipAddress,
                    keyboard);
          }
        } else {
          if (zone.isSecurityGroupEnabled()) {
            vm =
                _userVmService.createAdvancedSecurityGroupVirtualMachine(
                    zone,
                    serviceOffering,
                    template,
                    getNetworkIds(),
                    getSecurityGroupIdList(),
                    owner,
                    name,
                    displayName,
                    diskOfferingId,
                    size,
                    group,
                    getHypervisor(),
                    userData,
                    sshKeyPairName,
                    getIpToNetworkMap(),
                    ipAddress,
                    keyboard);
          } else {
            if (getSecurityGroupIdList() != null && !getSecurityGroupIdList().isEmpty()) {
              throw new InvalidParameterValueException(
                  "Can't create vm with security groups; security group feature is not enabled per zone");
            }
            vm =
                _userVmService.createAdvancedVirtualMachine(
                    zone,
                    serviceOffering,
                    template,
                    getNetworkIds(),
                    owner,
                    name,
                    displayName,
                    diskOfferingId,
                    size,
                    group,
                    getHypervisor(),
                    userData,
                    sshKeyPairName,
                    getIpToNetworkMap(),
                    ipAddress,
                    keyboard);
          }
        }
      }

      if (vm != null) {
        setEntityId(vm.getId());
      } else {
        throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm");
      }
    } catch (InsufficientCapacityException ex) {
      s_logger.info(ex);
      s_logger.trace(ex);
      throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
    } catch (ResourceUnavailableException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException ex) {
      s_logger.warn("Exception: ", ex);
      throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
    }
  }
  @Override
  public Network implement(
      Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context)
      throws InsufficientVirtualNetworkCapcityException {
    assert (config.getState() == State.Implementing) : "Why are we implementing " + config;

    if (Boolean.parseBoolean(_configDao.getValue(Config.OvsTunnelNetwork.key()))) {
      return null;
    }

    if (!_networkModel.networkIsConfiguredForExternalNetworking(
        config.getDataCenterId(), config.getId())) {
      return super.implement(config, offering, dest, context);
    }

    DataCenter zone = dest.getDataCenter();
    NetworkVO implemented =
        new NetworkVO(
            config.getTrafficType(),
            config.getMode(),
            config.getBroadcastDomainType(),
            config.getNetworkOfferingId(),
            State.Allocated,
            config.getDataCenterId(),
            config.getPhysicalNetworkId());

    // Get a vlan tag
    int vlanTag;
    if (config.getBroadcastUri() == null) {
      String vnet =
          _dcDao.allocateVnet(
              zone.getId(),
              config.getPhysicalNetworkId(),
              config.getAccountId(),
              context.getReservationId());

      try {
        vlanTag = Integer.parseInt(vnet);
      } catch (NumberFormatException e) {
        throw new CloudRuntimeException(
            "Obtained an invalid guest vlan tag. Exception: " + e.getMessage());
      }

      implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag));
      ActionEventUtils.onCompletedActionEvent(
          UserContext.current().getCallerUserId(),
          config.getAccountId(),
          EventVO.LEVEL_INFO,
          EventTypes.EVENT_ZONE_VLAN_ASSIGN,
          "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(),
          0);
    } else {
      vlanTag = Integer.parseInt(config.getBroadcastUri().getHost());
      implemented.setBroadcastUri(config.getBroadcastUri());
    }

    // Determine the new gateway and CIDR
    String[] oldCidr = config.getCidr().split("/");
    String oldCidrAddress = oldCidr[0];
    int cidrSize = Integer.parseInt(oldCidr[1]);
    long newCidrAddress = (NetUtils.ip2Long(oldCidrAddress));
    // if the implementing network is for vpc, no need to generate newcidr, use the cidr that came
    // from super cidr
    if (config.getVpcId() != null) {
      implemented.setGateway(config.getGateway());
      implemented.setCidr(config.getCidr());
      implemented.setState(State.Implemented);
    } else {
      // Determine the offset from the lowest vlan tag
      int offset = getVlanOffset(config.getPhysicalNetworkId(), vlanTag);
      cidrSize = getGloballyConfiguredCidrSize();
      // If the offset has more bits than there is room for, return null
      long bitsInOffset = 32 - Integer.numberOfLeadingZeros(offset);
      if (bitsInOffset > (cidrSize - 8)) {
        throw new CloudRuntimeException(
            "The offset "
                + offset
                + " needs "
                + bitsInOffset
                + " bits, but only have "
                + (cidrSize - 8)
                + " bits to work with.");
      }
      newCidrAddress =
          (NetUtils.ip2Long(oldCidrAddress) & 0xff000000) | (offset << (32 - cidrSize));
      implemented.setGateway(NetUtils.long2Ip(newCidrAddress + 1));
      implemented.setCidr(NetUtils.long2Ip(newCidrAddress) + "/" + cidrSize);
      implemented.setState(State.Implemented);
    }

    // Mask the Ipv4 address of all nics that use this network with the new guest VLAN offset
    List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(config.getId());
    for (NicVO nic : nicsInNetwork) {
      if (nic.getIp4Address() != null) {
        long ipMask = getIpMask(nic.getIp4Address(), cidrSize);
        nic.setIp4Address(NetUtils.long2Ip(newCidrAddress | ipMask));
        _nicDao.persist(nic);
      }
    }

    // Mask the destination address of all port forwarding rules in this network with the new guest
    // VLAN offset
    List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId());
    for (PortForwardingRuleVO pfRule : pfRulesInNetwork) {
      if (pfRule.getDestinationIpAddress() != null) {
        long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize);
        String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask);
        pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress));
        _pfRulesDao.update(pfRule.getId(), pfRule);
      }
    }

    return implemented;
  }
 public boolean shouldAvoid(DataCenter dc) {
   if (_dcIds != null && _dcIds.contains(dc.getId())) {
     return true;
   }
   return false;
 }
 @Override
 public void updateNetworkProfile(NetworkProfile networkProfile) {
   DataCenter dc = _dcDao.findById(networkProfile.getDataCenterId());
   networkProfile.setDns1(dc.getDns1());
   networkProfile.setDns2(dc.getDns2());
 }