public static BoolResult IsInstalled(string name)
        {
            
            Log.WriteStart("IsInstalled started. Name:{0}", name);
            BoolResult res = new BoolResult {IsSuccess = true};

            try
            {
                bool disableAutoDiscovery;

                if (!bool.TryParse(ConfigurationManager.AppSettings[DisableAutoDiscovery], out disableAutoDiscovery))
                    disableAutoDiscovery = false;
                
                if (disableAutoDiscovery)
                {
                    res.Value = true;
                    
                }
                else
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        res.IsSuccess = false;
                        res.ErrorCodes.Add(ErrorCodes.PROVIDER_NANE_IS_NOT_SPECIFIED);
                        return res;
                    }

                    Type providerType = Type.GetType(name);
                    IHostingServiceProvider provider = (IHostingServiceProvider)Activator.CreateInstance(providerType);
                    res.Value = provider.IsInstalled();
                }
            }
            catch (Exception ex)
            {
                res.IsSuccess = false;
                res.ErrorCodes.Add(ErrorCodes.CANNOT_CREATE_PROVIDER_INSTANCE);
                Log.WriteError(ex);
            }
            finally
            {
                Log.WriteEnd("IsInstalled ended. Name:{0}", name);
            }

            return res;
        }
Exemple #2
0
        /// <inheritdoc />
        public Task <BoolResult> ShutdownAsync(Context context)
        {
            return(ShutdownCall <ContentSessionTracer> .RunAsync(
                       Tracer,
                       context,
                       async() =>
            {
                ShutdownStarted = true;
                var finalResult = BoolResult.Success;

                foreach (var session in SessionsByCacheRoot.Values)
                {
                    var result = await session.ShutdownAsync(context).ConfigureAwait(false);
                    if (!result.Succeeded)
                    {
                        finalResult = new BoolResult(finalResult, result.ErrorMessage);
                    }
                }

                ShutdownCompleted = true;
                return finalResult;
            }));
        }
        private async Task RunServerTestAsync(Context context, Func <Context, ServiceConfiguration, Task> funcAsync)
        {
            using (var directory = new DisposableDirectory(FileSystem))
            {
                var storeConfig = CreateStoreConfiguration();
                storeConfig.Write(FileSystem, directory.Path);

                var serviceConfig = CreateServiceConfiguration(directory.Path, PortExtensions.GetNextAvailablePort(), Guid.NewGuid().ToString());

                using (var server = new ServiceProcess(serviceConfig, Scenario, WaitForServerReadyTimeoutMs, WaitForExitTimeoutMs))
                {
                    BoolResult r = await server.StartupAsync(context).ConfigureAwait(false);

                    r.ShouldBeSuccess();

                    await funcAsync(context, serviceConfig);

                    r = await server.ShutdownAsync(context);

                    r.ShouldBeSuccess();
                }
            }
        }
        /// <summary>
        /// Determines whether we can still perform an operation based on current state.
        /// </summary>
        public BoolResult CheckAndRegisterOperation()
        {
            if (_clock.UtcNow.Ticks >= Interlocked.Read(ref _nextOperationLimitTicks))
            {
                lock (this)
                {
                    if (_clock.UtcNow.Ticks >= _nextOperationLimitTicks)
                    {
                        Interlocked.Exchange(ref _nextOperationLimitTicks, _clock.UtcNow.Ticks + _operationLimitSpan.Ticks);
                        Interlocked.Exchange(ref _count, 0);
                        var nextSpan = new DateTime(ticks: _nextOperationLimitTicks);
                        _errorResult = new BoolResult($"Operation limit has been reached. Throttling operation. Limit={_operationLimitCount}, SpanDuration=[{_operationLimitSpan}] NextSpanStart=[{nextSpan:MM/dd/yyyy hh:mm:ss.ffff}]");
                    }
                }
            }

            if (Interlocked.Increment(ref _count) > _operationLimitCount)
            {
                return(_errorResult);
            }

            return(BoolResult.Success);
        }
Exemple #5
0
        /// <inheritdoc />
        public Task <BoolResult> ShutdownAsync(Context context)
        {
            ShutdownStarted = true;

            return(ShutdownCall <ContentSessionTracer> .RunAsync(_tracer, context, async() =>
            {
                var shutdownResults =
                    await
                    Task.WhenAll(_sessionForStream.ShutdownAsync(context), _sessionForPath.ShutdownAsync(context));
                Contract.Assert(shutdownResults.Length == 2);

                var shutdownResultForStream = shutdownResults[0];
                var shutdownResultForPath = shutdownResults[1];

                var result = shutdownResultForStream & shutdownResultForPath;

                if (!result.Succeeded)
                {
                    var sb = new StringBuilder();
                    if (!shutdownResultForStream.Succeeded)
                    {
                        sb.Concat($"{SessionForStreamText} shutdown failed, error=[{shutdownResultForStream}]", "; ");
                    }

                    if (!shutdownResultForPath.Succeeded)
                    {
                        sb.Concat($"{SessionForPathText} shutdown failed, error=[{shutdownResultForPath}]", "; ");
                    }

                    result = new BoolResult(sb.ToString());
                }

                ShutdownCompleted = true;

                return result;
            }));
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response">response value arrive from exchange's server</param>
        /// <returns></returns>
        public override BoolResult GetResponseMessage(IRestResponse response = null)
        {
            var _result = new BoolResult();

            if (response != null)
            {
                if (response.IsSuccessful == true)
                {
                    var _json_result = this.DeserializeObject <JToken>(response.Content);

                    var _json_error = _json_result.SelectToken("error");
                    if (_json_error != null)
                    {
                        var _error_msg = _json_error.Value <string>();
                        if (_error_msg != "")
                        {
                            _result.SetFailure(
                                _error_msg,
                                ErrorCode.ResponseDataError
                                );
                        }
                    }
                }

                if (_result.success == true && response.IsSuccessful == false)
                {
                    _result.SetFailure(
                        response.ErrorMessage ?? response.StatusDescription,
                        ErrorCode.ResponseRestError,
                        (int)response.StatusCode,
                        false
                        );
                }
            }

            return(_result);
        }
Exemple #7
0
        /// <inheritdoc />
        public Task <BoolResult> StartupAsync(Context context)
        {
            return(StartupCall <ContentSessionTracer> .RunAsync(
                       Tracer,
                       context,
                       async() =>
            {
                StartupStarted = true;

                var finalResult = BoolResult.Success;

                var sessions = SessionsByCacheRoot.Values.ToArray();
                for (var i = 0; i < sessions.Length; i++)
                {
                    var canHibernate = sessions[i] is IHibernateContentSession ? "can" : "cannot";
                    Tracer.Debug(context, $"Session {sessions[i].Name} {canHibernate} hibernate");
                    var startupResult = await sessions[i].StartupAsync(context).ConfigureAwait(false);

                    if (!startupResult.Succeeded)
                    {
                        finalResult = startupResult;
                        for (var j = 0; j < i; j++)
                        {
                            var shutdownResult = await sessions[j].ShutdownAsync(context).ConfigureAwait(false);
                            if (!shutdownResult.Succeeded)
                            {
                                finalResult = new BoolResult(finalResult, shutdownResult.ErrorMessage);
                            }
                        }
                    }
                }

                StartupCompleted = true;
                return finalResult;
            }));
        }
        protected override BoolResult OnCanRun(RunContext context)
        {
            if (!Target.CanRun)
            {
                return(BoolResult.False("Run is not supported with current build settings"));
            }

            var artifact = context.GetBuildArtifact <DotsRuntimeBuildArtifact>();

            if (artifact == null)
            {
                return(BoolResult.False($"Could not retrieve build artifact '{nameof(DotsRuntimeBuildArtifact)}'."));
            }

            if (artifact.OutputTargetFile == null)
            {
                return(BoolResult.False($"{nameof(DotsRuntimeBuildArtifact.OutputTargetFile)} is null."));
            }

            if (!File.Exists(artifact.OutputTargetFile.FullName) && !Directory.Exists(artifact.OutputTargetFile.FullName))
            {
                return(BoolResult.False($"Output target file '{artifact.OutputTargetFile.FullName}' not found."));
            }

            if (!context.TryGetComponent <DotsRuntimeBuildProfile>(out var profile))
            {
                return(BoolResult.False($"Could not retrieve component '{nameof(DotsRuntimeBuildProfile)}'."));
            }

            if (profile.Target == null)
            {
                return(BoolResult.False($"{nameof(DotsRuntimeBuildProfile)} target is null."));
            }

            return(BoolResult.True());
        }
Exemple #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response">response value arrive from exchange's server</param>
        /// <returns></returns>
        public override BoolResult GetResponseMessage(IRestResponse response = null)
        {
            var _result = new BoolResult();

            if (response != null)
            {
                if (response.IsSuccessful == true)
                {
                    var _json_result = this.DeserializeObject <JToken>(response.Content);

                    var _json_success = _json_result["result"];
                    if (_json_success != null)
                    {
                        if (_json_success.Value <string>() != "success")
                        {
                            _result.SetFailure(
                                _json_result["data"]["message"].Value <string>(),
                                ErrorCode.ResponseDataError
                                );
                        }
                    }
                }

                if (_result.success == true && response.IsSuccessful == false)
                {
                    _result.SetFailure(
                        response.ErrorMessage ?? response.StatusDescription,
                        ErrorCode.ResponseRestError,
                        (int)response.StatusCode,
                        false
                        );
                }
            }

            return(_result);
        }
Exemple #10
0
        /// <inheritdoc />
        public async Task <Possible <int, Failure> > IncorporateRecordsAsync(IEnumerable <Task <StrongFingerprint> > strongFingerprints, Guid activityId)
        {
            var sfpList = new List <StrongFingerprint>();
            int count   = 0;

            foreach (var sfpTask in strongFingerprints)
            {
                var sfp = await sfpTask;
                sfpList.Add(sfp);

                SessionEntries?.TryAdd(sfp, 1);
                count++;
            }

            BoolResult incorporateResult =
                await CacheSession.IncorporateStrongFingerprintsAsync(
                    new Context(Logger),
                    sfpList.Select(sfp => Task.FromResult(new BuildXL.Cache.MemoizationStore.Interfaces.Sessions.StrongFingerprint(
                                                              sfp.WeakFingerprint.ToMemoization(),
                                                              new Selector(sfp.CasElement.ToMemoization(), sfp.HashElement.RawHash.ToByteArray())))),
                    CancellationToken.None);

            return(incorporateResult.Succeeded ? count : new Possible <int, Failure>(new CacheFailure(incorporateResult.ErrorMessage)));
        }
        /// <inheritdoc />
        protected override async Task<BoolResult> StartupCoreAsync(OperationContext context)
        {
            BoolResult result = await PreStartupAsync(context);

            var rpcConfiguration = Configuration.RpcConfiguration;
            if (result.Succeeded)
            {
                _grpcClient = new GrpcContentClient(SessionTracer, FileSystem, rpcConfiguration.GrpcPort, Configuration.Scenario, rpcConfiguration.HeartbeatInterval);
                result = await Configuration.RetryPolicy.ExecuteAsync(() => _grpcClient.StartupAsync(context, waitMs: 0));

                if (!result)
                {
                    await Configuration.RetryPolicy.ExecuteAsync(() => _grpcClient.ShutdownAsync(context)).ThrowIfFailure();
                }
            }

            if (!result)
            {
                await PostShutdownAsync(context).ThrowIfFailure();
                return result;
            }

            return result;
        }
Exemple #12
0
        /// <inheritdoc />
        public virtual async Task <BoolResult> ShutdownAsync(Context context)
        {
            ShutdownStarted = true;
            var shutdownMemoizationResult = _memoizationReadOnlySession != null
                ? await _memoizationReadOnlySession.ShutdownAsync(context).ConfigureAwait(false)
                : BoolResult.Success;

            var shutdownContentResult = _contentReadOnlySession != null
                ? await _contentReadOnlySession.ShutdownAsync(context).ConfigureAwait(false)
                : BoolResult.Success;

            BoolResult result;

            if (shutdownMemoizationResult.Succeeded && shutdownContentResult.Succeeded)
            {
                result = BoolResult.Success;
            }
            else
            {
                var sb = new StringBuilder();
                if (!shutdownMemoizationResult.Succeeded)
                {
                    sb.Append($"Memoization session shutdown failed, error=[{shutdownMemoizationResult}]");
                }

                if (!shutdownContentResult.Succeeded)
                {
                    sb.Append($"Content session shutdown failed, error=[{shutdownContentResult}]");
                }

                result = new BoolResult(sb.ToString());
            }

            ShutdownCompleted = true;
            return(result);
        }
        public async Task <TResult> RunAsync([CallerMemberName] string?caller = null)
        {
            using (_counter?.Start())
            {
                TraceOperationStarted(caller !);
                var stopwatch = StopwatchSlim.Start();

                try
                {
                    // No need to run anything if the cancellation is requested already.
                    _context.Token.ThrowIfCancellationRequested();

                    var result = await AsyncOperation();

                    TraceOperationFinished(result, stopwatch.Elapsed, caller !);

                    return(result);
                }
                catch (Exception e)
                {
                    var resultBase = new BoolResult(e);

                    MarkResultIsCancelledIfNeeded(resultBase, e);

                    // Marking the operation as critical failure only when it was not a cancellation.
                    if (_isCritical && !resultBase.IsCancelled)
                    {
                        resultBase.MakeCritical();
                    }

                    TraceResultOperationFinished(resultBase, stopwatch.Elapsed, caller !);

                    throw;
                }
            }
        }
        public async Task IncorporateSucceedsAsync()
        {
            await IncorporateSucceedsAsyncRunner(async (context, incorporateSession, strongFingerprint, contentHashListWithDeterminism) =>
            {
                var strongFingerprints = new List <Task <StrongFingerprint> >()
                {
                    Task.FromResult(strongFingerprint)
                };
                BoolResult incorporateResult = await incorporateSession.IncorporateStrongFingerprintsAsync(context, strongFingerprints, Token).ConfigureAwait(false);
                return(incorporateResult.Succeeded);
            });

            await IncorporateSucceedsAsyncRunner(async (context, incorporateSession, strongFingerprint, contentHashListWithDeterminism) =>
            {
                var addOrGetResult = await incorporateSession.AddOrGetContentHashListAsync(context, strongFingerprint, contentHashListWithDeterminism, Token).ConfigureAwait(false);
                return(addOrGetResult.Succeeded);
            });

            await IncorporateSucceedsAsyncRunner(async (context, incorporateSession, strongFingerprint, contentHashListWithDeterminism) =>
            {
                var getResult = await incorporateSession.GetContentHashListAsync(context, strongFingerprint, Token).ConfigureAwait(false);
                return(getResult.Succeeded && (getResult.ContentHashListWithDeterminism.ContentHashList != null));
            });
        }
Exemple #15
0
        /// <inheritdoc />
        public Task <BoolResult> ShutdownAsync(Context context)
        {
            return(ShutdownCall <ContentStoreTracer> .RunAsync(Tracer, context, async() =>
            {
                ShutdownStarted = true;
                var finalResult = BoolResult.Success;

                foreach (var store in _drivesWithContentStore.Values)
                {
                    if (store.StartupCompleted && !store.ShutdownCompleted)
                    {
                        // Shutdown is available only when the store started up successfully and wasn't shut down yet.
                        var result = await store.ShutdownAsync(context).ConfigureAwait(false);
                        if (!result)
                        {
                            finalResult = new BoolResult(finalResult, result.ErrorMessage);
                        }
                    }
                }

                ShutdownCompleted = true;
                return finalResult;
            }));
        }
        /// <inheritdoc />
        protected override async Task <BoolResult> StartupCoreAsync(OperationContext context)
        {
            BoolResult result;

            try
            {
                result = await _configuration.ArtifactHttpClientFactory.StartupAsync(context);

                if (!result.Succeeded)
                {
                    return(result);
                }

                _artifactHttpClient = _configuration.UseDedupStore
                    ? (IArtifactHttpClient)await _configuration.ArtifactHttpClientFactory.CreateDedupStoreHttpClientAsync(context).ConfigureAwait(false)
                    : await _configuration.ArtifactHttpClientFactory.CreateBlobStoreHttpClientAsync(context).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                result = new BoolResult(e);
            }

            return(result);
        }
Exemple #17
0
 /// <inheritdoc />
 public void PostInitializationCompleted(Context context, BoolResult result)
 {
 }
Exemple #18
0
 public void PostInitializationCompleted(Context context, BoolResult result)
 {
     Contract.Requires(ContentStore != null, "ContentStore must be initialized here.");
     ContentStore.PostInitializationCompleted(context, result);
 }
Exemple #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response">response value arrive from exchange's server</param>
        /// <returns></returns>
        public override BoolResult GetResponseMessage(IRestResponse response = null)
        {
            var _result = new BoolResult();

            if (response != null)
            {
                if (response.IsSuccessful == true)
                {
                    var _json_result = this.DeserializeObject <JToken>(response.Content);

                    var _json_error = _json_result.SelectToken("error");
                    if (_json_error != null && _json_error.Count() > 0)
                    {
                        var _message = "";
                        {
                            if (_json_error.GetType() == typeof(JArray))
                            {
                                if (_json_error.Count() > 0)
                                {
                                    _message = _json_error[0].Value <string>();
                                }
                            }
                            else if (_json_error.GetType() == typeof(JValue))
                            {
                                _message = _json_error.Value <string>();
                            }
                        }

                        if (String.IsNullOrEmpty(_message) == false)
                        {
                            var _error_code = ErrorMessages
                                              .Where(e => _message.IndexOf(e.Key) >= 0)
                                              .OrderByDescending(e => e.Key.Length)
                                              .FirstOrDefault();

                            if (_error_code.Key != null)
                            {
                                _result.errorCode = _error_code.Value;
                            }
                            else
                            {
                                _result.errorCode = ErrorCode.ResponseDataError;
                            }

                            _result.SetFailure(
                                _message,
                                _result.errorCode
                                );
                        }
                        else
                        {
                            var _token_result = _json_result.SelectToken("result");
                            if (_token_result == null ||
                                (
                                    _token_result != null &&
                                    _token_result.GetType() == typeof(JArray) &&
                                    _token_result.Count() <= 0
                                )
                                )
                            {
                                _result.SetFailure(errorCode: ErrorCode.NotFoundData);
                            }
                        }
                    }
                }

                if (_result.success == true && response.IsSuccessful == false)
                {
                    _result.SetFailure(
                        response.ErrorMessage ?? response.StatusDescription,
                        ErrorCode.ResponseRestError,
                        (int)response.StatusCode,
                        false
                        );
                }
            }

            return(_result);
        }
Exemple #20
0
        public void ConstructFromResultBase()
        {
            var other = new BoolResult("error");

            Assert.False(new PutResult(other, Hash1, "message").Succeeded);
        }
        public async Task <OpenStreamResult> OpenStreamAsync(Context context, ContentHash contentHash, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal)
        {
            BoolResult result = await UnresponsiveUntilCancelledAsync(context, nameof(OpenStreamAsync), cts);

            return(new OpenStreamResult(result));
        }
        public async Task <PutResult> PutStreamAsync(Context context, HashType hashType, Stream stream, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal)
        {
            BoolResult result = await UnresponsiveUntilCancelledAsync(context, nameof(PutStreamAsync), cts);

            return(new PutResult(result, new ContentHash(hashType)));
        }
Exemple #23
0
 public virtual void StartupStop(Context context, BoolResult result)
 {
     InitializationFinished(context, result, result.Duration, $"{Name}.Startup stop {result.DurationMs}ms result=[{result}]", nameof(StartupStop));
 }
Exemple #24
0
        /// <inheritdoc />
        public Task <BoolResult> StartupAsync(Context context)
        {
            StartupStarted = true;

            return(StartupCall <CacheTracer> .RunAsync(_tracer, context, async() =>
            {
                var preStartupResult = await PreStartupAsync(context).ConfigureAwait(false);
                if (!preStartupResult.Succeeded)
                {
                    return preStartupResult;
                }

                var contentStoreTask = Task.Run(() => ContentStore.StartupAsync(context));
                var memoizationStoreResult = await MemoizationStore.StartupAsync(context).ConfigureAwait(false);
                var contentStoreResult = await contentStoreTask.ConfigureAwait(false);

                BoolResult result;

                if (!contentStoreResult.Succeeded || !memoizationStoreResult.Succeeded)
                {
                    var sb = new StringBuilder();

                    if (contentStoreResult.Succeeded)
                    {
                        var r = await ContentStore.ShutdownAsync(context).ConfigureAwait(false);
                        if (!r.Succeeded)
                        {
                            sb.AppendFormat($"Content store shutdown failed, error=[{r}]");
                        }
                    }
                    else
                    {
                        sb.AppendFormat($"Content store startup failed, error=[{contentStoreResult}]");
                    }

                    if (memoizationStoreResult.Succeeded)
                    {
                        var r = await MemoizationStore.ShutdownAsync(context).ConfigureAwait(false);
                        if (!r.Succeeded)
                        {
                            sb.Append(sb.Length > 0 ? ", " : string.Empty);
                            sb.AppendFormat($"Memoization store shutdown failed, error=[{memoizationStoreResult}]");
                        }
                    }
                    else
                    {
                        sb.Append(sb.Length > 0 ? ", " : string.Empty);
                        sb.AppendFormat($"Memoization store startup failed, error=[{memoizationStoreResult}]");
                    }

                    result = new BoolResult(sb.ToString());
                }
                else
                {
                    result = BoolResult.Success;
                }

                StartupCompleted = true;
                return result;
            }));
        }
Exemple #25
0
 /// <inheritdoc />
 public void PostInitializationCompleted(Context context, BoolResult result)
 {
     context.Debug($"Setting result for post-initialization completion task to '{result}'.");
     _postInitializationCompletion.TrySetResult(result);
 }
        /// <inheritdoc />
        public Task <BoolResult> StartupAsync(Context context)
        {
            StartupStarted = true;
            return(StartupCall <BuildCacheCacheTracer> .RunAsync(_tracer, context, async() =>
            {
                BoolResult result;

                _tracer.Debug(context, $"Creating ContentHashListAdapterFactory with {nameof(_useBlobContentHashLists)}={_useBlobContentHashLists}");
                _contentHashListAdapterFactory = await ContentHashListAdapterFactory.CreateAsync(
                    context, _buildCacheHttpClientFactory, _useBlobContentHashLists);
                Id =
                    await _contentHashListAdapterFactory.BuildCacheHttpClient.GetBuildCacheServiceDeterminism(_cacheNamespace)
                    .ConfigureAwait(false);

                var backingContentStoreTask = Task.Run(async() => await _backingContentStore.StartupAsync(context).ConfigureAwait(false));
                var writeThroughContentStoreResult = _writeThroughContentStore != null
                    ? await _writeThroughContentStore.StartupAsync(context).ConfigureAwait(false)
                    : BoolResult.Success;
                var backingContentStoreResult = await backingContentStoreTask.ConfigureAwait(false);

                if (backingContentStoreResult.Succeeded && writeThroughContentStoreResult.Succeeded)
                {
                    result = BoolResult.Success;
                }
                else
                {
                    var sb = new StringBuilder();
                    if (backingContentStoreResult.Succeeded)
                    {
                        var r = await _backingContentStore.ShutdownAsync(context).ConfigureAwait(false);
                        if (!r.Succeeded)
                        {
                            sb.Append($"Backing content store shutdown failed, error=[{r}]");
                        }
                    }
                    else
                    {
                        sb.Append($"Backing content store startup failed, error=[{backingContentStoreResult}]");
                    }

                    if (writeThroughContentStoreResult.Succeeded)
                    {
                        var r = _writeThroughContentStore != null
                            ? await _writeThroughContentStore.ShutdownAsync(context).ConfigureAwait(false)
                            : BoolResult.Success;
                        if (!r.Succeeded)
                        {
                            sb.Append(sb.Length > 0 ? ", " : string.Empty);
                            sb.Append($"Write-through content store shutdown failed, error=[{r}]");
                        }
                    }
                    else
                    {
                        sb.Append(sb.Length > 0 ? ", " : string.Empty);
                        sb.Append($"Write-through content store startup failed, error=[{writeThroughContentStoreResult}]");
                    }

                    result = new BoolResult(sb.ToString());
                }

                StartupCompleted = true;
                return result;
            }));
        }
        public async Task MultipleCaches()
        {
            const string CacheName1 = "test1";
            const string CacheName2 = "test2";

            using (var testDirectory0 = new DisposableDirectory(FileSystem))
                using (var testDirectory1 = new DisposableDirectory(FileSystem))
                    using (var testDirectory2 = new DisposableDirectory(FileSystem))
                    {
                        var config = CreateStoreConfiguration();

                        var rootPath1 = testDirectory1.Path;
                        config.Write(FileSystem, rootPath1);

                        var rootPath2 = testDirectory2.Path;
                        config.Write(FileSystem, rootPath2);

                        var grpcPort         = PortExtensions.GetNextAvailablePort();
                        var grpcPortFileName = Guid.NewGuid().ToString();

                        var serviceConfiguration = new ServiceConfiguration(
                            new Dictionary <string, AbsolutePath> {
                            { CacheName1, rootPath1 }, { CacheName2, rootPath2 }
                        },
                            testDirectory0.Path,
                            ServiceConfiguration.DefaultGracefulShutdownSeconds,
                            grpcPort,
                            grpcPortFileName);

                        using (var server = CreateServer(serviceConfiguration))
                        {
                            var factory   = new MemoryMappedFileGrpcPortSharingFactory(Logger, grpcPortFileName);
                            var reader    = factory.GetPortReader();
                            var port      = reader.ReadPort();
                            var rpcConfig = new ServiceClientRpcConfiguration(port);

                            using (var store1 = new ServiceClientContentStore(
                                       Logger,
                                       FileSystem,
                                       new ServiceClientContentStoreConfiguration(CacheName1, rpcConfig, Scenario)))
                                using (var store2 = new ServiceClientContentStore(
                                           Logger,
                                           FileSystem,
                                           new ServiceClientContentStoreConfiguration(CacheName2, rpcConfig, Scenario)))
                                {
                                    try
                                    {
                                        var rs = await server.StartupAsync(_context);

                                        rs.ShouldBeSuccess();

                                        var storeBoolResult1 = await store1.StartupAsync(_context);

                                        storeBoolResult1.ShouldBeSuccess();

                                        var storeBoolResult2 = await store2.StartupAsync(_context);

                                        storeBoolResult2.ShouldBeSuccess();

                                        IContentSession session1 = null;
                                        IContentSession session2 = null;

                                        try
                                        {
                                            var createSessionResult1 = store1.CreateSession(_context, "session1", ImplicitPin.None);
                                            createSessionResult1.ShouldBeSuccess();

                                            var createSessionResult2 = store2.CreateSession(_context, "session2", ImplicitPin.None);
                                            createSessionResult2.ShouldBeSuccess();

                                            using (createSessionResult1.Session)
                                                using (createSessionResult2.Session)
                                                {
                                                    var r1 = await createSessionResult1.Session.StartupAsync(_context);

                                                    r1.ShouldBeSuccess();
                                                    session1 = createSessionResult1.Session;

                                                    var r2 = await createSessionResult2.Session.StartupAsync(_context);

                                                    r2.ShouldBeSuccess();
                                                    session2 = createSessionResult2.Session;

                                                    var r3 = await session1.PutRandomAsync(
                                                        _context,
                                                        ContentHashType,
                                                        false,
                                                        RandomContentByteCount,
                                                        Token);

                                                    var pinResult = await session1.PinAsync(_context, r3.ContentHash, Token);

                                                    pinResult.ShouldBeSuccess();

                                                    r3 = await session2.PutRandomAsync(
                                                        _context,
                                                        ContentHashType,
                                                        false,
                                                        RandomContentByteCount,
                                                        Token);

                                                    pinResult = await session2.PinAsync(_context, r3.ContentHash, Token);

                                                    pinResult.ShouldBeSuccess();
                                                }
                                        }
                                        finally
                                        {
                                            if (session2 != null)
                                            {
                                                await session2.ShutdownAsync(_context).ShouldBeSuccess();
                                            }

                                            if (session1 != null)
                                            {
                                                await session1.ShutdownAsync(_context).ShouldBeSuccess();
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        BoolResult r1 = null;
                                        BoolResult r2 = null;

                                        if (store1.StartupCompleted)
                                        {
                                            r1 = await store1.ShutdownAsync(_context);
                                        }

                                        if (store2.StartupCompleted)
                                        {
                                            r2 = await store2.ShutdownAsync(_context);
                                        }

                                        var r3 = await server.ShutdownAsync(_context);

                                        r1?.ShouldBeSuccess();
                                        r2?.ShouldBeSuccess();
                                        r3?.ShouldBeSuccess();
                                    }
                                }
                        }
                    }
        }
Exemple #28
0
 public void PostInitializationCompleted(Context context, BoolResult result) => _local.PostInitializationCompleted(context, result);
        public async Task <IEnumerable <Task <Indexed <PinResult> > > > PinAsync(Context context, IReadOnlyList <ContentHash> contentHashes, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal)
        {
            BoolResult result = await UnresponsiveUntilCancelledAsync(context, nameof(PinAsync), cts);

            return(contentHashes.Select(hashWithPath => new PinResult(result)).AsIndexed().AsTasks());
        }
Exemple #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response">response value arrive from exchange's server</param>
        /// <returns></returns>
        public override BoolResult GetResponseMessage(IRestResponse response = null)
        {
            var _result = new BoolResult();

            if (response != null)
            {
                if (response.IsSuccessful == false) // (int) StatusCode >= 200 && (int) StatusCode <= 299 && ResponseStatus == ResponseStatus.Completed;
                {
                    if ((int)response.StatusCode != 429)
                    {
                        if (String.IsNullOrEmpty(response.Content) == false && response.Content[0] == '{')
                        {
                            var _json_result = this.DeserializeObject <JToken>(response.Content);

                            var _json_error = _json_result.SelectToken("error");
                            if (_json_error != null)
                            {
                                var _json_message = _json_error.SelectToken("message");
                                if (_json_message != null)
                                {
                                    var _error_code = ErrorCode.ExchangeError;

                                    var _error_msg = _json_message.Value <string>();
                                    if (String.IsNullOrEmpty(_error_msg) == false)
                                    {
                                        if (ErrorMessages.ContainsKey(_error_msg) == true)
                                        {
                                            _error_code = ErrorMessages[_error_msg];
                                        }
                                    }
                                    else
                                    {
                                        _error_msg = response.Content;
                                    }

                                    _result.SetFailure(_error_msg, _error_code);
                                }
                            }
                        }
                    }
                    else
                    {
                        _result.SetFailure(
                            response.ErrorMessage ?? response.StatusDescription,
                            ErrorCode.DDoSProtection,
                            (int)response.StatusCode,
                            false
                            );
                    }
                }

                if (_result.success == true && response.IsSuccessful == false)
                {
                    _result.SetFailure(
                        response.ErrorMessage ?? response.StatusDescription,
                        ErrorCode.ResponseRestError,
                        (int)response.StatusCode,
                        false
                        );
                }
            }

            return(_result);
        }
Exemple #31
0
 public virtual void ShutdownStop(Context context, BoolResult result)
 {
     TracerOperationFinished(context, result, $"{Name}.Shutdown stop {result.DurationMs}ms result=[{result}]");
 }