Exemplo n.º 1
0
        public void DeserializeKeyPairCollection()
        {
            // this one is odd because even in the list, the items are wrapped with a root that needs to be unwrapped
            string json = JObject.Parse(@"{
  'keypairs': [
    {
      'keypair': {
        'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDrBzodZLiWO6nIGGy9ZOVeFhbF6EaG8HUqrknNVKynH6+Hc5ToY71gmeQGJ7XZTAlyKKdFmPhNPCQCYqFQxjPKD3xTIAoGChlRHfkjYwjefbqxFswi9S0Fi3Lq8mawUVuPmPnuTr8KhL8ibnBbAxZnrcfTKBIoxhU+kN56CCmLnkJc5ouG/UcF+UpqUso45pYRf0YWANyyuafyCmj6NiDxMCGy/vnKUBLzMg8wQ01xGSGOfyGDIwuTFZpoPzjeqEV8oUGvxYt9Xyzh/pPKoOz1cz0wBDaVDpucTz3UEq65F9HhCmdwwjso8MP1K46LkM2JNQWQ0eTotqFvUJEoP2ff Generated-by-Nova',
        'name': 'keypair-d20a3d59-9433-4b79-8726-20b431d89c78',
        'fingerprint': 'ce:88:fe:6a:9e:c0:d5:91:08:8b:57:80:be:e6:ec:3d'
      }
},
    {
      'keypair': {
        'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated-by-Nova',
        'name': 'uploaded-keypair',
        'fingerprint': '1e:2c:9b:56:79:4b:45:77:f9:ca:7a:98:2c:b0:d5:3c'
      }
    }
  ]
}").ToString();

            var results = OpenStackNet.Deserialize <KeyPairSummaryCollection>(json);

            Assert.NotNull(results);
            Assert.Equal(2, results.Count());
            var result = results.First();

            Assert.Empty(((IHaveExtraData)result).Data);
            Assert.NotNull(result.PublicKey);
        }
Exemplo n.º 2
0
        public void DeserializeVolumeWithEmptyAttachment()
        {
            var json   = JObject.Parse(@"{'volume': {'attachments': [{}]}}").ToString();
            var result = OpenStackNet.Deserialize <Volume>(json);

            Assert.Empty(result.Attachments);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 5
0
        public void SerializeWhenNested()
        {
            var json = OpenStackNet.Serialize(new ThingCollection {
                new Thing()
            });

            Assert.DoesNotContain("\"thing\"", json);
        }
Exemplo n.º 6
0
        public void DeserializeWhenNotRoot()
        {
            var json   = JArray.Parse("[{'id':'thing-id'}]").ToString();
            var things = OpenStackNet.Deserialize <List <Thing> >(json);

            Assert.Equal(1, things.Count);
            Assert.Equal("thing-id", things[0].Id);
        }
Exemplo n.º 7
0
        public void ShouldIgnoreUnexpectedRootProperties()
        {
            var json  = JObject.Parse("{'links': [{'name': 'next', 'link': 'http://nextlink'}], 'thing': {'id': 'thing-id'}}").ToString();
            var thing = OpenStackNet.Deserialize <Thing>(json);

            Assert.NotNull(thing);
            Assert.Equal("thing-id", thing.Id);
        }
Exemplo n.º 8
0
        public void SerializeWhenNotRoot()
        {
            var json = OpenStackNet.Serialize(new List <Thing> {
                new Thing()
            });

            Assert.DoesNotContain("\"thing\"", json);
        }
Exemplo n.º 9
0
        public void DeserializeWhenNested()
        {
            var json   = JObject.Parse("{'things':[{'id':'thing-id'}]}").ToString();
            var things = OpenStackNet.Deserialize <ThingCollection>(json);

            Assert.NotNull(things);
            Assert.Equal(1, things.Count);
            Assert.Equal("thing-id", things[0].Id);
        }
Exemplo n.º 10
0
 /// <inheritdoc />
 public new HttpTest RespondWithJson(int status, object data)
 {
     ResponseQueue.Enqueue(new HttpResponseMessage
     {
         StatusCode = (HttpStatusCode)status,
         Content    = new CapturedJsonContent(OpenStackNet.Serialize(data))
     });
     return(this);
 }
Exemplo n.º 11
0
        public void DeserializeTimeToLiveFromSeconds()
        {
            var cache = new ServiceCache("cache", TimeSpan.FromSeconds(60));
            var json  = OpenStackNet.Serialize(cache);

            var result = OpenStackNet.Deserialize <ServiceCache>(json);

            Assert.Equal(60, result.TimeToLive.TotalSeconds);
        }
Exemplo n.º 12
0
        public void Deserialize()
        {
            var json = OpenStackNet.Serialize(new Thing {
                Id = "thing-id"
            });
            var thing = OpenStackNet.Deserialize <Thing>(json);

            Assert.Equal("thing-id", thing.Id);
        }
Exemplo n.º 13
0
        public void Serialize()
        {
            var json = OpenStackNet.Serialize(new Thing());

            var       jsonObj      = JObject.Parse(json);
            JProperty rootProperty = jsonObj.Properties().FirstOrDefault();

            Assert.NotNull(rootProperty);
            Assert.Equal("thing", rootProperty.Name);
        }
Exemplo n.º 14
0
        public void SerializePageLink()
        {
            var    link = new PageLink("next", "http://api.com/next");
            string json = OpenStackNet.Serialize(link);

            var result = OpenStackNet.Deserialize <PageLink>(json);

            Assert.NotNull(result);
            Assert.True(result.IsNextPage);
        }
Exemplo n.º 15
0
        public void SerializeServerWithoutSchedulerHints()
        {
            string expectedJson = JObject.Parse(@"{'server':{'name':'name','imageRef':'00000000-0000-0000-0000-000000000000','flavorRef':'00000000-0000-0000-0000-000000000000'}}")
                                  .ToString(Formatting.None);
            var server = new ServerCreateDefinition("name", Guid.Empty, Guid.Empty);

            var json = OpenStackNet.Serialize(server);

            Assert.Equal(expectedJson, json);
        }
Exemplo n.º 16
0
        public void SerializeTimeToLiveToSeconds()
        {
            var cache = new ServiceCache("cache", TimeSpan.FromSeconds(60));

            var json = OpenStackNet.Serialize(cache);

            var result = JObject.Parse(json);

            Assert.Equal(60, result.Value <double>("ttl"));
        }
Exemplo n.º 17
0
        public void WhenSerializingEmptyCollection_ItShouldBeIgnored()
        {
            var thing = new ExampleThing {
                Messages = new List <string>()
            };

            string json = OpenStackNet.Serialize(thing);

            Assert.DoesNotContain("messages", json);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Resets all configuration (Rackspace.NET, OpenStack.NET, Flurl and Json.NET) so that <see cref="Configure"/> can be called again.
        /// </summary>
        public static void ResetDefaults()
        {
            lock (ConfigureLock)
            {
                if (!_isConfigured)
                {
                    return;
                }

                OpenStackNet.ResetDefaults();

                _isConfigured = false;
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Provides thread-safe accesss to Rackspace.NET's global configuration options.
        /// <para>
        /// Can only be called once at application start-up, before instantiating any Rackspace.NET objects.
        /// </para>
        /// </summary>
        /// <param name="configureFlurl">Addtional configuration of Flurl's global settings <seealso cref="FlurlHttp.Configure" />.</param>
        /// <param name="configureJson">Additional configuration of Json.NET's global settings <seealso cref="JsonConvert.DefaultSettings" />.</param>
        /// <param name="configure">Additional configuration of Rackspace.NET's global settings.</param>
        public static void Configure(Action <FlurlHttpConfigurationOptions> configureFlurl = null, Action <JsonSerializerSettings> configureJson = null, Action <RackspaceNetConfigurationOptions> configure = null)
        {
            if (configure != null)
            {
                lock (ConfigureLock) { configure(Configuration); }
            }

            Action <OpenStackNetConfigurationOptions> configureOpenStackNet = options =>
            {
                Configuration.Apply(options);
            };

            OpenStackNet.Configure(configureFlurl, configureJson, configureOpenStackNet);
        }
Exemplo n.º 20
0
        public void WhenDeserializingNullCollection_ItShouldUseAnEmptyCollection()
        {
            var thing = new ExampleThing {
                Messages = null
            };
            string json = OpenStackNet.Serialize(thing);

            Assert.DoesNotContain("messages", json);

            var result = OpenStackNet.Deserialize <ExampleThing>(json);

            Assert.NotNull(result.Messages);
            Assert.Empty(result.Messages);
        }
        public void Deserialize()
        {
            string json = JObject.Parse("{'port':{'extra_dhcp_opts':[{'opt_name':'a','opt_value':'stuff'},{'opt_name':'b','opt_value':'things'}]}}").ToString(Formatting.None);

            var result = OpenStackNet.Deserialize <PortCreateDefinition>(json).DHCPOptions;

            Assert.NotNull(result);
            Assert.Equal(2, result.Count);

            Assert.Contains("a", result.Keys);
            Assert.Contains("b", result.Keys);
            Assert.Equal("stuff", result["a"]);
            Assert.Equal("things", result["b"]);
        }
        public void OpenStackNet_UsesDHCPOptionConverter()
        {
            var port = new Port
            {
                DHCPOptions = new Dictionary <string, string>
                {
                    { "a", "stuff" }
                }
            };

            var json   = OpenStackNet.Serialize(port);
            var result = OpenStackNet.Deserialize <Port>(json);

            Assert.NotNull(result.DHCPOptions);
            Assert.Equal(1, result.DHCPOptions.Count);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Provides thread-safe accesss to Rackspace.NET's global configuration options.
        /// <para>
        /// Can only be called once at application start-up, before instantiating any Rackspace.NET objects.
        /// </para>
        /// </summary>
        /// <param name="configureFlurl">Addtional configuration of Flurl's global settings <seealso cref="FlurlHttp.Configure" />.</param>
        /// <param name="configureJson">Additional configuration of Json.NET's global settings <seealso cref="JsonConvert.DefaultSettings" />.</param>
        /// <param name="configure">Additional configuration of Rackspace.NET's global settings.</param>
        public static void Configure(Action <FlurlHttpConfigurationOptions> configureFlurl = null, Action <JsonSerializerSettings> configureJson = null, Action <RackspaceNetConfigurationOptions> configure = null)
        {
            lock (ConfigureLock)
            {
                if (_isConfigured)
                {
                    return;
                }

                OpenStackNet.Configure(configureFlurl, configureJson);

                configure?.Invoke(Configuration);
                Configuration.Apply(OpenStackNet.Configuration);

                _isConfigured = true;
            }
        }
        public void Serialize()
        {
            var input = new PortCreateDefinition(null)
            {
                DHCPOptions =
                {
                    { "a", "stuff"  },
                    { "b", "things" }
                }
            };

            string result = OpenStackNet.Serialize(input);

            string expectedJson = JObject.Parse("{'port':{'extra_dhcp_opts':[{'opt_name':'a','opt_value':'stuff'},{'opt_name':'b','opt_value':'things'}]}}").ToString(Formatting.None);

            Assert.Equal(expectedJson, result);
        }
Exemplo n.º 25
0
        public async Task UseBothOpenStackAndRackspace_RackspaceConfiguredFirst()
        {
            using (var httpTest = new HttpTest())
            {
                RackspaceNet.Configure();
                OpenStackNet.Configure();

                await "http://api.com".GetAsync();

                var userAgent = httpTest.CallLog[0].Request.Headers.UserAgent.ToString();

                var rackspaceMatches = new Regex("rackspace").Matches(userAgent);
                Assert.Equal(1, rackspaceMatches.Count);

                var openstackMatches = new Regex("openstack").Matches(userAgent);
                Assert.Equal(1, openstackMatches.Count);
            }
        }
Exemplo n.º 26
0
        public void DeserializeSecurityGroupRule()
        {
            const string json   = @"{
'security_group_rule': {
    'from_port': 22,
    'group': {},
    'ip_protocol': 'tcp',
    'to_port': 22,
    'parent_group_id': 'bfa0c0ed-274b-4711-b3ee-37d35660fb06',
    'ip_range': {
        'cidr': '0.0.0.0 / 24'
    },
    'id': '55d75417-37df-48e2-96aa-20ba53a82900'
}}";
            var          result = OpenStackNet.Deserialize <SecurityGroupRule>(JObject.Parse(json).ToString());

            Assert.Equal("0.0.0.0 / 24", result.CIDR);
        }
Exemplo n.º 27
0
        public void SerializeServiceCollection()
        {
            var services = new ServiceCollection
            {
                Items = { new Service {
                              Id = "service-id"
                          } },
                Links = { new PageLink("next", "http://api.com/next") }
            };
            string json = OpenStackNet.Serialize(services);

            Assert.Contains("\"services\"", json);
            Assert.DoesNotContain("\"service\"", json);

            var result = OpenStackNet.Deserialize <ServiceCollection>(json);

            Assert.NotNull(result);
            Assert.Single(result);
            Assert.Single(result.Items);
            Assert.Single(result.Links);
            Assert.True(result.HasNextPage);
        }
Exemplo n.º 28
0
        public void WhenValueIsUnrecognized_AndDestinationIsNullable_UseNull()
        {
            var result = OpenStackNet.Deserialize <StuffStatus?>("\"bad-enum-value\"");

            Assert.Null(result);
        }
Exemplo n.º 29
0
        public void WhenValueIsUnrecognized_AndUnknownIsNotPresent_MatchToFirstValue()
        {
            var result = OpenStackNet.Deserialize <StuffStatus>("\"bad-enum-value\"");

            Assert.Equal(StuffStatus.Missing, result);
        }
Exemplo n.º 30
0
        public void WhenValueIsUnrecognized_MatchToUnknownValue()
        {
            var result = OpenStackNet.Deserialize <ThingStatus>("\"bad-enum-value\"");

            Assert.Equal(ThingStatus.Unknown, result);
        }