public async Task BatchItemSessionTokenAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            testDocToReplace.Cost++;

            ItemResponse <TestDoc> readResponse = await BatchTestBase.JsonContainer.ReadItemAsync <TestDoc>(
                this.TestDocPk1ExistingA.Id,
                BatchTestBase.GetPartitionKey(this.PartitionKey1));

            ISessionToken beforeRequestSessionToken = BatchTestBase.GetSessionToken(readResponse.Headers.Session);

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerInlineCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .CreateItem(testDocToCreate)
                                                       .ReplaceItem(testDocToReplace.Id, testDocToReplace)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);
            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            ISessionToken afterRequestSessionToken = BatchTestBase.GetSessionToken(batchResponse.Headers.Session);

            Assert.IsTrue(afterRequestSessionToken.LSN > beforeRequestSessionToken.LSN, "Response session token should be more than request session token");
        }
Example #2
0
        public void TestSetSessionTokenDoesntWorkForMasterQueries()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId1 = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname1   = "dbs/db1/colls/collName1";

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.ReadFeed, collectionFullname1 + "/docs/42", ResourceType.Collection, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                request.ResourceId = collectionResourceId1;

                sessionContainer.SetSessionToken(request, new StoreRequestNameValueCollection()
                {
                    { HttpConstants.HttpHeaders.SessionToken, "range_0:1" }
                });
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId1, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");

                Assert.AreEqual(null, token);
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.CreateFromName(OperationType.Read, collectionFullname1 + "/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");

                Assert.AreEqual(null, token);
            }
        }
        private static string ResolvePartitionLocalSessionTokenForGateway(SessionContainerState self,
                                                                          DocumentServiceRequest request,
                                                                          string partitionKeyRangeId)
        {
            ConcurrentDictionary <string, ISessionToken> partitionKeyRangeIdToTokenMap = SessionContainer.GetPartitionKeyRangeIdToTokenMap(self, request);

            if (partitionKeyRangeIdToTokenMap != null)
            {
                if (partitionKeyRangeIdToTokenMap.TryGetValue(partitionKeyRangeId, out ISessionToken sessionToken))
                {
                    return(partitionKeyRangeId + SessionContainer.sessionTokenSeparator + sessionToken.ConvertToString());
                }
                else if (request.RequestContext.ResolvedPartitionKeyRange.Parents != null)
                {
                    ISessionToken parentSessionToken = null;
                    for (int parentIndex = request.RequestContext.ResolvedPartitionKeyRange.Parents.Count - 1; parentIndex >= 0; parentIndex--)
                    {
                        if (partitionKeyRangeIdToTokenMap.TryGetValue(request.RequestContext.ResolvedPartitionKeyRange.Parents[parentIndex],
                                                                      out sessionToken))
                        {
                            // A partition can have more than 1 parent (merge). In that case, we apply Merge to generate a token with both parent's max LSNs
                            parentSessionToken = parentSessionToken != null?parentSessionToken.Merge(sessionToken) : sessionToken;
                        }
                    }

                    // When we don't have the session token for a partition, we can leverage the session token of the parent(s)
                    if (parentSessionToken != null)
                    {
                        return(partitionKeyRangeId + SessionContainer.sessionTokenSeparator + parentSessionToken.ConvertToString());
                    }
                }
            }

            return(null);
        }
Example #4
0
        public void TestResolvePartitionLocalSessionTokenReturnsNullOnCollectionMiss()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId1 = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname    = "dbs/db1/colls/collName";

            sessionContainer.SetSessionToken(
                collectionResourceId1,
                collectionFullname,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
            }
                );

            sessionContainer.SetSessionToken(
                collectionResourceId1,
                collectionFullname,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_1:1#101#4=90#5=1" }
            }
                );

            var collectionResourceId2 = ResourceId.NewDocumentCollectionId(42, 130).DocumentCollectionId.ToString();

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId2, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_1");

                Assert.AreEqual(null, token);
            }
        }
        private static async Task <Nullable <long> > GetLSNFromSessionContainer(
            Container container,
            ContainerProperties containerProperties,
            PartitionKey pkValue)
        {
            string path      = $"dbs/{container.Database.Id}/colls/{container.Id}";
            string pkRangeId = await GetPKRangeIdForPartitionKey(container, containerProperties, pkValue);

            DocumentServiceRequest dummyRequest = new DocumentServiceRequest(
                OperationType.Read,
                ResourceType.Document,
                path,
                body: null,
                AuthorizationTokenType.PrimaryMasterKey,
                headers: null);

            ISessionToken sessionToken = container
                                         .Database
                                         .Client
                                         .DocumentClient
                                         .sessionContainer
                                         .ResolvePartitionLocalSessionToken(
                dummyRequest,
                pkRangeId);

            return(sessionToken?.LSN);
        }
Example #6
0
        public void TestSetSessionTokenOverwritesLowerLSN()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId1 = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname1   = "dbs/db1/colls/collName1";

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionFullname1 + "/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                request.ResourceId = collectionResourceId1;

                sessionContainer.SetSessionToken(request, new DictionaryNameValueCollection()
                {
                    { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
                });
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionFullname1 + "/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                request.ResourceId = collectionResourceId1;

                sessionContainer.SetSessionToken(request, new DictionaryNameValueCollection()
                {
                    { HttpConstants.HttpHeaders.SessionToken, "range_0:1#105#4=90#5=1" }
                });
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId1, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");

                Assert.AreEqual(105, token.LSN);
            }
        }
Example #7
0
 public StoreResultStatistics(
     DocumentClientException exception,
     StatusCodes statusCode,
     SubStatusCodes subStatusCode,
     string partitionKeyRangeId,
     long lsn,
     double requestCharge,
     bool isValid,
     Uri storePhysicalAddress,
     long globalCommittedLSN,
     long itemLSN,
     ISessionToken sessionToken,
     bool usingLocalLSN,
     string activityId)
 {
     this.Exception           = exception;
     this.StatusCode          = statusCode;
     this.SubStatusCode       = subStatusCode;
     this.PartitionKeyRangeId = partitionKeyRangeId;
     this.LSN                  = lsn;
     this.RequestCharge        = requestCharge;
     this.IsValid              = isValid;
     this.StorePhysicalAddress = storePhysicalAddress;
     this.GlobalCommittedLSN   = globalCommittedLSN;
     this.ItemLSN              = itemLSN;
     this.SessionToken         = sessionToken;
     this.UsingLocalLSN        = usingLocalLSN;
     this.ActivityId           = activityId;
 }
        internal static string GetDifferentLSNToken(string token, long lsnIncrement)
        {
            string[]      tokenParts            = token.Split(':');
            ISessionToken sessionToken          = SessionTokenHelper.Parse(tokenParts[1]);
            ISessionToken differentSessionToken = BatchTestBase.CreateSessionToken(sessionToken, sessionToken.LSN + lsnIncrement);

            return(string.Format(CultureInfo.InvariantCulture, "{0}:{1}", tokenParts[0], differentSessionToken.ConvertToString()));
        }
 protected bool HandleLoginResponse(ISessionToken sessionToken)
 {
     if (null != sessionToken)
     {
         Response.Headers.Add(TokenAuthenticationOptions.SessionTokenHeader, sessionToken.Id);
         return(true);
     }
     return(false);
 }
Example #10
0
 private bool IsTokenValid(ISessionToken token)
 {
     if (null != token && token.Expired)
     {
         _tokens.Remove(token.Id);
         return(false);
     }
     return(null != token);
 }
        public IWebConsoleData CreateWebConsole(
            string userId,
            ISessionToken sessionToken,
            ISolutionStsClient stsClient,
            string vcEndpoint)
        {
            IWebConsoleData result = null;

            _logger.LogInformation("StartCreateWebConsole");

            try {
                Sessions.Instance.EnsureValidUser(userId);
                _logger.LogDebug("RunspaceProvider -> CreateWebConsole call");

                string bearerSamlToken = "";
                try {
                    _logger.LogDebug($"HoK Saml Token availble: {sessionToken.HoKSamlToken != null}");
                    if (sessionToken.HoKSamlToken == null)
                    {
                        throw new Exception(APIGatewayResources.PowerCLIVCloginController_NoRefreshTokenAvailable_For_Session);
                    }

                    _logger.LogDebug($"STSClient -> IssueBearerTokenBySolutionToken call");
                    bearerSamlToken = stsClient
                                      .IssueBearerTokenBySolutionToken(sessionToken.HoKSamlToken.RawXmlElement)
                                      .OuterXml;
                } catch (Exception exc) {
                    _logger.LogError(exc, "Issue Bearer Token failed");
                    result.State        = DataTypes.WebConsoleState.Error;
                    result.ErrorDetails = new DataTypes.ErrorDetails(exc);
                }

                var token          = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(bearerSamlToken));
                var webConsoleInfo = _runspaceProvider.CreateWebConsole(vcEndpoint, token, true);
                _logger.LogDebug($"Runspace provider result: {webConsoleInfo.Id}, {webConsoleInfo.CreationState}, {webConsoleInfo.CreationError}");
                result = new WebConsoleData(webConsoleInfo);
                result.CreationTime = DateTime.Now;
                result.State        = DataTypes.WebConsoleState.Available;

                _runspacesStatsMonitor.RegisterWebConsole(result, sessionToken.SessionId);
                _userWebConsoles.Add(userId, result.Id, result);
            } catch (RunspaceProviderException runspaceProviderException) {
                _logger.LogError(runspaceProviderException, "Runspace provider exception was thrown");
                throw;
            } catch (Exception ex) {
                throw new RunspaceProviderException(
                          string.Format(
                              APIGatewayResources.MultiTenantRunspaceProvider_CreateFailed,
                              userId,
                              ex.Message),
                          ex);
            }

            return(result);
        }
Example #12
0
        public void TestClearTokenKeepsUnmatchedCollection()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId1 = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname1   = "dbs/db1/colls/collName1";

            sessionContainer.SetSessionToken(
                collectionResourceId1,
                collectionFullname1,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
            }
                );

            var    collectionResourceId2 = ResourceId.NewDocumentCollectionId(42, 130).DocumentCollectionId.ToString();
            string collectionFullname2   = "dbs/db1/colls/collName2";

            sessionContainer.SetSessionToken(
                collectionResourceId2,
                collectionFullname2,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
            }
                );

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId1, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(100, token.LSN);
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId2, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(100, token.LSN);
            }

            sessionContainer.ClearTokenByResourceId(collectionResourceId1);

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId1, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(null, token);
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId2, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(100, token.LSN);
            }
        }
Example #13
0
        public void TestSessionContainer()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            int numCollections          = 2;
            int numPartitionKeyRangeIds = 5;

            for (uint i = 0; i < numCollections; i++)
            {
                var    collectionResourceId = ResourceId.NewDocumentCollectionId(42, 129 + i).DocumentCollectionId.ToString();
                string collectionFullname   = "dbs/db1/colls/collName_" + i;

                for (int j = 0; j < numPartitionKeyRangeIds; j++)
                {
                    string partitionKeyRangeId = "range_" + j;
                    string lsn = "1#" + j + "#4=90#5=2";

                    sessionContainer.SetSessionToken(
                        collectionResourceId,
                        collectionFullname,
                        new DictionaryNameValueCollection()
                    {
                        { HttpConstants.HttpHeaders.SessionToken, $"{partitionKeyRangeId}:{lsn}" }
                    });
                }
            }

            using (DocumentServiceRequest request =
                       DocumentServiceRequest.Create(
                           OperationType.ReadFeed,
                           ResourceType.Collection,
                           new Uri("https://foo.com/dbs/db1/colls/collName_1", UriKind.Absolute),
                           new MemoryStream(Encoding.UTF8.GetBytes("content1")),
                           AuthorizationTokenType.PrimaryMasterKey,
                           null))
            {
                ISessionToken sessionToken = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_1");
                Assert.IsTrue(sessionToken.LSN == 1);

                DocumentServiceRequestContext dsrContext      = new DocumentServiceRequestContext();
                PartitionKeyRange             resolvedPKRange = new PartitionKeyRange();
                resolvedPKRange.Id      = "range_" + (numPartitionKeyRangeIds + 10);
                resolvedPKRange.Parents = new Collection <string>(new List <string> {
                    "range_2", "range_x"
                });
                dsrContext.ResolvedPartitionKeyRange = resolvedPKRange;
                request.RequestContext = dsrContext;

                sessionToken = sessionContainer.ResolvePartitionLocalSessionToken(request, resolvedPKRange.Id);
                Assert.IsTrue(sessionToken.LSN == 2);
            }
        }
 internal static ISessionToken CreateSessionToken(ISessionToken from, long globalLSN)
 {
     // Creates session token with specified GlobalLSN
     if (from is SimpleSessionToken)
     {
         return(new SimpleSessionToken(globalLSN));
     }
     else if (from is VectorSessionToken)
     {
         return(new VectorSessionToken(from as VectorSessionToken, globalLSN));
     }
     else
     {
         throw new ArgumentException();
     }
 }
Example #15
0
        public BaseServiceCaller(ISessionToken sessionToken, IConfiguration configuration = null)
        {
            SessionToken = sessionToken;
            if (configuration == null)
            {
                configuration = new Configuration();
            }

            Configuration = configuration;

            _session = new Session {
                Token = SessionToken.Token
            };
            _expiration = DateTime.MaxValue;
            InitializeHttpClients(configuration);
        }
Example #16
0
        public void TestClearTokenByResourceIdRemovesToken()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname   = "dbs/db1/colls/collName";

            sessionContainer.SetSessionToken(
                collectionResourceId,
                collectionFullname,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
            }
                );

            // check that can read from cache based on resource-id
            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(100, token.LSN);
            }

            // check that can read from cache based on name
            using (DocumentServiceRequest request = DocumentServiceRequest.CreateFromName(OperationType.Read, "dbs/db1/colls/collName/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(100, token.LSN);
            }

            sessionContainer.ClearTokenByResourceId(collectionResourceId);

            // check that can't read from cache based on resource-id
            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(null, token);
            }

            // check that can't read from cache based on name
            using (DocumentServiceRequest request = DocumentServiceRequest.CreateFromName(OperationType.Read, "dbs/db1/colls/collName/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");
                Assert.AreEqual(null, token);
            }
        }
 private void AddSessionToken(ulong rid, string partitionKeyRangeId, ISessionToken token)
 {
     this.sessionTokensRIDBased.AddOrUpdate(
         rid,
         (ridKey) =>
     {
         ConcurrentDictionary <string, ISessionToken> tokens = new ConcurrentDictionary <string, ISessionToken>();
         tokens[partitionKeyRangeId] = token;
         return(tokens);
     },
         (ridKey, tokens) =>
     {
         tokens.AddOrUpdate(
             partitionKeyRangeId,
             token,
             (existingPartitionKeyRangeId, existingToken) => existingToken.Merge(token));
         return(tokens);
     });
 }
Example #18
0
        public void TestSetSessionTokenGivesPriorityToOwnerIdOverResourceIdWhenRequestIsNameBased()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId1 = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            var    collectionResourceId2 = ResourceId.NewDocumentCollectionId(42, 130).DocumentCollectionId.ToString();
            string collectionFullname1   = "dbs/db1/colls/collName1";

            using (DocumentServiceRequest request = DocumentServiceRequest.CreateFromName(OperationType.Read, collectionFullname1 + "/docs/42", ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                request.ResourceId = collectionResourceId1;

                Assert.IsTrue(request.IsNameBased);

                sessionContainer.SetSessionToken(
                    request,
                    new DictionaryNameValueCollection()
                {
                    { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" },
                    { HttpConstants.HttpHeaders.OwnerId, collectionResourceId2 }
                }
                    );
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId1, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");

                Assert.AreEqual(null, token);
            }

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId2, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_0");

                Assert.AreEqual(100, token.LSN);
            }
        }
Example #19
0
        public void TestResolvePartitionLocalSessionTokenReturnsTokenOnParentMatch()
        {
            SessionContainer sessionContainer = new SessionContainer("127.0.0.1");

            var    collectionResourceId = ResourceId.NewDocumentCollectionId(42, 129).DocumentCollectionId.ToString();
            string collectionFullname   = "dbs/db1/colls/collName";

            sessionContainer.SetSessionToken(
                collectionResourceId,
                collectionFullname,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_0:1#100#4=90#5=1" }
            }
                );

            sessionContainer.SetSessionToken(
                collectionResourceId,
                collectionFullname,
                new DictionaryNameValueCollection()
            {
                { HttpConstants.HttpHeaders.SessionToken, "range_1:1#101#4=90#5=1" }
            }
                );

            using (DocumentServiceRequest request = DocumentServiceRequest.Create(OperationType.Read, collectionResourceId, ResourceType.Document, AuthorizationTokenType.PrimaryMasterKey, null))
            {
                request.RequestContext.ResolvedPartitionKeyRange         = new PartitionKeyRange();
                request.RequestContext.ResolvedPartitionKeyRange.Parents = new Collection <string>()
                {
                    "range_1"
                };

                ISessionToken token = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_2");

                Assert.AreEqual(101, token.LSN);
            }
        }
Example #20
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="token">A unique token, a JSON Web Token (JWT), valid for a limited period of time, typically an hour. Used to provide in the 'Authorization' header of forthcoming requests.</param>
 /// <param name="configuration"></param>
 public Client(ISessionToken token, IConfiguration configuration = null)
 {
     _service = new BaseServiceCaller(token, configuration);
 }
Example #21
0
        private void TestSessionContainer(Func <int, ISessionToken> getSessionToken)
        {
            ConcurrentDictionary <UInt64, ConcurrentDictionary <string, ISessionToken> > sessionTokens          = new ConcurrentDictionary <ulong, ConcurrentDictionary <string, ISessionToken> >();
            ConcurrentDictionary <string, ConcurrentDictionary <string, ISessionToken> > sessionTokensNameBased = new ConcurrentDictionary <string, ConcurrentDictionary <string, ISessionToken> >();

            int numCollections          = 2;
            int numPartitionKeyRangeIds = 5;

            for (int i = 0; i < numCollections; i++)
            {
                string collName = "dbs/db1/colls/collName_" + i;
                ulong  collId   = (ulong)i;

                ConcurrentDictionary <string, ISessionToken> idToTokenMap          = new ConcurrentDictionary <string, ISessionToken>();
                ConcurrentDictionary <string, ISessionToken> idToTokenMapNameBased = new ConcurrentDictionary <string, ISessionToken>();

                for (int j = 0; j < numPartitionKeyRangeIds; j++)
                {
                    string        range = "range_" + j;
                    ISessionToken token = getSessionToken(j);

                    bool successFlag = idToTokenMap.TryAdd(range, token) && idToTokenMapNameBased.TryAdd(range, token);

                    if (!successFlag)
                    {
                        throw new InvalidOperationException("Add should not fail!");
                    }
                }

                bool successFlag2 = sessionTokens.TryAdd(collId, idToTokenMap) && sessionTokensNameBased.TryAdd(collName, idToTokenMapNameBased);

                if (!successFlag2)
                {
                    throw new InvalidOperationException("Add should not fail!");
                }
            }

            SessionContainer sessionContainer = new SessionContainer("127.0.0.1", sessionTokens, sessionTokensNameBased);

            using (DocumentServiceRequest request =
                       DocumentServiceRequest.Create(
                           Cosmos.Internal.OperationType.ReadFeed,
                           Cosmos.Internal.ResourceType.Collection,
                           new Uri("https://foo.com/dbs/db1/colls/collName_1", UriKind.Absolute),
                           new MemoryStream(Encoding.UTF8.GetBytes("content1")),
                           AuthorizationTokenType.PrimaryMasterKey,
                           null))
            {
                ISessionToken sessionToken = sessionContainer.ResolvePartitionLocalSessionToken(request, "range_1");
                Assert.IsTrue(sessionToken.Equals(getSessionToken(1)));

                DocumentServiceRequestContext dsrContext      = new DocumentServiceRequestContext();
                PartitionKeyRange             resolvedPKRange = new PartitionKeyRange();
                resolvedPKRange.Id      = "range_" + (numPartitionKeyRangeIds + 10);
                resolvedPKRange.Parents = new Collection <string>(new List <string> {
                    "range_2", "range_x"
                });
                dsrContext.ResolvedPartitionKeyRange = resolvedPKRange;
                request.RequestContext = dsrContext;

                sessionToken = sessionContainer.ResolvePartitionLocalSessionToken(request, resolvedPKRange.Id);
                Assert.IsTrue(sessionToken.Equals(getSessionToken(2)));
            }
        }
Example #22
0
        public IRunspaceData StartCreate(
            string userId,
            ISessionToken sessionToken,
            string name,
            bool runVcConnectionScript,
            ISolutionStsClient stsClient,
            string vcEndpoint)
        {
            IRunspaceData result = null;

            _logger.LogInformation("StartCreate");

            try {
                Sessions.Instance.EnsureValidUser(userId);
                _logger.LogDebug("RunspaceProvider -> StartCreate call");
                var runspaceInfo = _runspaceProvider.StartCreate();
                _logger.LogDebug($"Runspace provider result: {runspaceInfo.Id}, {runspaceInfo.CreationState}, {runspaceInfo.CreationError}");
                result = new RunspaceData(runspaceInfo);
                result.CreationTime          = DateTime.Now;
                result.Name                  = name;
                result.RunVcConnectionScript = runVcConnectionScript;
                result.State                 = DataTypes.RunspaceState.Creating;

                _userRunspaces.Add(userId, result.Id, result);
                _runspacesStatsMonitor.Register(result, sessionToken.SessionId);

                Task.Run(() => {
                    _logger.LogDebug("RunspaceProvider -> WaitCreateCompletion call");
                    var waitResult = _runspaceProvider.WaitCreateCompletion(result);
                    _logger.LogDebug($"Runspace provider WaitCreateCompletion result: {waitResult.Id}, {waitResult.CreationState}, {waitResult.CreationError}");
                    if (waitResult.CreationState == RunspaceCreationState.Error)
                    {
                        ((RunspaceData)result).ErrorDetails = new DataTypes.ErrorDetails(waitResult.CreationError);
                        ((RunspaceData)result).State        = DataTypes.RunspaceState.Error;
                    }
                    else
                    {
                        // Update endpoint info
                        ((RunspaceData)result).Endpoint = waitResult.Endpoint;
                    }

                    if (waitResult.CreationState == RunspaceCreationState.Ready &&
                        !runVcConnectionScript)
                    {
                        ((RunspaceData)result).State = DataTypes.RunspaceState.Ready;
                    }

                    _logger.LogDebug($"Connect VC requested: {runVcConnectionScript}");
                    if (runVcConnectionScript && waitResult.CreationState == RunspaceCreationState.Ready)
                    {
                        string bearerSamlToken = null;

                        try {
                            _logger.LogDebug($"HoK Saml Token availble: {sessionToken.HoKSamlToken != null}");
                            if (sessionToken.HoKSamlToken == null)
                            {
                                throw new Exception(APIGatewayResources.PowerCLIVCloginController_NoRefreshTokenAvailable_For_Session);
                            }

                            _logger.LogDebug($"STSClient -> IssueBearerTokenBySolutionToken call");
                            bearerSamlToken = stsClient
                                              .IssueBearerTokenBySolutionToken(sessionToken.HoKSamlToken.RawXmlElement)
                                              .OuterXml;
                        } catch (Exception exc) {
                            _logger.LogError(exc, "Issue Bearer Token failed");
                            result.State        = DataTypes.RunspaceState.Error;
                            result.ErrorDetails = new DataTypes.ErrorDetails(exc);
                        }

                        if (bearerSamlToken != null)
                        {
                            // Connect PowerCLI
                            try {
                                var scriptExecutionRequest = new DataTypes.ScriptExecution {
                                    OutputObjectsFormat = OutputObjectsFormat.Json,
                                    Name             = "powerclivclogin",
                                    Script           = PCLIScriptsReader.ConnectByStringSamlToken,
                                    ScriptParameters = new DataTypes.ScriptParameter[] {
                                        new DataTypes.ScriptParameter {
                                            Name  = "server",
                                            Value = vcEndpoint
                                        },
                                        new DataTypes.ScriptParameter {
                                            Name  = "samlToken",
                                            Value = bearerSamlToken
                                        },
                                        new DataTypes.ScriptParameter {
                                            Name  = "allLinked",
                                            Value = true
                                        }
                                    }
                                };

                                _logger.LogDebug($"Start Connect VC script");
                                var scriptResult = ScriptExecutionMediatorSingleton.
                                                   Instance.
                                                   ScriptExecutionMediator.
                                                   StartScriptExecution(sessionToken.UserName, result, scriptExecutionRequest).Result;
                                result.VcConnectionScriptId = scriptResult.Id;

                                _logger.LogDebug($"Wait Connect VC script to complete");
                                while (scriptResult.State == ScriptState.Running)
                                {
                                    var intermediateResult = ScriptExecutionMediatorSingleton.Instance.ScriptExecutionMediator.GetScriptExecution(
                                        sessionToken.UserName,
                                        scriptResult.Id);
                                    if (intermediateResult != null)
                                    {
                                        scriptResult = intermediateResult;
                                    }
                                    Thread.Sleep(200);
                                }
                            } catch (RunspaceEndpointException runspaceEndointException) {
                                _logger.LogError(runspaceEndointException, "Runspace endpoint exception while waiting connect VC script");
                                result.ErrorDetails = new DataTypes.ErrorDetails(runspaceEndointException);
                                result.State        = DataTypes.RunspaceState.Error;
                            } catch (Exception exc) {
                                _logger.LogError(exc, "Wait Connect VC script failed");
                                result.ErrorDetails = new DataTypes.ErrorDetails(exc);
                                result.State        = DataTypes.RunspaceState.Error;
                            }
                        }

                        if (result.State != DataTypes.RunspaceState.Error)
                        {
                            result.State = DataTypes.RunspaceState.Ready;
                        }
                    }
                });
            } catch (RunspaceProviderException runspaceProviderException) {
                _logger.LogError(runspaceProviderException, "Runspace provider exception was thrown");
                throw;
            }
            catch (Exception ex) {
                throw new RunspaceProviderException(
                          string.Format(
                              APIGatewayResources.MultiTenantRunspaceProvider_CreateFailed,
                              userId,
                              ex.Message),
                          ex);
            }

            return(result);
        }
Example #23
0
        private static void AddSessionToken(SessionContainerState self, ulong rid, string partitionKeyRangeId, ISessionToken token)
        {
            // Avoid using GetOrAdd because it adds lock contention with the inner AddOrUpdate call
            if (!self.sessionTokensRIDBased.TryGetValue(rid, out ConcurrentDictionary <string, ISessionToken> tokens))
            {
                tokens = new ConcurrentDictionary <string, ISessionToken>();
                if (!self.sessionTokensRIDBased.TryAdd(rid, tokens))
                {
                    // Handle if there was a race condition and a different thread did
                    // the add after the initial read
                    if (!self.sessionTokensRIDBased.TryGetValue(rid, out tokens))
                    {
                        throw new InternalServerErrorException("AddSessionToken failed to get or add the session token dictionary.");
                    }
                }
            }

            tokens.AddOrUpdate(
                key: partitionKeyRangeId,
                addValue: token,
                updateValueFactory: (existingPartitionKeyRangeId, existingToken) => existingToken.Merge(token));
        }