Beispiel #1
0
        static void Main(string[] args)
        {
            var identityUrl = new Uri("{identity-url}");
            var identity    = new CloudIdentityWithProject
            {
                Username    = "******",
                ProjectName = "{project-name}",
                Password    = "******"
            };
            const string region           = "RegionOne";
            var          identityProvider = new OpenStackIdentityProvider(identityUrl, identity);
            var          filesProvider    = new CloudFilesProvider(null, identityProvider);
            // Create versions container
            const string versionContainerName = "mycontainer-versions";

            filesProvider.CreateContainer(versionContainerName, region: region);
            // Create main container
            const string containerName = "mycontainer";
            var          headers       = new Dictionary <string, string>
            {
                { "X-Versions-Location", versionContainerName }
            };

            filesProvider.CreateContainer(containerName, headers, region);
            // Upload the initial file
            filesProvider.CreateObjectFromFile(containerName, @"C:\thing-v1.txt", "thing.txt", region: region);
            // Upload the same file again, this should not create a new version
            filesProvider.CreateObjectFromFile(containerName, @"C:\thing-v1.txt", "thing.txt", region: region);
            // Upload a new version of the file
            filesProvider.CreateObjectFromFile(containerName, @"C:\thing-v2.txt", "thing.txt", region: region);
        }
        /// <inheritdoc/>
        public UserAccess CreateUserAccess(string username, string password, string tenantName = null, string tenantId = null)
        {
            CloudIdentity identity = null;
            if (tenantId == null)
            {
                identity = new CloudIdentity()
                {
                    Username = username,
                    Password = password
                };

            }
            else
            {
                identity = new CloudIdentityWithProject()
                {
                    ProjectId = (new ProjectId(tenantId ?? tenantName)),
                    ProjectName = tenantName,
                    Username = username,
                    Password = password
                };

            }

            CloudIdentityProvider identityProvider = new CloudIdentityProvider(identity, DefaultPublicEndPointUri);
            UserAccess ua = identityProvider.GetUserAccess(identity);
            this.UA = ua;
            return ua;
        }
        /// <inheritdoc/>
        public UserAccess CreateUserAccess(string username, string password, string tenantName = null, string tenantId = null)
        {
            CloudIdentity identity = null;

            if (tenantId == null)
            {
                identity = new CloudIdentity()
                {
                    Username = username,
                    Password = password
                };
            }
            else
            {
                identity = new CloudIdentityWithProject()
                {
                    ProjectId   = (new ProjectId(tenantId ?? tenantName)),
                    ProjectName = tenantName,
                    Username    = username,
                    Password    = password
                };
            }

            CloudIdentityProvider identityProvider = new CloudIdentityProvider(identity, DefaultPublicEndPointUri);
            UserAccess            ua = identityProvider.GetUserAccess(identity);

            this.UA = ua;
            return(ua);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            const string region = "RegionOne";

            // Configure OpenStack.NET
            OpenStackNet.Configure(options => options.DefaultTimeout = TimeSpan.FromSeconds(5));

            // Authenticate
            var identityUrl = new Uri("http://example.com");
            var user        = new CloudIdentityWithProject();
            var identity    = new OpenStackIdentityProvider(identityUrl, user);

            identity.Authenticate();

            // Use legacy and new providers
            var legacyNetworking = new CloudNetworksProvider(null, identity);

            legacyNetworking.ListNetworks();
            var networks = new NetworkingService(identity, region);

            networks.ListNetworks();

            var legacyCompute = new CloudServersProvider(null, identity);

            legacyCompute.ListServers();
            var compute = new ComputeService(identity, region);

            compute.ListServers();
        }
        /// <inheritdoc/>
        public override UserAccess GetUserAccess(CloudIdentity identity, bool forceCacheRefresh = false)
        {
            identity = identity ?? DefaultIdentity;

            CloudIdentityWithProject identityWithProject = identity as CloudIdentityWithProject;

            if (identityWithProject == null)
            {
                return(base.GetUserAccess(identityWithProject, forceCacheRefresh));
            }

            if (string.IsNullOrEmpty(identityWithProject.Password))
            {
                throw new NotSupportedException(string.Format("The {0} identity must specify a password.", typeof(CloudIdentityWithProject)));
            }
            if (!string.IsNullOrEmpty(identityWithProject.APIKey))
            {
                throw new NotSupportedException(string.Format("The {0} identity does not support API key authentication.", typeof(CloudIdentityWithProject)));
            }

            Func <UserAccess> refreshCallback =
                () =>
            {
                var projectId = identityWithProject.ProjectId != null?JToken.FromObject(identityWithProject.ProjectId) : string.Empty;

                JObject requestBody = new JObject(
                    new JProperty("auth", new JObject(
                                      new JProperty("passwordCredentials", new JObject(
                                                        new JProperty("username", JValue.CreateString(identityWithProject.Username)),
                                                        new JProperty("password", JValue.CreateString(identityWithProject.Password)))),
                                      new JProperty("tenantName", JToken.FromObject(identityWithProject.ProjectName)),
                                      new JProperty("tenantId", projectId))));

                var response = ExecuteRESTRequest <JObject>(identity, new Uri(UrlBase, "/v2.0/tokens"), HttpMethod.POST, requestBody, isTokenRequest: true);
                if (response == null || response.Data == null)
                {
                    return(null);
                }

                // The defalut json serialization is helpfully formatting the expires date string. Use our custom serializer for this part to prevent chaos of timezone proportions.
                var rawJson = response.Data["access"]?.ToString(Formatting.None);
                if (rawJson == null)
                {
                    return(null);
                }

                UserAccess access = OpenStackNet.Deserialize <UserAccess>(rawJson);
                if (access == null || access.Token == null)
                {
                    return(null);
                }

                return(access);
            };
            string key        = string.Format("{0}:{1}/{2}", UrlBase, identityWithProject.ProjectId, identityWithProject.Username);
            var    userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);

            return(userAccess);
        }
        /// <inheritdoc/>
        public override UserAccess GetUserAccess(CloudIdentity identity, bool forceCacheRefresh = false)
        {
            CloudIdentityWithProject identityWithProject = identity as CloudIdentityWithProject;

            if (identityWithProject == null)
            {
                return(base.GetUserAccess(identityWithProject, forceCacheRefresh));
            }

            if (string.IsNullOrEmpty(identityWithProject.Password))
            {
                throw new NotSupportedException(string.Format("The {0} identity must specify a password.", typeof(CloudIdentityWithProject)));
            }
            if (!string.IsNullOrEmpty(identityWithProject.APIKey))
            {
                throw new NotSupportedException(string.Format("The {0} identity does not support API key authentication.", typeof(CloudIdentityWithProject)));
            }

            Func <UserAccess> refreshCallback =
                () =>
            {
                JObject requestBody = new JObject(
                    new JProperty("auth", new JObject(
                                      new JProperty("passwordCredentials", new JObject(
                                                        new JProperty("username", JValue.CreateString(identityWithProject.Username)),
                                                        new JProperty("password", JValue.CreateString(identityWithProject.Password)))),
                                      new JProperty("tenantName", JToken.FromObject(identityWithProject.ProjectName)),
                                      new JProperty("tenantId", JToken.FromObject(identityWithProject.ProjectId)))));

                var response = ExecuteRESTRequest <JObject>(identity, new Uri(UrlBase, "/v2.0/tokens"), HttpMethod.POST, requestBody, isTokenRequest: true);
                if (response == null || response.Data == null)
                {
                    return(null);
                }

                JToken userAccessObject = response.Data["access"];
                if (userAccessObject == null)
                {
                    return(null);
                }

                UserAccess access = userAccessObject.ToObject <UserAccess>();
                if (access == null || access.Token == null)
                {
                    return(null);
                }

                return(access);
            };
            string key        = string.Format("{0}:{1}/{2}", UrlBase, identityWithProject.ProjectId, identityWithProject.Username);
            var    userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);

            return(userAccess);
        }
Beispiel #7
0
        public OpenStackMember(string username, string password, string tenantName = null, string tenantId = null, string defaultregion = "tyo1", bool bLazyProviderSetting = false)
        {
            if (username == null)
            {
                throw new ArgumentNullException("username");
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("username cannot be empty");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("password cannot be empty");
            }

            this.UserName   = username;
            this.TenantId   = tenantId;
            this.TenantName = tenantName;

            CloudIdentity identity = null;

            if (tenantName != null || tenantId != null)
            {
                identity = new CloudIdentityWithProject()
                {
                    ProjectId   = (new ProjectId(tenantId ?? tenantName)),
                    ProjectName = tenantName,
                    Username    = username,
                    Password    = password
                };
            }
            else
            {
                identity = new CloudIdentity()
                {
                    Username = username,
                    Password = password
                };
            }

            this.Identity      = identity;
            this.DefaultRegion = defaultregion;
            if (!bLazyProviderSetting)
            {
                SetProviders();
            }
        }
Beispiel #8
0
        private static void CopyToOvh()
        {
            Console.WriteLine("Copy to OVH");

            var username      = GetSetting("username");
            var password      = GetSetting("password");
            var projectname   = GetSetting("projectname");
            var containerName = GetSetting("containername");
            var uri           = GetSetting("uri");
            var zipFolder     = GetSetting("zipfolder");

            var zipFs = zipFolder.Split(';');

            foreach (var zipF in zipFs)
            {
                var identityEndpoint = new Uri(uri);
                var identity         = new CloudIdentityWithProject
                {
                    Username    = username,
                    Password    = password,
                    ProjectName = projectname
                };

                var identityProvider = new OpenStackIdentityProvider(identityEndpoint, identity);
                // Verify that we can connect and our credentials are correct
                identityProvider.Authenticate();

                var provider = new CloudFilesProvider(identity, identityProvider);


                var filelist = Directory.GetFiles(zipF, "*.zip");
                if (filelist.Any())
                {
                    foreach (var filePath in filelist)
                    {
                        Console.WriteLine("Copy OpenStack: " + DateTime.UtcNow + " " + filePath);

                        var objectName = Path.GetFileName(filePath);
                        // Method 2: Set metadata in a separate call after the object is created
                        provider.CreateObjectFromFile(containerName, filePath, objectName, null, 4096, null, "GRA1");
                        var metadata = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                        {
                            { "Key", "Value" }
                        };
                        provider.UpdateObjectMetadata(containerName, objectName, metadata, "GRA1");
                    }
                }
            }
        }
Beispiel #9
0
        public ExternalProviderOpenStack(string url, string user, string pass, string tenant, string bucket)
        {
            var identityEndpoint = new Uri(url);
            var identity         = new CloudIdentityWithProject
            {
                Username    = user,
                Password    = pass,
                ProjectName = tenant,
            };

            OpenStackIdentityProvider identityProvider = new OpenStackIdentityProvider(identityEndpoint, identity);

            GetStorageEndpoint(identityProvider, identity);

            openstackFilesProvider = new CloudFilesProvider(null, "regionOne", identityProvider, null);
            publicBucketName       = bucket;
            serverUrl = url;

            CreateBuckets();
        }
Beispiel #10
0
        public ExternalProviderOpenStack(GXService providerService)
        {
            var identityEndpoint = new Uri(providerService.Properties.Get("SERVER_URL"));
            var identity         = new CloudIdentityWithProject
            {
                Username    = CryptoImpl.Decrypt(providerService.Properties.Get("STORAGE_PROVIDER_USER")),
                Password    = CryptoImpl.Decrypt(providerService.Properties.Get("STORAGE_PROVIDER_PASSWORD")),
                ProjectName = providerService.Properties.Get("TENANT_NAME"),
            };

            OpenStackIdentityProvider identityProvider = new OpenStackIdentityProvider(identityEndpoint, identity);

            GetStorageEndpoint(identityProvider, identity);

            openstackFilesProvider = new CloudFilesProvider(null, "regionOne", identityProvider, null);
            publicBucketName       = CryptoImpl.Decrypt(providerService.Properties.Get("PUBLIC_BUCKET_NAME"));
            privateBucketName      = CryptoImpl.Decrypt(providerService.Properties.Get("PRIVATE_BUCKET_NAME"));
            folderName             = providerService.Properties.Get("FOLDER_NAME");
            serverUrl = providerService.Properties.Get("SERVER_URL");

            CreateBuckets();
            CreateFolder(folderName);
        }
Beispiel #11
0
        private void GetStorageEndpoint(OpenStackIdentityProvider identityProvider, CloudIdentityWithProject identity)
        {
            UserAccess user    = identityProvider.GetUserAccess(identity);
            var        catalog = user.ServiceCatalog;
            Endpoint   objectStorageEndpoint = null;

            foreach (ServiceCatalog service in catalog)
            {
                if (service.Type == "object-store")
                {
                    if (service.Endpoints.Any())
                    {
                        objectStorageEndpoint = service.Endpoints.First();
                    }
                }
            }

            storageUrl = objectStorageEndpoint.PublicURL;

            if (String.IsNullOrEmpty(storageUrl))
            {
                throw new Exception("Couldn't found object storage endpoint, please check credentials in storage configuration.");
            }
        }
Beispiel #12
0
        /// <inheritdoc/>
        public override UserAccess GetUserAccess(CloudIdentity identity, bool forceCacheRefresh = false)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            CloudIdentityWithProject identityWithProject = identity as CloudIdentityWithProject;

            if (identityWithProject == null)
            {
                if (identity.GetType() != typeof(CloudIdentity))
                {
                    throw new NotSupportedException(string.Format("{0} does not support credentials of type {1}", GetType().Name, identity.GetType().Name));
                }
            }

            Func <UserAccess> refreshCallback =
                () =>
            {
                JObject credentialsObject;
                if (!string.IsNullOrEmpty(identity.APIKey))
                {
                    credentialsObject = new JObject(
                        new JProperty("apiAccessKeyCredentials", new JObject(
                                          new JProperty("accessKey", identity.APIKey),
                                          new JProperty("secretKey", identity.Password))));
                }
                else
                {
                    credentialsObject = new JObject(
                        new JProperty("passwordCredentials", new JObject(
                                          new JProperty("username", identity.Username),
                                          new JProperty("password", identity.Password))));
                }

                JObject authObject = new JObject(credentialsObject);
                if (identityWithProject != null && identityWithProject.ProjectId != null)
                {
                    authObject.Add("tenantId", JToken.FromObject(identityWithProject.ProjectId));
                }
                if (identityWithProject != null && !string.IsNullOrEmpty(identityWithProject.ProjectName))
                {
                    authObject.Add("tenantName", JToken.FromObject(identityWithProject.ProjectName));
                }

                JObject requestBody = new JObject(
                    new JProperty("auth", authObject));

                var response = ExecuteRESTRequest <JObject>(identity, new Uri(UrlBase, "/v2.0/tokens"), HttpMethod.POST, requestBody, isTokenRequest: true);
                if (response == null || response.Data == null)
                {
                    return(null);
                }

                JToken userAccessObject = response.Data["access"];
                if (userAccessObject == null)
                {
                    return(null);
                }

                UserAccess access = userAccessObject.ToObject <UserAccess>();
                if (access == null || access.Token == null)
                {
                    return(null);
                }

                return(access);
            };
            string key        = string.Format("{0}:{1}/{2}/{3}/{4}", UrlBase, identityWithProject != null ? identityWithProject.ProjectId : null, identity.Username, identity.APIKey, identity.Password);
            var    userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);

            return(userAccess);
        }
Beispiel #13
0
    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);
    }
Beispiel #14
0
    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 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();
    }
Beispiel #15
0
        public static void Main(string[] args)
        {
            // step-1
            var username     = "******";
            var password     = "******";
            var project_name = "your_project_name";
            var project_id   = "your_project_id";
            var auth_url     = "http://controller:5000/v2.0";
            var region       = "your_region_name";
            var networkid    = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

            var identity = new CloudIdentityWithProject()
            {
                Username    = username,
                Password    = password,
                ProjectId   = new ProjectId(project_id),
                ProjectName = project_name
            };

            var identityProvider = new OpenStackIdentityProvider(
                new Uri(auth_url));

            var conn = new CloudServersProvider(identity, identityProvider);

            // step-2
            var images = conn.ListImages(region: region);

            foreach (var image in images)
            {
                Console.WriteLine(string.Format(
                                      "Image Id: {0} - Image Name: {1}",
                                      image.Id,
                                      image.Name));
            }

            // step-3
            var flavors = conn.ListFlavors(region: region);

            foreach (var flavor in flavors)
            {
                Console.WriteLine(string.Format(
                                      "Flavor Id: {0} - Flavor Name: {1}",
                                      flavor.Id,
                                      flavor.Name));
            }

            // step-4
            var image_id = "97f55846-6ea5-4e9d-b437-bda97586bd0c";
            var _image   = conn.GetImage(image_id, region: region);

            Console.WriteLine(string.Format(
                                  "Image Id: {0} - Image Name: {1}",
                                  _image.Id,
                                  _image.Name));

            // step-5
            var flavor_id = "2";
            var _flavor   = conn.GetFlavor(flavor_id, region: region);

            Console.WriteLine(string.Format(
                                  "Flavor Id: {0} - Flavor Name: {1}",
                                  _flavor.Id,
                                  _flavor.Name));

            // step-6
            var instance_name    = "testing";
            var testing_instance = conn.CreateServer(instance_name,
                                                     _image.Id,
                                                     _flavor.Id,
                                                     region: region,
                                                     networks: new List <String> ()
            {
                networkid
            });

            Console.WriteLine(string.Format(
                                  "Instance Id: {0} at {1}",
                                  testing_instance.Id,
                                  testing_instance.Links
                                  ));

            // step-7
            var instances = conn.ListServers(region: region);

            foreach (var instance in instances)
            {
                Console.WriteLine(string.Format(
                                      "Instance Id: {0} at {1}",
                                      testing_instance.Id,
                                      testing_instance.Links));
            }

            // step-8
            conn.DeleteServer(testing_instance.Id, region: region);

            // step-9

            // step-10

            // step-11

            // step-12

            // step-13

            // step-14

            // step-15

            Console.Read();
        }
        public OpenStackMember(string username, string password, string tenantName = null, string tenantId = null, string defaultregion = "tyo1", bool bLazyProviderSetting = false)
        {
            if (username == null)
                throw new ArgumentNullException("username");
            if (string.IsNullOrEmpty(username))
                throw new ArgumentException("username cannot be empty");
            if (password == null)
                throw new ArgumentNullException("password");
            if (string.IsNullOrEmpty(password))
                throw new ArgumentException("password cannot be empty");

            this.UserName = username;
            this.TenantId = tenantId;
            this.TenantName = tenantName;

            CloudIdentity identity = null;
            if (tenantName != null || tenantId != null)
            {
                identity = new CloudIdentityWithProject()
                {
                    ProjectId = (new ProjectId(tenantId ?? tenantName)),
                    ProjectName = tenantName,
                    Username = username,
                    Password = password
                };
            }
            else
            {
                identity = new CloudIdentity()
                {
                    Username = username,
                    Password = password
                };
            }

            this.Identity = identity;
            this.DefaultRegion = defaultregion;
            if (!bLazyProviderSetting)
                SetProviders();
        }