Beispiel #1
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Microsoft.Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (IpBlock != null)
     {
         IpBlock.Validate();
     }
 }
 public void IPCreate()
 {
     Configure();
     ipBlock = new IpBlock { Properties = new IpBlockProperties { Location = "us/lasdev", Size = 1 } };
     ipBlock = ipApi.Create(ipBlock);
     DoWait(ipBlock.Request);
     Assert.IsNotNull(ipBlock);
 }
Beispiel #3
0
        /// <summary>
        /// Parses a comma delimited list of IPv4 addresses in CIDR notation and stores them
        /// in the IpBlocks db table. Each IpBlock is then enumerated and all of the possible
        /// IP addresses in the range are stored in the IpAddresses db table.
        /// </summary>
        /// <param name="ipBlocks">A comma delimited list of IPv4 addresses in CIDR notation.</param>
        /// <param name="ipConfigId">The Id of the IpConfig that these IpBlocks belong to.</param>
        /// <returns></returns>
        private async Task ProcessIpBlocks(List <string> ipBlocks, long ipConfigId)
        {
            HashSet <string> blocks = new HashSet <string>();

            for (int i = 0; i < ipBlocks.Count; i++)
            {
                // Remove whitespace from string
                ipBlocks.ElementAt(i).Replace(ipBlocks.ElementAt(i), Regex.Replace(ipBlocks.ElementAt(i), @"\s+", ""));

                // Check for duplicate IpBlocks
                if (!blocks.Add(ipBlocks.ElementAt(i)))
                {
                    // TODO - One of the IpBlocks is a duplicate
                    throw new NotSupportedException();
                }
            }

            // For each Ipv4 address in CIDR notation, enumerate all the IPs in the range then add them to ipAddresses
            foreach (string cidr in ipBlocks)
            {
                IpBlock ipBlock = new IpBlock
                {
                    CIDR       = cidr,
                    IpConfigId = ipConfigId
                };

                // Store each CIDR IPv4 address in the IpBlocks db table
                _context.IpBlocks.Add(ipBlock);
                await _context._SaveChangesAsync();

                IPNetwork block = IPNetwork.Parse(cidr);

                // Adjust the prefix relative to the IPsPerSub
                byte prefix = (byte)(32 - Math.Log((await _context.IpConfigs.FindAsync(ipConfigId)).IPsPerSub, 2));

                // Break the IpBlock into smaller subnets in CIDR IPv4 notation
                IPNetworkCollection subnets = block.Subnet(prefix);

                // This list will contain all of the enumerated IP address entities for the ipBlock
                List <IpAddress> ipAddressEntities = new List <IpAddress>();

                foreach (IPNetwork network in subnets)
                {
                    IpAddress ip = new IpAddress
                    {
                        Value       = network.Value,
                        IsAvailable = true,
                        IpBlockId   = ipBlock.Id
                    };

                    ipAddressEntities.Add(ip);
                }

                // Store all of the enumerated IP address entities in the IpAddresses db table
                _context.IpAddresses.AddRange(ipAddressEntities);
                await _context._SaveChangesAsync();
            }
        }
 public void IPCreate()
 {
     Configure();
     ipBlock = new IpBlock {
         Properties = new IpBlockProperties {
             Location = "us/lasdev", Size = 1
         }
     };
     ipBlock = ipApi.Create(ipBlock);
     DoWait(ipBlock.Request);
     Assert.IsNotNull(ipBlock);
 }
        private RedBlackTree <AsnWrapper> LoadAsnTree()
        {
            var asnBlocks = _storageService.ReadAsnBlocks();
            var tree      = new RedBlackTree <AsnWrapper>();

            foreach (var asnBlock in asnBlocks)
            {
                var ipBlock = new IpBlock(asnBlock.Network);
                tree.Put(ipBlock.FirstIp, new AsnWrapper
                {
                    FirstIp  = ipBlock.FirstIp,
                    LastIp   = ipBlock.LastIp,
                    AsnBlock = asnBlock
                });
            }
            return(tree);
        }
        private RedBlackTree <CityWrapper> LoadCityTree()
        {
            var cityBlocks = _storageService.ReadCityBlocks();
            var tree       = new RedBlackTree <CityWrapper>();

            foreach (var cityBlock in cityBlocks)
            {
                var ipBlock = new IpBlock(cityBlock.Network);
                tree.Put(ipBlock.FirstIp, new CityWrapper
                {
                    FirstIp   = ipBlock.FirstIp,
                    LastIp    = ipBlock.LastIp,
                    CityBlock = cityBlock
                });
            }
            return(tree);
        }
        /// <summary>
        /// Reserve IP Block This will reserve a new IP Block
        /// </summary>
        /// <param name="ipblock">IP Block to be reserved</param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of ApiResponse (IpBlock)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<IpBlock>> CreateAsyncWithHttpInfo(IpBlock ipblock, bool? parameter = null, int? depth = null)
        {
            // verify the required parameter 'ipblock' is set
            if (ipblock == null) throw new ApiException(400, "Missing required parameter 'ipblock' when calling Create");


            var path_ = "/ipblocks";

            var pathParams = new Dictionary<String, String>();
            var queryParams = new Dictionary<String, String>();
            var headerParams = new Dictionary<String, String>();
            var formParams = new Dictionary<String, String>();
            var fileParams = new Dictionary<String, FileParameter>();
            Object postBody = null;

            // to determine the Content-Type header
            String[] httpContentTypes = new String[] {
                "application/json", "application/vnd.profitbricks.resource+json"
            };
            String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);

            // to determine the Accept header
            String[] httpHeaderAccepts = new String[] {
                "application/vnd.profitbricks.resource+json"
            };
            String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
            if (httpHeaderAccept != null)
                headerParams.Add("Accept", httpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            pathParams.Add("format", "json");

            if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
            if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter



            postBody = Configuration.ApiClient.Serialize(ipblock); // http body (model) parameter



            // authentication (basicAuth) required

            // http basic authentication required
            if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
            {
                headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
            }


            // make the HTTP request
            IRestResponse response = (IRestResponse)await Configuration.ApiClient.CallApiAsync(path_,
                Method.POST, queryParams, postBody, headerParams, formParams, fileParams,
                pathParams, httpContentType);

            int statusCode = (int)response.StatusCode;

            if (statusCode >= 400)
                throw new ApiException(statusCode, "Error calling Create: " + response.Content, response.Content);
            else if (statusCode == 0)
                throw new ApiException(statusCode, "Error calling Create: " + response.ErrorMessage, response.ErrorMessage);

            return new ApiResponse<IpBlock>(statusCode,
                response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (IpBlock)Configuration.ApiClient.Deserialize(response, typeof(IpBlock)));

        }
        /// <summary>
        /// Reserve IP Block This will reserve a new IP Block
        /// </summary>
        /// <param name="ipblock">IP Block to be reserved</param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of IpBlock</returns>
        public async System.Threading.Tasks.Task<IpBlock> CreateAsync(IpBlock ipblock, bool? parameter = null, int? depth = null)
        {
            ApiResponse<IpBlock> response = await CreateAsyncWithHttpInfo(ipblock, parameter, depth);
            return response.Data;

        }
 /// <summary>
 /// Reserve IP Block This will reserve a new IP Block
 /// </summary>
 /// <param name="ipblock">IP Block to be reserved</param> 
 /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
 /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
 /// <returns>IpBlock</returns>
 public IpBlock Create(IpBlock ipblock, bool? parameter = null, int? depth = null)
 {
     ApiResponse<IpBlock> response = CreateWithHttpInfo(ipblock, parameter, depth);
     response.Data.Request = response.Headers["Location"];
     return response.Data;
 }
Beispiel #10
0
        protected override void BeginProcessing()
        {
            try
            {
                var dcApi              = new DataCenterApi(Utilities.Configuration);
                var serverApi          = new ServerApi(Utilities.Configuration);
                var volumeApi          = new VolumeApi(Utilities.Configuration);
                var attachedVolumesApi = new AttachedVolumesApi(Utilities.Configuration);

                var datacenter = dcApi.FindById(DataCenterId, depth: 5);

                var server = new Server
                {
                    Properties = new ServerProperties
                    {
                        Name      = this.Name,
                        Cores     = this.Cores,
                        Ram       = (int)(this.Ram / 1024 / 1024),
                        CpuFamily = this.CpuFamily
                    }
                };

                var newServer = serverApi.Create(this.DataCenterId, server);

                WriteVerbose("Creating the server...");

                Utilities.DoWait(newServer.Request);

                if (!string.IsNullOrEmpty(this.AvailabilityZone))
                {
                    server.Properties.AvailabilityZone = this.AvailabilityZone;
                }

                if (!string.IsNullOrEmpty(this.BootVolume))
                {
                    server.Properties.BootVolume = new ResourceReference {
                        Id = this.BootVolume
                    };
                }

                if (!string.IsNullOrEmpty(this.BootCDRom))
                {
                    server.Properties.BootCdrom = new ResourceReference {
                        Id = this.BootCDRom
                    };
                }

                long size = Size;
                size = size == 0 ? 21474836480 : Size;

                var volume = new Volume
                {
                    Properties = new VolumeProperties
                    {
                        Size = (int)(size / 1024 / 1024 / 1024),
                        Type = (string.IsNullOrEmpty(DiskType) ? "HDD" : DiskType),
                        Name = Name,
                    }
                };

                if (!string.IsNullOrEmpty(ImageId))
                {
                    volume.Properties.Image = ImageId;
                }

                if (!string.IsNullOrEmpty(ImageAlias))
                {
                    volume.Properties.ImageAlias = ImageAlias;
                }

                if (!string.IsNullOrEmpty(SshKey))
                {
                    volume.Properties.SshKeys = new List <string> {
                        SshKey
                    };
                }

                if (!string.IsNullOrEmpty(Password))
                {
                    volume.Properties.ImagePassword = Password;
                }

                WriteVerbose("Creating the volume...");
                volume = volumeApi.Create(this.DataCenterId, volume);

                Utilities.DoWait(volume.Request);

                var attachedVol = attachedVolumesApi.AttachVolume(DataCenterId, newServer.Id, new Volume {
                    Id = volume.Id
                });



                if (this.PublicIp)
                {
                    var nic = new Nic
                    {
                        Properties = new NicProperties
                        {
                            Lan = 1,
                        }
                    };
                    var nicApi = new NetworkInterfacesApi(Utilities.Configuration);

                    if (this.StaticIp)
                    {
                        var ipblockApi = new IPBlocksApi(Utilities.Configuration);

                        var ipblock = new IpBlock
                        {
                            Properties = new IpBlockProperties
                            {
                                Location = datacenter.Properties.Location,
                                Size     = 1
                            }
                        };
                        WriteVerbose("Creating the static IP address...");
                        ipblock = ipblockApi.Create(ipblock);


                        Utilities.DoWait(ipblock.Request);
                        nic.Properties.Ips = ipblock.Properties.Ips;
                    }

                    WriteVerbose("Creating the nic...");
                    nic = nicApi.Create(DataCenterId, newServer.Id, nic);

                    Utilities.DoWait(nic.Request);
                }

                server = serverApi.FindById(datacenter.Id, newServer.Id, depth: 5);

                datacenter = dcApi.FindById(DataCenterId, depth: 5);

                server = serverApi.FindById(datacenter.Id, newServer.Id, depth: 5);


                WriteObject(server);
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
            }
        }