Esempio n. 1
0
        private async Task IndexEntries(QueryOperationContext queryContext, OperationCancelToken token, RequestTimeTracker tracker, HttpMethod method, bool ignoreLimit)
        {
            var indexQuery = await GetIndexQuery(queryContext.Documents, method, tracker);

            var existingResultEtag = GetLongFromHeaders("If-None-Match");

            var result = await Database.QueryRunner.ExecuteIndexEntriesQuery(indexQuery, queryContext, ignoreLimit, existingResultEtag, token);

            if (result.NotModified)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.NotModified;
                return;
            }

            HttpContext.Response.Headers[Constants.Headers.Etag] = CharExtensions.ToInvariantString(result.ResultEtag);

            await using (var writer = new AsyncBlittableJsonTextWriter(queryContext.Documents, ResponseBodyStream()))
            {
                await writer.WriteIndexEntriesQueryResultAsync(queryContext.Documents, result, token.Token);
            }
        }
Esempio n. 2
0
        public async Task Exists()
        {
            var hash = GetStringQueryString("hash");

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                using (context.OpenReadTransaction())
                    using (Slice.From(context.Allocator, hash, out var hashSlice))
                    {
                        var count = AttachmentsStorage.GetCountOfAttachmentsForHash(context, hashSlice);
                        await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                        {
                            writer.WriteStartObject();
                            writer.WritePropertyName("Hash");
                            writer.WriteString(hash);
                            writer.WriteComma();
                            writer.WritePropertyName("Count");
                            writer.WriteInteger(count);
                            writer.WriteEndObject();
                        }
                    }
        }
Esempio n. 3
0
            public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
            {
                url = $"{node.Url}/admin/certificates/replace-cluster-cert?replaceImmediately={_replaceImmediately}";

                var request = new HttpRequestMessage
                {
                    Method  = HttpMethod.Post,
                    Content = new BlittableJsonContent(async stream =>
                    {
                        await using (var writer = new AsyncBlittableJsonTextWriter(ctx, stream))
                        {
                            writer.WriteStartObject();
                            writer.WritePropertyName(nameof(CertificateDefinition.Certificate));
                            writer.WriteString(Convert.ToBase64String(_certBytes)); // keep the private key -> this is a server cert
                            writer.WriteEndObject();
                        }
                    })
                };

                return(request);
            }
Esempio n. 4
0
 public async Task ListRemoteConnections()
 {
     using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context))
         await using (var write = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
         {
             context.Write(write,
                           new DynamicJsonValue
             {
                 ["Remote-Connections"] = new DynamicJsonArray(RemoteConnection.RemoteConnectionsList
                                                               .Select(connection => new DynamicJsonValue
                 {
                     [nameof(RemoteConnection.RemoteConnectionInfo.Caller)]      = connection.Caller,
                     [nameof(RemoteConnection.RemoteConnectionInfo.Term)]        = connection.Term,
                     [nameof(RemoteConnection.RemoteConnectionInfo.Destination)] = connection.Destination,
                     [nameof(RemoteConnection.RemoteConnectionInfo.StartAt)]     = connection.StartAt,
                     ["Duration"] = DateTime.UtcNow - connection.StartAt,
                     [nameof(RemoteConnection.RemoteConnectionInfo.Number)] = connection.Number,
                 }))
             });
         }
 }
Esempio n. 5
0
        private async Task Explain(DocumentsOperationContext context, RequestTimeTracker tracker, HttpMethod method)
        {
            var indexQuery = await GetIndexQuery(context, method, tracker);

            var explanations = Database.QueryRunner.ExplainDynamicIndexSelection(indexQuery, out string indexName);

            using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream(), Database.DatabaseShutdown))
            {
                writer.WriteStartObject();
                writer.WritePropertyName("IndexName");
                writer.WriteString(indexName);
                writer.WriteComma();
                writer.WriteArray(context, "Results", explanations, (w, c, explanation) =>
                {
                    w.WriteExplanation(context, explanation);
                });

                writer.WriteEndObject();
                await writer.OuterFlushAsync();
            }
        }
Esempio n. 6
0
        public async Task GetConfiguration()
        {
            using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    var djv = new DynamicJsonValue
                    {
                        [nameof(GetLogsConfigurationResult.CurrentMode)]   = LoggingSource.Instance.LogMode,
                        [nameof(GetLogsConfigurationResult.Mode)]          = ServerStore.Configuration.Logs.Mode,
                        [nameof(GetLogsConfigurationResult.Path)]          = ServerStore.Configuration.Logs.Path.FullPath,
                        [nameof(GetLogsConfigurationResult.UseUtcTime)]    = ServerStore.Configuration.Logs.UseUtcTime,
                        [nameof(GetLogsConfigurationResult.RetentionTime)] = LoggingSource.Instance.RetentionTime,
                        [nameof(GetLogsConfigurationResult.RetentionSize)] = LoggingSource.Instance.RetentionSize == long.MaxValue ? null : (object)LoggingSource.Instance.RetentionSize,
                        [nameof(GetLogsConfigurationResult.Compress)]      = LoggingSource.Instance.Compressing
                    };

                    var json = context.ReadObject(djv, "logs/configuration");

                    writer.WriteObject(json);
                }
        }
        private async Task GetTaskConfigurationsAsync <T>(OngoingTaskType type, Func <BlittableJsonReaderObject, T> converter)
            where T : IDynamicJsonValueConvertible
        {
            var taskName = GetStringQueryString("name", required: false);

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (context.OpenReadTransaction())
                    await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                    {
                        var blittables = ServerStore.Cluster.GetServerWideConfigurations(context, type, taskName);
                        var result     = new ServerWideTasksResult <T>();

                        foreach (var blittable in blittables)
                        {
                            var configuration = converter(blittable);
                            result.Results.Add(configuration);
                        }

                        context.Write(writer, result.ToJson());
                    }
        }
Esempio n. 8
0
        public async Task GetStudioConfiguration()
        {
            var configuration = Database.StudioConfiguration;

            if (configuration == null)
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                var val = configuration.ToJson();
                var clientConfigurationJson = context.ReadObject(val, Constants.Configuration.StudioId);

                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteObject(clientConfigurationJson);
                }
            }
        }
Esempio n. 9
0
        private void WriteHeaders(AsyncBlittableJsonTextWriter writer, HttpContext httpContext, LazyStringValue headersProperty)
        {
            writer.WritePropertyName(headersProperty);
            writer.WriteStartObject();
            bool headerStart = true;

            foreach (var header in httpContext.Response.Headers)
            {
                foreach (var value in header.Value)
                {
                    if (headerStart == false)
                    {
                        writer.WriteComma();
                    }
                    headerStart = false;
                    writer.WritePropertyName(header.Key);
                    writer.WriteString(value);
                }
            }
            writer.WriteEndObject();
        }
        public async Task Allocations()
        {
            var delay = GetIntValueQueryString("delay", required: false) ?? 5;

            IReadOnlyCollection <AllocationInfo> allocations;

            using (var listener = new Expensive_GcEventListener())
            {
                await Task.Delay(TimeSpan.FromSeconds(delay));

                allocations = listener.Allocations;
            }

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();

                    var first = true;
                    foreach (var alloc in allocations.OrderByDescending(x => x.Allocations))
                    {
                        if (first == false)
                        {
                            writer.WriteComma();
                        }

                        first = false;
                        writer.WritePropertyName(alloc.Type);
                        writer.WriteStartObject();
                        writer.WritePropertyName("Memory");
                        writer.WriteString(new Size((long)alloc.Allocations, SizeUnit.Bytes).ToString());
                        writer.WriteComma();
                        writer.WritePropertyName("Allocations");
                        writer.WriteInteger(alloc.NumberOfAllocations);
                        writer.WriteEndObject();
                    }

                    writer.WriteEndObject();
                }
        }
Esempio n. 11
0
        public static async Task SendDatabaseRecord(string name, ServerStore serverStore, HttpContext httpContext, Stream responseBodyStream)
        {
            using (serverStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
            {
                var dbId = Constants.Documents.Prefix + name;
                using (context.OpenReadTransaction())
                    using (var dbDoc = serverStore.Cluster.Read(context, dbId, out long etag))
                    {
                        if (dbDoc == null)
                        {
                            httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                            httpContext.Response.Headers["Database-Missing"] = name;
                            await using (var writer = new AsyncBlittableJsonTextWriter(context, responseBodyStream))
                            {
                                context.Write(writer,
                                              new DynamicJsonValue
                                {
                                    ["Type"]    = "Error",
                                    ["Message"] = "Database " + name + " wasn't found"
                                });
                            }

                            return;
                        }

                        await using (var writer = new AsyncBlittableJsonTextWriter(context, responseBodyStream))
                        {
                            writer.WriteStartObject();
                            writer.WriteDocumentPropertiesWithoutMetadata(context, new Document
                            {
                                Data = dbDoc
                            });
                            writer.WriteComma();
                            writer.WritePropertyName("Etag");
                            writer.WriteInteger(etag);
                            writer.WriteEndObject();
                        }
                    }
            }
        }
        public static async Task TrySavingAsync(string topologyHash, ClusterTopologyResponse clusterTopology, DocumentConventions conventions, JsonOperationContext context, CancellationToken token)
        {
            try
            {
                if (conventions.DisableTopologyCache)
                {
                    return;
                }

                var path = GetPath(topologyHash, conventions);
                if (clusterTopology == null)
                {
                    Clear(path);
                    return;
                }

                using (var stream = SafeFileStream.Create(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                    await using (var writer = new AsyncBlittableJsonTextWriter(context, stream))
                    {
                        var json = new DynamicJsonValue
                        {
                            [nameof(clusterTopology.Topology)] = clusterTopology.Topology.ToJson(),
                            [nameof(clusterTopology.Leader)]   = clusterTopology.Leader,
                            [nameof(clusterTopology.NodeTag)]  = clusterTopology.NodeTag,
                            [nameof(clusterTopology.Etag)]     = clusterTopology.Etag,
                            ["PersistedAt"] = DateTimeOffset.UtcNow.ToString(DefaultFormat.DateTimeOffsetFormatsToWrite),
                        };

                        context.Write(writer, json);
                        await writer.FlushAsync(token).ConfigureAwait(false);
                    }
            }
            catch (Exception e)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Could not persist the cluster topology", e);
                }
            }
        }
Esempio n. 13
0
            public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
            {
                var path = new StringBuilder(node.Url)
                           .Append("/databases/")
                           .Append(node.Database)
                           .Append("/queries")
                           .Append("?allowStale=")
                           .Append(_options.AllowStale)
                           .Append("&maxOpsPerSec=")
                           .Append(_options.MaxOpsPerSecond)
                           .Append("&details=")
                           .Append(_options.RetrieveDetails);

                if (_options.StaleTimeout != null)
                {
                    path
                    .Append("&staleTimeout=")
                    .Append(_options.StaleTimeout.Value);
                }

                var request = new HttpRequestMessage
                {
                    Method  = HttpMethods.Patch,
                    Content = new BlittableJsonContent(async stream =>
                    {
                        await using (var writer = new AsyncBlittableJsonTextWriter(ctx, stream))
                        {
                            writer.WriteStartObject();

                            writer.WritePropertyName("Query");
                            writer.WriteIndexQuery(_conventions, ctx, _queryToUpdate);

                            writer.WriteEndObject();
                        }
                    })
                };

                url = path.ToString();
                return(request);
            }
Esempio n. 14
0
        private static async Task WriteForDatabase(ZipArchive archive, JsonOperationContext context, LocalEndpointClient localEndpointClient, string databaseName, string path = null, CancellationToken token = default)
        {
            token.ThrowIfCancellationRequested();

            var endpointParameters = new Dictionary <string, Microsoft.Extensions.Primitives.StringValues>
            {
                { "database", new Microsoft.Extensions.Primitives.StringValues(databaseName) }
            };

            foreach (var route in DebugInfoPackageUtils.Routes.Where(x => x.TypeOfRoute == RouteInformation.RouteType.Databases))
            {
                token.ThrowIfCancellationRequested();

                try
                {
                    var entry = archive.CreateEntry(DebugInfoPackageUtils.GetOutputPathFromRouteInformation(route, path ?? databaseName));
                    entry.ExternalAttributes = ((int)(FilePermissions.S_IRUSR | FilePermissions.S_IWUSR)) << 16;

                    await using (var entryStream = entry.Open())
                        await using (var writer = new AsyncBlittableJsonTextWriter(context, entryStream))
                        {
                            using (var endpointOutput = await localEndpointClient.InvokeAndReadObjectAsync(route, context, endpointParameters))
                            {
                                context.Write(writer, endpointOutput);
                                await writer.FlushAsync();

                                await entryStream.FlushAsync(token);
                            }
                        }
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    await DebugInfoPackageUtils.WriteExceptionAsZipEntryAsync(e, archive, path ?? databaseName);
                }
            }
        }
Esempio n. 15
0
        public Task RunningQueries()
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream(), Database.DatabaseShutdown))
                {
                    writer.WriteStartObject();

                    var isFirst = true;
                    foreach (var group in Database.QueryRunner.CurrentlyRunningQueries.GroupBy(x => x.IndexName))
                    {
                        if (isFirst == false)
                        {
                            writer.WriteComma();
                        }
                        isFirst = false;

                        writer.WritePropertyName(group.Key);
                        writer.WriteStartArray();

                        var isFirstInternal = true;
                        foreach (var query in group)
                        {
                            if (isFirstInternal == false)
                            {
                                writer.WriteComma();
                            }

                            isFirstInternal = false;

                            query.Write(writer, context);
                        }

                        writer.WriteEndArray();
                    }

                    writer.WriteEndObject();
                }

            return(Task.CompletedTask);
        }
Esempio n. 16
0
        private async Task GetConflictsByEtag(long etag)
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                    using (context.OpenReadTransaction())
                    {
                        var skip     = GetStart();
                        var pageSize = GetPageSize();

                        var alreadyAdded = new HashSet <LazyStringValue>(LazyStringValueComparer.Instance);
                        var array        = new DynamicJsonArray();
                        var conflicts    = Database.DocumentsStorage.ConflictsStorage.GetConflictsAfter(context, etag);
                        foreach (var conflict in conflicts)
                        {
                            if (alreadyAdded.Add(conflict.Id))
                            {
                                if (skip > 0)
                                {
                                    skip--;
                                    continue;
                                }
                                if (pageSize-- <= 0)
                                {
                                    break;
                                }
                                array.Add(new DynamicJsonValue
                                {
                                    [nameof(GetConflictsResult.Id)] = conflict.Id,
                                    [nameof(GetConflictsResult.Conflict.LastModified)] = conflict.LastModified
                                });
                            }
                        }

                        context.Write(writer, new DynamicJsonValue
                        {
                            ["TotalResults"] = Database.DocumentsStorage.ConflictsStorage.GetNumberOfDocumentsConflicts(context),
                            [nameof(GetConflictsResult.Results)] = array
                        });
                    }
        }
Esempio n. 17
0
        private async Task ExecuteQueryOperation(IndexQueryServerSide query,
                                                 Func <QueryRunner,
                                                       QueryOperationOptions,
                                                       Action <IOperationProgress>, OperationCancelToken,
                                                       Task <IOperationResult> > operation,
                                                 IDisposable returnContextToPool,
                                                 Operations.Operations.OperationType operationType)
        {
            var options = GetQueryOperationOptions();
            var token   = CreateTimeLimitedQueryOperationToken();

            var operationId = Database.Operations.GetNextOperationId();

            var indexName = query.Metadata.IsDynamic
                ? (query.Metadata.IsCollectionQuery ? "collection/" : "dynamic/") + query.Metadata.CollectionName
                : query.Metadata.IndexName;

            var details = new BulkOperationResult.OperationDetails
            {
                Query = query.Query
            };

            var task = Database.Operations.AddOperation(
                Database,
                indexName,
                operationType,
                onProgress => operation(Database.QueryRunner, options, onProgress, token), operationId, details, token);

            using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteOperationIdAndNodeTag(context, operationId, ServerStore.NodeTag);
                }

            _ = task.ContinueWith(_ =>
            {
                using (returnContextToPool)
                    token.Dispose();
            });
        }
Esempio n. 18
0
        public async Task NextIdentityFor()
        {
            var name = GetQueryStringValueAndAssertIfSingleAndNotEmpty("name");

            if (name[name.Length - 1] != '|')
            {
                name += '|';
            }

            var(_, _, newIdentityValue) = await Database.ServerStore.GenerateClusterIdentityAsync(name, Database.IdentityPartsSeparator, Database.Name, GetRaftRequestIdFromQuery());

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("NewIdentityValue");
                    writer.WriteInteger(newIdentityValue);

                    writer.WriteEndObject();
                }
        }
Esempio n. 19
0
        public async Task GetTestSqlConnection()
        {
            try
            {
                var factoryName      = GetStringQueryString("factoryName");
                var connectionString = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                RelationalDatabaseWriter.TestConnection(factoryName, connectionString);

                DynamicJsonValue result = new DynamicJsonValue
                {
                    [nameof(NodeConnectionTestResult.Success)] = true,
                };

                using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
                    await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                    {
                        context.Write(writer, result);
                    }
            }
            catch (Exception ex)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Error occurred during sql replication connection test", ex);
                }

                using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
                {
                    await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                    {
                        context.Write(writer, new DynamicJsonValue
                        {
                            [nameof(NodeConnectionTestResult.Success)] = false,
                            [nameof(NodeConnectionTestResult.Error)]   = ex.ToString()
                        });
                    }
                }
            }
        }
Esempio n. 20
0
 private static void WriteAttachmentDetails(AsyncBlittableJsonTextWriter writer, Attachment attachment, string documentId)
 {
     writer.WriteStartObject();
     writer.WritePropertyName(nameof(AttachmentDetails.Name));
     writer.WriteString(attachment.Name);
     writer.WriteComma();
     writer.WritePropertyName(nameof(AttachmentDetails.Hash));
     writer.WriteString(attachment.Base64Hash.ToString());
     writer.WriteComma();
     writer.WritePropertyName(nameof(AttachmentDetails.ContentType));
     writer.WriteString(attachment.ContentType);
     writer.WriteComma();
     writer.WritePropertyName(nameof(AttachmentDetails.Size));
     writer.WriteInteger(attachment.Size);
     writer.WriteComma();
     writer.WritePropertyName(nameof(AttachmentDetails.ChangeVector));
     writer.WriteString(attachment.ChangeVector);
     writer.WriteComma();
     writer.WritePropertyName(nameof(AttachmentDetails.DocumentId));
     writer.WriteString(documentId);
     writer.WriteEndObject();
 }
        private static void WriteNode(AsyncBlittableJsonTextWriter writer, ServerNode node, JsonOperationContext context)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(context.GetLazyString(nameof(ServerNode.Url)));
            writer.WriteString(context.GetLazyString(node.Url));

            writer.WriteComma();
            writer.WritePropertyName(context.GetLazyString(nameof(ServerNode.Database)));
            writer.WriteString(context.GetLazyString(node.Database));

            // ClusterTag and ServerRole included for debugging purpose only
            writer.WriteComma();
            writer.WritePropertyName(context.GetLazyString(nameof(ServerNode.ClusterTag)));
            writer.WriteString(context.GetLazyString(node.ClusterTag));

            writer.WriteComma();
            writer.WritePropertyName(context.GetLazyString(nameof(ServerNode.ServerRole)));
            writer.WriteString(context.GetLazyString(node.ServerRole.ToString()));

            writer.WriteEndObject();
        }
Esempio n. 22
0
        public async Task DetailedStats()
        {
            using (var context = QueryOperationContext.Allocate(Database, needsServerContext: true))
                using (context.OpenReadTransaction())
                {
                    var stats = new DetailedDatabaseStatistics();

                    FillDatabaseStatistics(stats, context);

                    stats.CountOfTimeSeriesDeletedRanges = Database.DocumentsStorage.TimeSeriesStorage.GetNumberOfTimeSeriesDeletedRanges(context.Documents);
                    using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext serverContext))
                        using (serverContext.OpenReadTransaction())
                        {
                            stats.CountOfIdentities                = ServerStore.Cluster.GetNumberOfIdentities(serverContext, Database.Name);
                            stats.CountOfCompareExchange           = ServerStore.Cluster.GetNumberOfCompareExchange(serverContext, Database.Name);
                            stats.CountOfCompareExchangeTombstones = ServerStore.Cluster.GetNumberOfCompareExchangeTombstones(serverContext, Database.Name);
                        }

                    await using (var writer = new AsyncBlittableJsonTextWriter(context.Documents, ResponseBodyStream()))
                        writer.WriteDetailedDatabaseStatistics(context.Documents, stats);
                }
        }
Esempio n. 23
0
        private static void WriteRange(AsyncBlittableJsonTextWriter writer, TimeSeriesRangeResult rangeResult, long?totalCount)
        {
            writer.WriteStartObject();
            {
                writer.WritePropertyName(nameof(TimeSeriesRangeResult.From));
                if (rangeResult.From == DateTime.MinValue)
                {
                    writer.WriteNull();
                }
                else
                {
                    writer.WriteDateTime(rangeResult.From, true);
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(TimeSeriesRangeResult.To));
                if (rangeResult.To == DateTime.MaxValue)
                {
                    writer.WriteNull();
                }
                else
                {
                    writer.WriteDateTime(rangeResult.To, true);
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(TimeSeriesRangeResult.Entries));
                WriteEntries(writer, rangeResult.Entries);

                if (totalCount.HasValue)
                {
                    // add total entries count to the response
                    writer.WriteComma();
                    writer.WritePropertyName(nameof(TimeSeriesRangeResult.TotalResults));
                    writer.WriteInteger(totalCount.Value);
                }
            }
            writer.WriteEndObject();
        }
Esempio n. 24
0
        public async Task GetReplicationReconnectionQueue()
        {
            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    var data = new DynamicJsonArray();
                    foreach (var queueItem in Database.ReplicationLoader.ReconnectQueue)
                    {
                        data.Add(new DynamicJsonValue
                        {
                            ["Url"]      = queueItem.Url,
                            ["Database"] = queueItem.Database,
                            ["Disabled"] = queueItem.Disabled
                        });
                    }

                    context.Write(writer, new DynamicJsonValue
                    {
                        ["Queue-Info"] = data
                    });
                }
        }
Esempio n. 25
0
        public async Task GetStats()
        {
            var etlStats = GetProcessesToReportOn().Select(x => new EtlTaskStats
            {
                TaskName = x.Key,
                Stats    = x.Value.Select(y => new EtlProcessTransformationStats
                {
                    TransformationName = y.TransformationName,
                    Statistics         = y.Statistics
                }).ToArray()
            }).ToArray();

            using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();
                    writer.WriteArray(context, "Results", etlStats, (w, c, stats) => w.WriteObject(context.ReadObject(stats.ToJson(), "etl/stats")));
                    writer.WriteEndObject();
                }
            }
        }
Esempio n. 26
0
        public async Task GetPeriodicBackupStatus()
        {
            var name = GetQueryStringValueAndAssertIfSingleAndNotEmpty("name");

            if (await CanAccessDatabaseAsync(name, requireAdmin: false, requireWrite: false) == false)
            {
                return;
            }

            var taskId = GetLongQueryString("taskId", required: true);

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (context.OpenReadTransaction())
                    using (var statusBlittable = ServerStore.Cluster.Read(context, PeriodicBackupStatus.GenerateItemName(name, taskId.Value)))
                        await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                        {
                            writer.WriteStartObject();
                            writer.WritePropertyName(nameof(GetPeriodicBackupStatusOperationResult.Status));
                            writer.WriteObject(statusBlittable);
                            writer.WriteEndObject();
                        }
        }
Esempio n. 27
0
        public async Task TxInfo()
        {
            var results = new List <TransactionDebugHandler.TransactionInfo>();

            var env    = Server.ServerStore._env;
            var txInfo = new TransactionDebugHandler.TransactionInfo
            {
                Path        = env.Options.BasePath.FullPath,
                Information = env.ActiveTransactions.AllTransactionsInstances
            };

            results.Add(txInfo);

            using (Server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context))
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    context.Write(writer, new DynamicJsonValue
                    {
                        ["tx-info"] = TransactionDebugHandler.ToJson(results)
                    });
                }
        }
Esempio n. 28
0
        public async Task Stream()
        {
            var documentId = GetStringQueryString("docId");
            var name = GetStringQueryString("name");
            var fromStr = GetStringQueryString("from", required: false);
            var toStr = GetStringQueryString("to", required: false);
            var offset = GetTimeSpanQueryString("offset", required: false);

            var from = string.IsNullOrEmpty(fromStr) 
                ? DateTime.MinValue 
                : TimeSeriesHandler.ParseDate(fromStr, name);

            var to = string.IsNullOrEmpty(toStr)
                ? DateTime.MaxValue
                : TimeSeriesHandler.ParseDate(toStr, name);

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            using (context.OpenReadTransaction())
            {
                var reader = new TimeSeriesReader(context, documentId, name, from, to, offset);

                using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream(), Database.DatabaseShutdown))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("Results");
                    writer.WriteStartArray();
                    foreach (var entry in reader.AllValues())
                    {
                        context.Write(writer, entry.ToTimeSeriesEntryJson());
                        writer.WriteComma();
                        await writer.MaybeOuterFlushAsync();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();

                    await writer.MaybeOuterFlushAsync();
                }
            }
        }
Esempio n. 29
0
        public async Task GetSettings()
        {
            ConfigurationEntryScope?scope = null;
            var scopeAsString             = GetStringQueryString("scope", required: false);

            if (scopeAsString != null)
            {
                if (Enum.TryParse <ConfigurationEntryScope>(scopeAsString, ignoreCase: true, out var value) == false)
                {
                    throw new BadRequestException($"Could not parse '{scopeAsString}' to a valid configuration entry scope.");
                }

                scope = value;
            }

            var feature = HttpContext.Features.Get <IHttpAuthenticationFeature>() as RavenServer.AuthenticateConnection;
            var status  = feature?.Status ?? RavenServer.AuthenticationStatus.ClusterAdmin;

            var settingsResult = new SettingsResult();

            foreach (var configurationEntryMetadata in RavenConfiguration.AllConfigurationEntries.Value)
            {
                if (scope.HasValue && scope != configurationEntryMetadata.Scope)
                {
                    continue;
                }

                var entry = new ConfigurationEntryServerValue(Server.Configuration.Settings, configurationEntryMetadata, status);
                settingsResult.Settings.Add(entry);
            }

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
            {
                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    context.Write(writer, settingsResult.ToJson());
                }
            }
        }
Esempio n. 30
0
        public async Task Get()
        {
            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
            {
                Dictionary <string, SorterDefinition> sorters;
                using (context.OpenReadTransaction())
                {
                    var rawRecord = Server.ServerStore.Cluster.ReadRawDatabaseRecord(context, Database.Name);
                    sorters = rawRecord?.Sorters;
                }

                if (sorters == null)
                {
                    sorters = new Dictionary <string, SorterDefinition>();
                }

                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();

                    writer.WriteArray(context, "Sorters", sorters.Values, (w, c, sorter) =>
                    {
                        w.WriteStartObject();

                        w.WritePropertyName(nameof(SorterDefinition.Name));
                        w.WriteString(sorter.Name);
                        w.WriteComma();

                        w.WritePropertyName(nameof(SorterDefinition.Code));
                        w.WriteString(sorter.Code);

                        w.WriteEndObject();
                    });

                    writer.WriteEndObject();
                }
            }
        }