openstack.net uses C# .Net to operate the openstack SDK CLI

1. Introduction to openstack.net

  •     What is openstack.net for? It mainly provides a set of SDK for .Net developers to operate on the openstack platform, which can be simply regarded as a CLI tool based on the .Net platform, so as to provide .Net developers with convenient secondary development functions of the cloud computing platform.

    The current openstack.net project is implemented in c#, which is open sourced by Rackspace on the basis of its business. Project address:
    https://github.com/openstacknetsdk/openstack.net
    http://www.openstacknetsdk.org/

  •     openstack.net simple structure

  •      Keystone related: provider and Identity

     The provider is where your account resides. Such as Rackspace, VMWare, Azure, Openstack, etc. Apparently, you cannot create (or "start") a server in Azure with a Rackspace account. By authenticating your account with the provider, you obtain an identity and thus can use cloud objects. In other words, your identity is your Identity at a particular provider.

    When working with cloud objects, Identity can be used in one of two ways:

    An Identity object can be passed in each method call, or

    An identity object can be specified when creating a provider object, and all subsequent calls using that provider object will use the identity object.

    For example: 

_cloudIdentity = new CloudIdentity(){Username = "username", APIKey = "api_key_goes_here"};

  Example 1

Once the Identity object is created, it is used to create the Provider object. Provider objects allow you to perform cloud tasks such as starting servers, uploading files, etc.

The following example (Example 2) uses an Identity object to demonstrate how to create a Provider object. Note that the Identity object is included when instantiating the provider. This allows us to make subsequent calls without including the identity each time.

_provider = new CloudServersProvider(_cloudIdentity);

Example 2

Now that we have a Provider object, we can use it to perform cloud tasks (more on these tasks later in this article), such as starting a server.

For example starting a server instance. It's not important to fully understand this example, it's just that the principle is clearly understood: Providers are where you do most of your work.

NewServer newServer = _provider.CreateServer(serverName, imageId, flavorId);
  • Instance servers related

A fundamental property of cloud computing is the ability to spin up additional servers as demand increases and scale them down when demand decreases.

OpenStack allows you to start servers programmatically. A software developer can write a few lines of code in minutes that used to take days for hardware technicians and network administrators.

Depending on the provider, you may have many operating system and virtual machine configurations to choose from. In addition, some software may also be provided.

The typical code for starting an instance service by using openstack.net is defined as follows
:
 

 public ServerCreateDefinition(string name, Identifier imageId, Identifier flavorId)
        {
            Name = name;
            ImageId = imageId;
            FlavorId = flavorId;
            SecurityGroups = new List<SecurityGroupReference>();
            Networks = new List<ServerNetworkDefinition>();
            Metadata = new Dictionary<string, string>();
            Personality = new List<Personality>();
            BlockDeviceMapping = new List<ServerBlockDeviceMapping>();
        }

 create:
 

 public virtual async Task<T> CreateServerAsync<T>(object server, CancellationToken cancellationToken = default(CancellationToken))
            where T : IServiceResource
        {
            return await BuildCreateServerRequest(server, cancellationToken)
                .SendAsync()
                .ReceiveJson<T>()
                .PropogateOwner(this).ConfigureAwait(false);
        }

Two, use

  The openstack.net open source project has a built-in sample, let's take a look at its operation

Create server, create snapshot

using System;
using System.Linq;
using System.Threading.Tasks;
using net.openstack.Core.Domain;
using net.openstack.Core.Providers;
using OpenStack.Compute.v2_1;

public class ComputeSample : ISample
{
    public async Task Run(string identityEndpoint, string username, string password, string project, string region)
    {
        // Configure authentication
        var user = new CloudIdentityWithProject
        {
            Username = username,
            Password = password,
            ProjectName = project
        };
        var identity = new OpenStackIdentityProvider(new Uri(identityEndpoint), user);
        var compute = new ComputeService(identity, region);

        Console.WriteLine("Looking up the tiny flavor...");
        var flavors = await compute.ListFlavorsAsync();
        var tinyFlavor = flavors.FirstOrDefault(x => x.Name.Contains("tiny"));
        if (tinyFlavor == null) throw new Exception("Unable to find a flavor with the 'tiny' in the name!");

        Console.WriteLine("Looking up the cirros image...");
        var images = await compute.ListImagesAsync(new ImageListOptions { Name = "cirros" });
        var cirrosImage = images.FirstOrDefault();
        if (cirrosImage == null) throw new Exception("Unable to find an image named 'cirros'");

        Console.WriteLine("Creating Sample server... ");
        var serverDefinition = new ServerCreateDefinition("sample", cirrosImage.Id, tinyFlavor.Id);
        //附上网络 
        var insideNetwork = new ServerNetworkDefinition
        {
            NetworkId = "8c7f834d-e552-4996-9810-e706b3e7a3a5"
        };
        serverDefinition.Networks.Add(insideNetwork);
        var server = await compute.CreateServerAsync(serverDefinition);

        Console.WriteLine("Waiting for the sample server to come online...");
        await server.WaitUntilActiveAsync();

        Console.WriteLine("Taking a snaphot of the sample server...");
        var snapshot = await server.SnapshotAsync(new SnapshotServerRequest("sample-snapshot"));
        await snapshot.WaitUntilActiveAsync();

        Console.WriteLine();
        Console.WriteLine("Sample Server Information:");
        Console.WriteLine();
        Console.WriteLine($"Server Id: {server.Id}");
        Console.WriteLine($"Server Name: {server.Name}");
        Console.WriteLine($"Server Status: {server.Status}");
        Console.WriteLine($"Server Address: {server.IPv4Address}");
        Console.WriteLine();
        Console.WriteLine("Sample Snapshot Information:");
        Console.WriteLine();
        Console.WriteLine($"Image Id: {snapshot.Id}");
        Console.WriteLine($"Image Name: {snapshot.Name}");
        Console.WriteLine($"Image Status: {snapshot.Status}");
        Console.WriteLine($"Image Type: {snapshot.Type}");
        Console.WriteLine();

        Console.WriteLine("Deleting Sample Server...");
        await snapshot.DeleteAsync();
        await server.DeleteAsync();
    }

    public void PrintTasks()
    {
        Console.WriteLine("This sample will perform the following tasks:");
        Console.WriteLine("\t* Lookup a flavor with tiny in the name");
        Console.WriteLine("\t* Lookup an image named cirros");
        Console.WriteLine("\t* Create a server using cirros and the tiny flavor");
        Console.WriteLine("\t* Snapshot the server");
        Console.WriteLine("\t* Delete the snapshot and server");
    }

}

operation result:

Synchronous service instance creation can be seen in the openstack panel

Create networks and subnets

 

using System;
using System.Linq;
using System.Threading.Tasks;
using net.openstack.Core.Domain;
using net.openstack.Core.Providers;
using OpenStack.Networking;
using OpenStack.Networking.v2;

public class NetworkingSample : ISample
{
    public async Task Run(string identityEndpoint, string username, string password, string project, string region)
    {
        // Configure authentication
        var user = new CloudIdentityWithProject
        {
            Username = username,
            Password = password,
            ProjectName = project
        };
        var identity = new OpenStackIdentityProvider(new Uri(identityEndpoint), user);
        var networking = new NetworkingService(identity, region);

        Console.WriteLine("Creating Sample Network... ");
        var networkDefinition = new NetworkDefinition {Name = "Sample"};
        var sampleNetwork = await networking.CreateNetworkAsync(networkDefinition);

        Console.WriteLine("Adding a subnet to Sample Network...");
        var subnetDefinition = new SubnetCreateDefinition(sampleNetwork.Id, IPVersion.IPv4, "192.0.2.0/24")
        {
            Name = "Sample"
        };
        var sampleSubnet = await networking.CreateSubnetAsync(subnetDefinition);

        Console.WriteLine("Attaching a port to Sample Network...");
        var portDefinition = new PortCreateDefinition(sampleNetwork.Id)
        {
            Name = "Sample"
        };
        var samplePort = await networking.CreatePortAsync(portDefinition);

        Console.WriteLine("Listing Networks...");
        var networks = await networking.ListNetworksAsync();
        foreach (Network network in networks)
        {
            Console.WriteLine($"{network.Id}\t\t\t{network.Name}");
        }

        Console.WriteLine();
        Console.WriteLine("Sample Network Information:");
        Console.WriteLine();
        Console.WriteLine($"Network Id: {sampleNetwork.Id}");
        Console.WriteLine($"Network Name: {sampleNetwork.Name}");
        Console.WriteLine($"Network Status: {sampleNetwork.Status}");
        Console.WriteLine();
        Console.WriteLine($"Subnet Id: {sampleSubnet.Id}");
        Console.WriteLine($"Subnet Name: {sampleSubnet.Name}");
        Console.WriteLine($"Subnet IPs: {sampleSubnet.AllocationPools.First().Start} - {sampleSubnet.AllocationPools.First().End}");
        Console.WriteLine();
        Console.WriteLine($"Port Id: {samplePort.Id}");
        Console.WriteLine($"Port Name: {samplePort.Name}");
        Console.WriteLine($"Port Address: {samplePort.MACAddress}");
        Console.WriteLine($"Port Status: {samplePort.Status}");
        Console.WriteLine();

        Console.WriteLine("Deleting Sample Network...");
        await networking.DeletePortAsync(samplePort.Id);
        await networking.DeleteNetworkAsync(sampleNetwork.Id);
    }

    public void PrintTasks()
    {
        Console.WriteLine("This sample will perform the following tasks:");
        Console.WriteLine("\t* Create a network");
        Console.WriteLine("\t* Add a subnet to the network");
        Console.WriteLine("\t* Attach a port to the network");
        Console.WriteLine("\t* Delete the network");
    }

}

operation result:

The sample network in the openstack panel has been created

 3. Reference documents

https://github.com/openstacknetsdk/openstack.net/wiki/Getting-Started-With-The-OpenStack-NET-SDK

http://www.openstacknetsdk.org/docs/html/e11545c6-88c9-4ff1-b0cf-abffd4bd3ff7.htm

https://github.com/openstacknetsdk/openstack.net/wiki

Guess you like

Origin blog.csdn.net/zhujisoft/article/details/109671635