Example #1
0
        public MetricsModule()
            : base(Config.ModulePath ?? "/")
        {
            if (string.IsNullOrEmpty(Config.ModulePath))
            {
                return;
            }

            if (Config.ModuleConfigAction != null)
            {
                Config.ModuleConfigAction(this);
            }

            Get["/"] = _ =>
            {
                if (this.Request.Url.Path.EndsWith("/"))
                {
                    return(Response.AsText(FlotWebApp.GetFlotApp(), "text/html"));
                }
                else
                {
                    return(Response.AsRedirect(this.Request.Url.ToString() + "/"));
                }
            };
            Get["/text"]   = _ => Response.AsText(GetAsHumanReadable());
            Get["/json"]   = _ => Response.AsText(RegistrySerializer.GetAsJson(Config.Registry), "text/json");
            Get["/ping"]   = _ => Response.AsText("pong", "text/plain");
            Get["/health"] = _ => GetHealthStatus();
        }
Example #2
0
 public void WriteRegistries()
 {
     using (var streamReader = new StreamReader(RegistryFile))
     {
         string line;
         while (!string.IsNullOrWhiteSpace(line = streamReader.ReadLine()))
         {
             WriteRegistry(RegistrySerializer.DeserializeDataRegistry(line));
         }
     }
 }
 private static void WriteTextMetrics(HttpListenerContext context, MetricsRegistry registry, Func <HealthStatus> healthStatus)
 {
     context.Response.ContentType       = "text/plain";
     context.Response.StatusCode        = 200;
     context.Response.StatusDescription = "OK";
     using (var writer = new StreamWriter(context.Response.OutputStream))
     {
         writer.Write(RegistrySerializer.GetAsHumanReadable(registry, healthStatus));
     }
     context.Response.Close();
 }
        private DataRegistry SearchInDataFile(int directIndex, int registryNumber)
        {
            using (var dataStreamReader = new StreamReader(base.RegistryFile))
            {
                dataStreamReader.BaseStream.Seek((directIndex - 1) * _dataRegistrySize, SeekOrigin.Begin);

                var registry = RegistrySerializer.DeserializeDADataRegistry(dataStreamReader.ReadLine());
            }

            return(new DataRegistry()
            {
                Id = registryNumber
            });
        }
        private static void WriteJsonMetrics(HttpListenerContext context, MetricsRegistry registry)
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            context.Response.ContentType       = "application/json";
            context.Response.StatusCode        = 200;
            context.Response.StatusDescription = "OK";
            var json = RegistrySerializer.GetAsJson(registry);

            using (var writer = new StreamWriter(context.Response.OutputStream))
            {
                writer.Write(json);
            }
            context.Response.Close();
        }
Example #6
0
        private DataRegistry BinarySearchInIndexFile(int id)
        {
            IndexRegistry indexRegistry = null;

            using (var stream = File.OpenRead(IndexFile))
            {
                indexRegistry = BinarySearch(stream, id, 0, (int)stream.Length / _indexRegistrySize, _indexRegistrySize, RegistrySerializer.DeserializeIndexRegistry);
            }

            if (indexRegistry == null)
            {
                return(null);
            }

            using (var dataStreamReader = new StreamReader(base.RegistryFile))
            {
                dataStreamReader.BaseStream.Seek((indexRegistry.DataIndex - 1) * _dataRegistrySize, SeekOrigin.Begin);

                return(RegistrySerializer.DeserializeDataRegistry(dataStreamReader.ReadLine()));
            }
        }
Example #7
0
        private async Task ExecuteAsync(PublishArguments args)
        {
            Controller.HealthCheck();

            Registry registry;

            if (args.Registry != null)
            {
                if (args.Registry.Name != "index.json")
                {
                    throw new UserInputException("Please specify the path to your locally cloned index.json file");
                }

                registry = await Controller.GetRegistryAsync(args.Registry.FullName);
            }
            else
            {
                registry = await Controller.GetRegistryAsync();
            }

            var name = args.PackageName ?? (args.Quiet ? "unnamed" : Renderer.Ask("Package Name: ", false, RegistryPackage.ValidNameRegex, "my-package"));

            var package = registry.GetOrCreatePackage(name);
            var version = package.CreateVersion();

            var pathOrUrls = args.Input;

            if (!args.Quiet && (pathOrUrls == null || pathOrUrls.Length == 0))
            {
                Renderer.WriteLine("No files were provided; please enter each file, folder or url. When done, enter an empty line.");
                var fileInputs = new List <string>();
                var empty      = false;
                var counter    = 1;
                do
                {
                    var line = Renderer.Ask($"File/Folder/Url {counter++}: ");
                    empty = string.IsNullOrWhiteSpace(line);
                    if (!empty)
                    {
                        fileInputs.Add(line.Trim());
                    }
                }while (!empty);
                pathOrUrls = fileInputs.ToArray();
            }

            if (pathOrUrls != null)
            {
                foreach (var pathOrUrl in pathOrUrls)
                {
                    version.Files.AddRange(pathOrUrl.StartsWith("http") && Uri.TryCreate(pathOrUrl, UriKind.Absolute, out var url)
                         ? await Controller.BuildRegistryFilesFromUrlAsync(registry, url).ConfigureAwait(false)
                         : await Controller.BuildRegistryFilesFromPathAsync(registry, Path.GetFullPath(pathOrUrl), args.Saves).ConfigureAwait(false));
                }
            }

            registry.AssertNoDuplicates(version);

            if (package == null || version == null || package.Versions == null)
            {
                throw new NullReferenceException($"Error in {nameof(Controller.BuildRegistryFilesFromPathAsync)}: Null values were returned.");
            }

            var isNew = package.Versions.Count == 1;

            // TODO: Validate all fields
            if (!args.Quiet && !isNew && string.IsNullOrEmpty(args.PackageVersion))
            {
                Renderer.WriteLine($"This package already exists (by {package.Author ?? "Unknown User"}), a new version will be added to it.");

                Renderer.WriteLine($"Latest {Math.Min(5, package.Versions.Count - 1)} versions:");
                foreach (var existingVersion in package.Versions.Where(v => !ReferenceEquals(v, version)).Take(5))
                {
                    Renderer.WriteLine($"- {existingVersion.Version}");
                }
            }

            version.Created = DateTimeOffset.Now;
            version.Version = args.PackageVersion ?? (args.Quiet ? "1.0.0" : Renderer.Ask("Package version: ", true, RegistryPackageVersion.ValidVersionNameRegex, "1.0.0"));

            if (!args.Quiet && !isNew)
            {
                version.Notes = Renderer.Ask("Release notes: ");
            }

            if (isNew)
            {
                if (!args.Quiet)
                {
                    Renderer.WriteLine("Looks like a new package in the registry! If this was not what you expected, you might have mistyped the package name; press CTRL+C if you want to abort.");
                }

                var author = args.PackageAuthor ?? (args.Quiet ? "Anonymous" : Renderer.Ask("Author Name: ", true));
                if (!registry.Authors.Any(a => a.Name.Equals(author, StringComparison.InvariantCultureIgnoreCase)))
                {
                    registry.Authors.Add(new RegistryAuthor
                    {
                        Name   = author,
                        Github = args.Quiet ? null : Renderer.Ask($"GitHub Profile URL: "),
                        Reddit = args.Quiet ? null : Renderer.Ask($"Reddit Profile URL: ")
                    });
                }

                package.Author = author;

                if (!args.Quiet)
                {
                    package.Description = Renderer.Ask("Description: ");
                    package.Tags        = (Renderer.Ask("Tags (comma-separated list): ") ?? "").Split(',').Select(x => x.Trim()).Where(x => x != "").ToList();
                    package.Homepage    = Renderer.Ask("Package Homepage URL: ");
                    package.Repository  = Renderer.Ask("Package Repository URL: ");
                }
            }

            if (!args.Quiet)
            {
                string baseUrl = null;
                foreach (var file in version.Files)
                {
                    if (!string.IsNullOrEmpty(file.Url))
                    {
                        continue;
                    }

                    if (baseUrl != null)
                    {
                        var fileUrl = $"{baseUrl}{file.Filename.Replace(" ", "%20")}";
                        file.Url = Renderer.Ask($"{file.Filename} URL ({fileUrl}): ") ?? fileUrl;
                    }
                    else
                    {
                        file.Url = Renderer.Ask($"{file.Filename} URL: ", true);
                        if (file.Url.EndsWith("/" + file.Filename.Replace(" ", "%20")))
                        {
                            baseUrl = file.Url.Substring(0, file.Url.LastIndexOf("/") + 1);
                        }
                    }
                }
            }

            var serializer = new RegistrySerializer();

            if (args.Registry != null)
            {
                Controller.SaveToFile(serializer.Serialize(registry), args.Registry.FullName, false);
                Renderer.WriteLine($"JSON written to {args.Registry.FullName}");
            }
            else
            {
                Renderer.WriteLine("JSON Template:");
                Renderer.WriteLine(serializer.Serialize(package));
            }
        }