@Override
 protected void allocateVnet(
     Network network,
     NetworkVO implemented,
     long dcId,
     long physicalNetworkId,
     String reservationId)
     throws InsufficientVirtualNetworkCapcityException {
   if (network.getBroadcastUri() == null) {
     String vnet =
         _dcDao.allocateVnet(
             dcId,
             physicalNetworkId,
             network.getAccountId(),
             reservationId,
             UseSystemGuestVlans.valueIn(network.getAccountId()));
     if (vnet == null) {
       throw new InsufficientVirtualNetworkCapcityException(
           "Unable to allocate vnet as a part of network " + network + " implement ",
           DataCenter.class,
           dcId);
     }
     implemented.setBroadcastUri(BroadcastDomainType.Vswitch.toUri(vnet));
     ActionEventUtils.onCompletedActionEvent(
         CallContext.current().getCallingUserId(),
         network.getAccountId(),
         EventVO.LEVEL_INFO,
         EventTypes.EVENT_ZONE_VLAN_ASSIGN,
         "Assigned Zone Vlan: " + vnet + " Network Id: " + network.getId(),
         0);
   } else {
     implemented.setBroadcastUri(network.getBroadcastUri());
   }
 }
 public NetworkProfile(Network network) {
   this.id = network.getId();
   this.uuid = network.getUuid();
   this.broadcastUri = network.getBroadcastUri();
   this.dataCenterId = network.getDataCenterId();
   this.ownerId = network.getAccountId();
   this.state = network.getState();
   this.name = network.getName();
   this.mode = network.getMode();
   this.broadcastDomainType = network.getBroadcastDomainType();
   this.trafficType = network.getTrafficType();
   this.gateway = network.getGateway();
   this.cidr = network.getCidr();
   this.networkOfferingId = network.getNetworkOfferingId();
   this.related = network.getRelated();
   this.displayText = network.getDisplayText();
   this.reservationId = network.getReservationId();
   this.networkDomain = network.getNetworkDomain();
   this.domainId = network.getDomainId();
   this.guestType = network.getGuestType();
   this.physicalNetworkId = network.getPhysicalNetworkId();
   this.aclType = network.getAclType();
   this.restartRequired = network.isRestartRequired();
   this.specifyIpRanges = network.getSpecifyIpRanges();
   this.vpcId = network.getVpcId();
 }
  @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;
  }
  @DB
  protected FirewallRule createFirewallRule(
      Long ipAddrId,
      Account caller,
      String xId,
      Integer portStart,
      Integer portEnd,
      String protocol,
      List<String> sourceCidrList,
      Integer icmpCode,
      Integer icmpType,
      Long relatedRuleId,
      FirewallRule.FirewallRuleType type,
      Long networkId,
      FirewallRule.TrafficType trafficType)
      throws NetworkRuleConflictException {

    IPAddressVO ipAddress = null;
    if (ipAddrId != null) {
      // this for ingress firewall rule, for egress id is null
      ipAddress = _ipAddressDao.findById(ipAddrId);
      // Validate ip address
      if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
        throw new InvalidParameterValueException(
            "Unable to create firewall rule; " + "couldn't locate IP address by id in the system");
      }
      _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
    }

    validateFirewallRule(
        caller,
        ipAddress,
        portStart,
        portEnd,
        protocol,
        Purpose.Firewall,
        type,
        networkId,
        trafficType);

    // icmp code and icmp type can't be passed in for any other protocol rather than icmp
    if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
      throw new InvalidParameterValueException(
          "Can specify icmpCode and icmpType for ICMP protocol only");
    }

    if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (portStart != null || portEnd != null)) {
      throw new InvalidParameterValueException(
          "Can't specify start/end port when protocol is ICMP");
    }

    Long accountId = null;
    Long domainId = null;

    if (ipAddress != null) {
      // Ingress firewall rule
      accountId = ipAddress.getAllocatedToAccountId();
      domainId = ipAddress.getAllocatedInDomainId();
    } else if (networkId != null) {
      // egress firewall rule
      Network network = _networkModel.getNetwork(networkId);
      accountId = network.getAccountId();
      domainId = network.getDomainId();
    }

    Transaction txn = Transaction.currentTxn();
    txn.start();

    FirewallRuleVO newRule =
        new FirewallRuleVO(
            xId,
            ipAddrId,
            portStart,
            portEnd,
            protocol.toLowerCase(),
            networkId,
            accountId,
            domainId,
            Purpose.Firewall,
            sourceCidrList,
            icmpCode,
            icmpType,
            relatedRuleId,
            trafficType);
    newRule.setType(type);
    newRule = _firewallDao.persist(newRule);

    if (type == FirewallRuleType.User) detectRulesConflict(newRule);

    if (!_firewallDao.setStateToAdd(newRule)) {
      throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
    }
    CallContext.current().setEventDetails("Rule Id: " + newRule.getId());

    txn.commit();

    return newRule;
  }