Add VPS to a private Network

@param string $vpsName The name of the VPS
@param string $privateNetworkName The name of the privateNetwork to add to
422951
public function addVpsToPrivateNetwork($vpsName, $privateNetworkName)
    {
        return $this->getSoapClient(array_merge(array($vpsName, $privateNetworkName), array('__method' => 'addVpsToPrivateNetwork')))->addVpsToPrivateNetwork($vpsName, $privateNetworkName);
    }
260424
public function cancelAddon($vpsName, $addonName)
    {
        return $this->getSoapClient(array_merge(array($vpsName, $addonName), array('__method' => 'cancelAddon')))->cancelAddon($vpsName, $addonName);
    }
291081
public void setServerName(String serverName) {
    if (serverName == null || serverName.equals("")) {
      this.serverName = "localhost";
    } else {
      this.serverName = serverName;
    }
  }
1191783
@Override
	public VpnGateway createVpnGateway(String endpoint, String name,String description, VpnProtocol protocol, String bgpAsn)throws CloudException, InternalException {
        if( logger.isTraceEnabled() ) {
            logger.trace("ENTER: " + AzureVPNSupport.class.getName() + ".createVPNGateway()");
        }
        try {
            ProviderContext ctx = provider.getContext();

            if( ctx == null ) {
                throw new AzureConfigException("No context was specified for this request");
            }
           
            
            AzureMethod method = new AzureMethod(provider);
            StringBuilder xml = new StringBuilder();
            xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            xml.append("<NetworkConfiguration  xmlns=\"http://schemas.microsoft.com/windowsazure\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">");
            xml.append("<VirtualNetworkConfiguration>");            
            xml.append("<LocalNetworkSites>");
            
            xml.append("<LocalNetworkSite name=\"" + name +  "\">");
            xml.append("<AddressSpace>");
            xml.append("<AddressPrefix>"+ endpoint +"/32" + "</AddressPrefix>");
            xml.append("</AddressSpace>");
            xml.append("<VPNGatewayAddress>"+ endpoint + "</VPNGatewayAddress>");
            xml.append("</LocalNetworkSite>");
            
            xml.append("</LocalNetworkSites>");
            xml.append("</VirtualNetworkConfiguration>");
            xml.append("</NetworkConfiguration>");
               

            if( logger.isDebugEnabled() ) {
                try {
                    method.parseResponse(xml.toString(), false);
                }
                catch( Exception e ) {
                    logger.warn("Unable to parse outgoing XML locally: " + e.getMessage());
                    logger.warn("XML:");
                    logger.warn(xml.toString());
                }
            }

            String resourceDir = NETWORKING_SERVICES + "/media";
            method.post(ctx.getAccountNumber(),resourceDir , xml.toString());
            // TODO: VPNGateway
            return null;
        }
        finally {
            if( logger.isTraceEnabled() ) {
                logger.trace("EXIT: " + AzureVPNSupport.class.getName() + ".createVPNGateway()");
            }
        }
		
	}
1201661
public void serviceName_network_ipNet_PUT(String serviceName, String ipNet, OvhNetwork body) throws IOException {
		String qPath = "/router/{serviceName}/network/{ipNet}";
		StringBuilder sb = path(qPath, serviceName, ipNet);
		exec(qPath, "PUT", sb.toString(), body);
	}
1326783
public function addSnippet($sSnptName)
    {
        $oSnpt                      = ViewFactory::createSnippet($sSnptName);
        $this->snippets[$sSnptName] = $oSnpt;
    }
301420
@Override
    public Server addServer(String serverName, String hostAddress, int port, IpChannelType ipChannelType,
            boolean acceptAnonymousConnections, int maxConcurrentConnectionsCount, String[] extraHostAddresses)
            throws Exception {
        if (!this.started) {
            throw new Exception(String.format("Management=%s not started", this.name));
        }

        if (serverName == null) {
            throw new Exception("Server name cannot be null");
        }

        if (hostAddress == null) {
            throw new Exception("Server host address cannot be null");
        }

        if (port < 1) {
            throw new Exception("Server host port cannot be less than 1");
        }

        synchronized (this) {
            for (FastList.Node<Server> n = this.servers.head(), end = this.servers.tail(); (n = n.getNext()) != end;) {
                Server serverTemp = n.getValue();
                if (serverName.equals(serverTemp.getName())) {
                    throw new Exception(String.format("Server name=%s already exist", serverName));
                }

                if (hostAddress.equals(serverTemp.getHostAddress()) && port == serverTemp.getHostport()) {
                    throw new Exception(String.format("Server name=%s is already bound to %s:%d", serverTemp.getName(),
                            serverTemp.getHostAddress(), serverTemp.getHostport()));
                }
            }

            NettyServerImpl server = new NettyServerImpl(serverName, hostAddress, port, ipChannelType,
                    acceptAnonymousConnections, maxConcurrentConnectionsCount, extraHostAddresses);
            server.setManagement(this);

            FastList<Server> newServers = new FastList<Server>();
            newServers.addAll(this.servers);
            newServers.add(server);
            this.servers = newServers;
            // this.servers.add(server);

            this.store();

            for (ManagementEventListener lstr : managementEventListeners) {
                try {
                    lstr.onServerAdded(server);
                } catch (Throwable ee) {
                    logger.error("Exception while invoking onServerAdded", ee);
                }
            }

            if (logger.isInfoEnabled()) {
                logger.info(String.format("Created Server=%s", server.getName()));
            }

            return server;
        }
    }
226037
public function addPrivateKey(PrivateKeyInterface $privateKey)
    {
        $pubKeyHex = $privateKey->getPublicKey()->getHex();
        $this->privateKeys[$pubKeyHex] = $privateKey;
    }
975186
public static function addName(string $name, string $poolClassName, \Imi\Pool\Interfaces\IPoolConfig $config = null, $resourceConfig = null)
    {
        static::$pools[$name] = BeanFactory::newInstance($poolClassName, $name, $config, $resourceConfig);
        static::$pools[$name]->open();
    }
283139
public static base_response add(nitro_service client, ipsecprofile resource) throws Exception {
		ipsecprofile addresource = new ipsecprofile();
		addresource.name = resource.name;
		addresource.ikeversion = resource.ikeversion;
		addresource.encalgo = resource.encalgo;
		addresource.hashalgo = resource.hashalgo;
		addresource.lifetime = resource.lifetime;
		addresource.psk = resource.psk;
		addresource.publickey = resource.publickey;
		addresource.privatekey = resource.privatekey;
		addresource.peerpublickey = resource.peerpublickey;
		addresource.livenesscheckinterval = resource.livenesscheckinterval;
		addresource.replaywindowsize = resource.replaywindowsize;
		addresource.ikeretryinterval = resource.ikeretryinterval;
		addresource.retransmissiontime = resource.retransmissiontime;
		return addresource.add_resource(client);
	}
568210
def network_setup():
  """"""

  # from https://gist.github.com/nguyendv/8cfd92fc8ed32ebb78e366f44c2daea6

  ec2 = u.get_ec2_resource()
  client = u.get_ec2_client()
  existing_vpcs = u.get_vpc_dict()
  zones = u.get_zones()

  # create VPC from scratch. Remove this if default VPC works well enough.
  vpc_name = u.get_vpc_name()
  if u.get_vpc_name() in existing_vpcs:
    print("Reusing VPC " + vpc_name)
    vpc = existing_vpcs[vpc_name]
    subnets = list(vpc.subnets.all())
    assert len(subnets) == len(
      zones), "Has %s subnets, but %s zones, something went wrong during resource creation, try delete_resources.py/create_resources.py" % (
      len(subnets), len(zones))

  else:
    print("Creating VPC " + vpc_name)
    vpc = ec2.create_vpc(CidrBlock='192.168.0.0/16')

    # enable DNS on the VPC
    response = vpc.modify_attribute(EnableDnsHostnames={"Value": True})
    assert u.is_good_response(response)
    response = vpc.modify_attribute(EnableDnsSupport={"Value": True})
    assert u.is_good_response(response)

    vpc.create_tags(Tags=u.create_name_tags(vpc_name))
    vpc.wait_until_available()

  gateways = u.get_gateway_dict(vpc)
  gateway_name = u.get_gateway_name()
  if gateway_name in gateways:
    print("Reusing gateways " + gateway_name)
  else:
    print("Creating internet gateway " + gateway_name)
    ig = ec2.create_internet_gateway()
    ig.attach_to_vpc(VpcId=vpc.id)
    ig.create_tags(Tags=u.create_name_tags(gateway_name))

    # check that attachment succeeded
    attach_state = u.extract_attr_for_match(ig.attachments, State=-1,
                                            VpcId=vpc.id)
    assert attach_state == 'available', "vpc %s is in state %s" % (vpc.id,
                                                                   attach_state)

    route_table = vpc.create_route_table()
    route_table_name = u.get_route_table_name()
    route_table.create_tags(Tags=u.create_name_tags(route_table_name))

    dest_cidr = '0.0.0.0/0'
    route_table.create_route(
      DestinationCidrBlock=dest_cidr,
      GatewayId=ig.id
    )
    # check success
    for route in route_table.routes:
      # result looks like this
      # ec2.Route(route_table_id='rtb-a8b438cf',
      #    destination_cidr_block='0.0.0.0/0')
      if route.destination_cidr_block == dest_cidr:
        break
    else:
      # sometimes get
      #      AssertionError: Route for 0.0.0.0/0 not found in [ec2.Route(route_table_id='rtb-cd9153b0', destination_cidr_block='192.168.0.0/16')]
      # TODO: add a wait/retry?
      assert False, "Route for %s not found in %s" % (dest_cidr,
                                                      route_table.routes)

    assert len(zones) <= 16  # for cidr/20 to fit into cidr/16
    ip = 0
    for zone in zones:
      cidr_block = '192.168.%d.0/20' % (ip,)
      ip += 16
      print("Creating subnet %s in zone %s" % (cidr_block, zone))
      subnet = vpc.create_subnet(CidrBlock=cidr_block,
                                 AvailabilityZone=zone)
      subnet.create_tags(Tags=[{'Key': 'Name', 'Value': f'{vpc_name}-subnet'},
                               {'Key': 'Region', 'Value': zone}])
      response = client.modify_subnet_attribute(
        MapPublicIpOnLaunch={'Value': True},
        SubnetId=subnet.id
      )
      assert u.is_good_response(response)
      u.wait_until_available(subnet)
      assert subnet.map_public_ip_on_launch, "Subnet doesn't enable public IP by default, why?"

      route_table.associate_with_subnet(SubnetId=subnet.id)

  # Use default VPC from now on
  vpc = u.get_default_vpc()
  if not vpc:
    util.log(f"Creating default VPC for region {u.get_region()}")
    client.create_default_vpc()
  vpc = u.get_default_vpc()
  assert vpc, "Could not create default VPC?"

  existing_security_groups = u.get_security_group_dict()
  security_group_name = u.get_security_group_name()
  if security_group_name in existing_security_groups:
    print("Reusing security group " + security_group_name)
    security_group = existing_security_groups[security_group_name]
    assert security_group.vpc_id == vpc.id, f"Found security group {security_group} " \
                                            f"attached to {security_group.vpc_id} but expected {vpc.id}"
  else:
    print("Creating security group " + security_group_name)
    security_group = ec2.create_security_group(
      GroupName=security_group_name, Description=security_group_name,
      VpcId=vpc.id)

    security_group.create_tags(Tags=u.create_name_tags(security_group_name))

    # allow ICMP access for public ping
    security_group.authorize_ingress(
      CidrIp='0.0.0.0/0',
      IpProtocol='icmp',
      FromPort=-1,
      ToPort=-1
    )

    # open public ports
    # always include SSH port which is required for basic functionality
    assert 22 in PUBLIC_TCP_RANGES, "Must enable SSH access"
    for port in PUBLIC_TCP_RANGES:
      if util.is_iterable(port):
        assert len(port) == 2
        from_port, to_port = port
      else:
        from_port, to_port = port, port

      response = security_group.authorize_ingress(IpProtocol="tcp",
                                                  CidrIp="0.0.0.0/0",
                                                  FromPort=from_port,
                                                  ToPort=to_port)
      assert u.is_good_response(response)

    for port in PUBLIC_UDP_RANGES:
      if util.is_iterable(port):
        assert len(port) == 2
        from_port, to_port = port
      else:
        from_port, to_port = port, port

      response = security_group.authorize_ingress(IpProtocol="udp",
                                                  CidrIp="0.0.0.0/0",
                                                  FromPort=from_port,
                                                  ToPort=to_port)
      assert u.is_good_response(response)

    # allow ingress within security group
    # Authorizing ingress doesn't work with names in a non-default VPC,
    # so must use more complicated syntax
    # https://github.com/boto/boto3/issues/158
    response = {}
    for protocol in ['icmp']:
      try:
        rule = {'FromPort': -1,
                'IpProtocol': protocol,
                'IpRanges': [],
                'PrefixListIds': [],
                'ToPort': -1,
                'UserIdGroupPairs': [{'GroupId': security_group.id}]}
        response = security_group.authorize_ingress(IpPermissions=[rule])
      except Exception as e:
        if response['Error']['Code'] == 'InvalidPermission.Duplicate':
          print("Warning, got " + str(e))
        else:
          assert False, "Failed while authorizing ingress with " + str(e)

    for protocol in ['tcp', 'udp']:
      try:
        rule = {'FromPort': 0,
                'IpProtocol': protocol,
                'IpRanges': [],
                'PrefixListIds': [],
                'ToPort': 65535,
                'UserIdGroupPairs': [{'GroupId': security_group.id}]}
        response = security_group.authorize_ingress(IpPermissions=[rule])
      except Exception as e:
        if response['Error']['Code'] == 'InvalidPermission.Duplicate':
          print("Warning, got " + str(e))
        else:
          assert False, "Failed while authorizing ingress with " + str(e)

  return vpc, security_group
449476
public function orderAddon($vpsName, $addons)
    {
        return $this->getSoapClient(array_merge(array($vpsName, $addons), array('__method' => 'orderAddon')))->orderAddon($vpsName, $addons);
    }
136193
public static base_response add(nitro_service client, vpnclientlessaccessprofile resource) throws Exception {
		vpnclientlessaccessprofile addresource = new vpnclientlessaccessprofile();
		addresource.profilename = resource.profilename;
		return addresource.add_resource(client);
	}
58767
public function addConnection($name, $dsn)
    {
        if(isset($this->_connections[$name]))
            throw new \Pheasant\Exception("Connection $name already exists");

        $this->_connections[$name] = $dsn;

        return $this;
    }
1327549
public function CreateChannel($channelName , $private = null){
        $private = $private == null ? "" : "&private=true";
        $fullUrlApi = $this->url.'apps/'.$this->appKey.'/channels/'.$channelName.'?app_secret='.$this->token.$private;
        try{
            return $this->PostData($fullUrlApi , '' , 'POST');
        }catch(Exception $ex){
            exit();
        }
    }
779481
public function addSMIME(string $certificate, string $privateKey): void
    {
        $signer = new SMIMESigner();
        $signer->certificate = $certificate;
        $signer->privateKey = $privateKey;
        $this->set($signer);
    }
11167
public function privateKeyToDer($privateKey, $privateKyePassword = '')
    {
        try {
            if (strlen($privateKyePassword) === 0) {
                return CryptoVirgilKeyPair::privateKeyToDER($privateKey);
            }

            return CryptoVirgilKeyPair::privateKeyToDER(
                $this->encryptPrivateKey($privateKey, $privateKyePassword),
                $privateKyePassword
            );
        } catch (Exception $exception) {
            throw new PrivateKeyToDerConvertingException($exception->getMessage(), $exception->getCode());
        }
    }