Example #1
0
        public object GetServiceDirectoryList(ServiceDirectorySearch service)
        {
            dynamic       TBServiceDirectoryResult;
            List <object> ServiceDirectoryResult = new List <object>();

            try
            {
                List <ServiceDirectoryList> Result = ServiceDirectory.GetServiceDirectoryList(service);
                for (int i = 0; i < Result.Count; i++)
                {
                    ServiceDirectoryResult.Add(new { ServiceDirResult = Result[i] });
                }

                if (ServiceDirectoryResult != null)
                {
                    TBServiceDirectoryResult = new { status = "0", message = "success", updatedOn = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), ServiceDirectoryResult };
                }
                else
                {
                    TBServiceDirectoryResult = new { status = "0", message = "Record not found" };
                }
            }
            catch
            {
                TBServiceDirectoryResult = new { status = "1", message = "failed" };
            }

            return(new { TBServiceDirectoryResult });
        }
Example #2
0
        public object GetServiceDirectoryDetails(ServiceDirDetail serv)
        {
            dynamic       TBServiceDirectoryListResult;
            List <object> ServiceDirectoryListResult = new List <object>();

            try
            {
                //string a = HttpContext.Current.Request.HttpMethod;
                List <ServiceDirectoryDetail> Result = ServiceDirectory.GetServiceDirDetails(serv);
                for (int i = 0; i < Result.Count; i++)
                {
                    ServiceDirectoryListResult.Add(new { ServiceDirList = Result[i] });
                }

                if (Result != null && Result.Count != 0)
                {
                    TBServiceDirectoryListResult = new { status = "0", message = "success", ServiceDirListResult = ServiceDirectoryListResult };
                }
                else
                {
                    TBServiceDirectoryListResult = new { status = "1", message = "Record not found", ServiceDirListResult = ServiceDirectoryListResult };
                }
            }
            catch
            {
                TBServiceDirectoryListResult = new { status = "1", message = "failed" };
            }

            return(new { TBServiceDirectoryListResult });
        }
Example #3
0
        private async Task HostUpdated(ServiceDirectory directory, ServiceEntry entry)
        {
            RuntimeMonitor.Monitor.RegisterCall("HostUpdated");

            LampClient newClient = new LampClient(ServiceEntryToUrl(entry), ServiceEntryToName(entry));

            // Update info in DB
            using (var client = new DatabaseClient())
            {
                var node = client.GetOne(newClient.Name);
                if (node != null)
                {
                    node.LastSeen = entry.LastSeenAlive;
                    node.Online   = true;
                    node.Url      = newClient.Url;

                    client.AddOrUpdate(node);
                }
                else
                {
                    // For some reason, this node was updated but no longer in the database
                    // Then treat it as an addition
                    await HostDiscovered(directory, entry, true);
                }
            }
        }
        protected override void ExecuteImpl(string[] args)
        {
            var googleapisRoot   = GetGoogleapisRoot();
            var serviceDirectory = ServiceDirectory.LoadFromGoogleapis(googleapisRoot);
            var outputDirectory  = DirectoryLayout.ForApi("ServiceDirectory").SourceDirectory;

            string directoryJson = JsonConvert.SerializeObject(serviceDirectory, Formatting.Indented);

            File.WriteAllText(Path.Combine(outputDirectory, "directory.json"), directoryJson);

            var gitCommit     = GetCommit(googleapisRoot);
            var synthMetadata = new
            {
                sources = new[] {
                    new {
                        git = new
                        {
                            name   = "googleapis",
                            remote = "https://github.com/googleapis/googleapis.git",
                            sha    = gitCommit
                        }
                    }
                }
            };
            var synthMetadataJson = JsonConvert.SerializeObject(synthMetadata, Formatting.Indented);

            File.WriteAllText(Path.Combine(outputDirectory, "synth.metadata"), synthMetadataJson);
        }
Example #5
0
        protected override void ExecuteImpl(string[] args)
        {
            string id = args[0];

            var catalog = ApiCatalog.Load();

            if (catalog.Apis.Any(api => api.Id == id))
            {
                throw new UserErrorException($"API {id} already exists in the API catalog.");
            }
            var serviceDirectory = ServiceDirectory.LoadFromGoogleapis();

            var service = serviceDirectory.Services.FirstOrDefault(service => service.CSharpNamespaceFromProtos == id);

            if (service is null)
            {
                var lowerWithoutCloud = id.Replace(".Cloud", "").ToLowerInvariant();
                var possibilities     = serviceDirectory.Services
                                        .Select(svc => svc.CSharpNamespaceFromProtos)
                                        .Where(ns => ns.Replace(".Cloud", "").ToLowerInvariant() == lowerWithoutCloud);
                throw new UserErrorException(
                          $"No service found for '{id}'.{Environment.NewLine}Similar possibilities (check options?): {string.Join(", ", possibilities)}");
            }

            var api = new ApiMetadata
            {
                Id          = id,
                ProtoPath   = service.ServiceDirectory,
                ProductName = service.Title.EndsWith(" API") ? service.Title[..^ 4] : service.Title,
Example #6
0
        public object GetServiceDirectoryCategories(ServiceDirectorySearch service)
        {
            //dynamic TBServiceCategoriesResult;
            List <object> ServiceCategoriesResult = new List <object>();

            try
            {
                List <ServiceCategoryList> Result = ServiceDirectory.GetServiceDirCategoriesList(service);
                for (int i = 0; i < Result.Count; i++)
                {
                    ServiceCategoriesResult.Add(Result[i]);
                }

                if (ServiceCategoriesResult != null)
                {
                    return(new { status = "0", message = "success", ServiceCategoriesResult });
                }
                else
                {
                    return(new { status = "0", message = "Record not found" });
                }
            }
            catch
            {
                return(new { status = "1", message = "failed" });
            }
        }
 public AcmeProtocolClient(HttpClient http, ServiceDirectory dir = null,
                           AccountDetails acct    = null, IJwsTool signer = null,
                           bool disposeHttpClient = false,
                           ILogger logger         = null)
 {
     Init(http, dir, acct, signer, logger);
     _disposeHttpClient = disposeHttpClient;
 }
Example #8
0
        private void HostRemoved(ServiceDirectory directory, ServiceEntry entry)
        {
            RuntimeMonitor.Monitor.RegisterCall("HostRemoved");

            using (var client = new DatabaseClient())
                client.RemoveByName(ServiceEntryToName(entry));
            Logger.Log("Host removed: {0}", entry.ToShortString());
        }
Example #9
0
        protected override void ExecuteImpl(string[] args)
        {
            var directory = ServiceDirectory.LoadFromGoogleapis();

            foreach (var api in directory.Services)
            {
                ReportAnomalies(api);
            }
        }
Example #10
0
        public async Task Run(string[] args)
        {
            Logger.Log("HippotronicsLedDaemon started");

            _serviceDirectory = new ServiceDirectory(
                hostFilterfunc: FilterHippoServices,
                netFilterFunc: FilterLocalNetwork
                );

            // Set up REST services in OWIN web server
            var webapp = WebApp.Start(
                String.Format("http://*:{0}/", Config.Port),
                new Action <IAppBuilder>(Configuration));

            Console.CancelKeyPress += (sender, e) =>
            {
                Logger.Log("HippotronicsLedDaemon stopped");
                webapp.Dispose();
            };

            // Set up ServiceDirectory to look for MDNS lamps on the network
            _serviceDirectory.KeepaliveCheckInterval = ((uint)Config.KeepaliveIntervalMinutes) * 60;
            _serviceDirectory.KeepaliveGrace         = Config.KeepaliveGrace;
            _serviceDirectory.KeepalivePing          = _serviceDirectory.KeepaliveTcp = true;

            _serviceDirectory.HostDiscovered += async(dir, entry) => { await HostDiscovered(dir, entry); };
            _serviceDirectory.HostUpdated    += async(dir, entry) => { await HostUpdated(dir, entry); };
            _serviceDirectory.HostRemoved    += HostRemoved;

            _serviceDirectory.Init();

            string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            int    lastPoint       = assemblyVersion.LastIndexOf('.');

            assemblyVersion = assemblyVersion.Substring(0, lastPoint);
            Logger.Log("HippotronicsLedDaemon version {0} running", assemblyVersion);

            // Schedule purge of records that have not been updated
            await ScheduleNextUpdate();


            // Run until Ctrl+C
            Console.CancelKeyPress += (sender, e) =>
            {
                _endEvent.Set();
            };

            // Start watchdog
            Watchdog.Dog.ScheduleDog();

            // Wait for normal termination
            _endEvent.WaitOne();

            Logger.Log("HippotronicsLedDaemon ending");
            Environment.Exit(0);        // Normal exit
        }
        public AcmeProtocolClient(Uri baseUri, ServiceDirectory dir = null,
                                  AccountDetails acct = null, IJwsTool signer = null,
                                  ILogger logger      = null)
        {
            var http = new HttpClient
            {
                BaseAddress = baseUri,
            };

            Init(http, dir, acct, signer, logger);
            _disposeHttpClient = true;
        }
Example #12
0
        private async Task HostDiscovered(ServiceDirectory directory, ServiceEntry entry, bool fromUpdate = false)
        {
            RuntimeMonitor.Monitor.RegisterCall("HostDiscovered");

            Logger.Log("Host discovered: {0}{1}", entry.ToShortString(), fromUpdate ? " from HostUpdated event" : "");

            LampClient newClient = new LampClient(ServiceEntryToUrl(entry), ServiceEntryToName(entry));

            // Get status and add to DB
            await GetLampStatus(newClient);

            UpdateDb(newClient);
        }
        private void Init(HttpClient http, ServiceDirectory dir,
                          AccountDetails acct, IJwsTool signer,
                          ILogger logger)
        {
            _http     = http;
            Directory = dir ?? new ServiceDirectory();

            Account = acct;

            Signer = signer ?? ResolveDefaultSigner();

            _log = logger ?? NullLogger.Instance;
            _log.LogInformation("ACME client initialized");
        }
Example #14
0
        public object GetServiceDirectoryListSync(ServiceDirectorySearch serv)
        {
            dynamic       TBServiceDirectoryResult;
            List <object> ServiceDirectoryResult = new List <object>();

            try
            {
                ServiceDirector Result = ServiceDirectory.GetServiceDirectoryListSync(serv);

                TBServiceDirectoryResult = new { status = "0", message = "success", updatedOn = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), Result };
            }
            catch
            {
                TBServiceDirectoryResult = new { status = "1", message = "An error occured. Please contact Administrator" };
            }
            return(new
            {
                TBServiceDirectoryResult
            });
        }
Example #15
0
        private void Init(HttpClient http, ServiceDirectory dir,
                          AccountDetails acct, IJwsTool signer,
                          ILogger logger)
        {
            _http     = http;
            Directory = dir ?? new ServiceDirectory();

            Account = acct;

            // We default to ES256 signer
            if (signer == null)
            {
                signer = new Crypto.JOSE.Impl.ESJwsTool();
                signer.Init();
            }
            Signer = signer;

            _log = logger ?? NullLogger.Instance;
            _log.LogInformation("ACME client initialized");
        }
        public ActionResult <object> GetDirectory()
        {
            var dir = new ServiceDirectory
            {
                Directory = Url.Action(nameof(GetDirectory),
                                       controller: null,
                                       values: null, protocol: Request.Scheme),
                NewNonce = Url.Action(nameof(AcmeController.NewNonce),
                                      controller: AcmeController.ControllerRoute,
                                      values: null, protocol: Request.Scheme),
                NewAccount = Url.Action(nameof(AcmeController.NewAccount),
                                        controller: AcmeController.ControllerRoute,
                                        values: null, protocol: Request.Scheme),
                NewOrder = Url.Action(nameof(AcmeController.NewOrder),
                                      controller: AcmeController.ControllerRoute,
                                      values: null, protocol: Request.Scheme),
                NewAuthz   = null,
                KeyChange  = null,
                RevokeCert = Url.Action(nameof(AcmeController.Revoke),
                                        controller: AcmeController.ControllerRoute,
                                        values: null, protocol: Request.Scheme),

                Meta = new DirectoryMeta
                {
                    TermsOfService = Url.Action(nameof(GetTermsOfService),
                                                controller: null, values: null, protocol: Request.Scheme),
                    Website                 = null,
                    CaaIdentities           = null,
                    ExternalAccountRequired = null,
                }
            };

            var random = Guid.NewGuid().ToString().Replace("-", "");

            //dir.SetExtra($"prop_{random}", random);
            dir.SetExtra($"prop_{random}",
                         "https://community.letsencrypt.org/t/adding-random-entries-to-the-directory/");

            return(dir);
        }
        protected override void ExecuteImpl(string[] args)
        {
            var catalog = ApiCatalog.Load();
            // Note: for now, we could actually load it from apis/ServiceDirectory, but hey...
            var directory       = ServiceDirectory.LoadFromGoogleapis();
            var stabilityFilter = BuildStabilityFilter(args[0]);

            var ignoredOrGeneratedPaths = new HashSet <string>(catalog.IgnoredPaths.Keys);

            ignoredOrGeneratedPaths.UnionWith(catalog.Apis.Select(api => api.ProtoPath));

            var missingServices = directory.Services
                                  .Where(stabilityFilter)
                                  .Where(svc => !ignoredOrGeneratedPaths.Contains(svc.ServiceDirectory))
                                  .ToList();

            Console.WriteLine($"Missing services: {missingServices.Count}");
            foreach (var service in missingServices)
            {
                Console.WriteLine(service.ServiceDirectory);
            }
        }
Example #18
0
        public object GetServiceCategoriesData(ServiceDirectorySearch service)
        {
            dynamic TBGetServiceCategoriesDataList;

            try
            {
                ClsSeviceCategoryData Result = ServiceDirectory.GetServiceCategoriesData(service);

                if (Result != null)
                {
                    TBGetServiceCategoriesDataList = new { status = "0", message = "success", Result = Result };
                }
                else
                {
                    TBGetServiceCategoriesDataList = new { status = "0", message = "Record not found" };
                }
            }
            catch
            {
                TBGetServiceCategoriesDataList = new { status = "1", message = "failed" };
            }

            return(new { TBGetServiceCategoriesDataList });
        }
        protected override void ExecuteImpl(string[] args)
        {
            string id = args[0];

            var catalog = ApiCatalog.Load();

            if (catalog.Apis.Any(api => api.Id == id))
            {
                throw new UserErrorException($"API {id} already exists in the API catalog.");
            }
            var serviceDirectory = ServiceDirectory.LoadFromGoogleapis();

            var service = serviceDirectory.Services.FirstOrDefault(service => service.CSharpNamespaceFromProtos == id);

            if (service is null)
            {
                var lowerWithoutCloud = id.Replace(".Cloud", "").ToLowerInvariant();
                var possibilities     = serviceDirectory.Services
                                        .Select(svc => svc.CSharpNamespaceFromProtos)
                                        .Where(ns => ns.Replace(".Cloud", "").ToLowerInvariant() == lowerWithoutCloud);
                throw new UserErrorException(
                          $"No service found for '{id}'.{Environment.NewLine}Similar possibilities (check options?): {string.Join(", ", possibilities)}");
            }

            var api = new ApiMetadata
            {
                Id          = id,
                ProtoPath   = service.ServiceDirectory,
                ProductName = service.Title,
                Description = service.Description,
                Version     = "1.0.0-beta00",
                Type        = ApiType.Grpc,
                Generator   = GeneratorType.Micro,
                // Let's not include test dependencies, which are rarely useful.
                TestDependencies = null
            };

            // Add dependencies discovered via the proto imports.
            // This doesn't fail on any dependencies that aren't found - we could tighten this up later
            // by knowing about common protos, for example.
            var apisByProtoPath = catalog.Apis.Where(api => api.ProtoPath is object).ToDictionary(api => api.ProtoPath);

            foreach (var import in service.ImportDirectories)
            {
                if (apisByProtoPath.TryGetValue(import, out var dependency))
                {
                    api.Dependencies.Add(dependency.Id, dependency.Version);
                }
            }

            // Now work out what the new API metadata looks like in JSON.
            var serializer = new JsonSerializer
            {
                NullValueHandling = NullValueHandling.Ignore,
                Converters        = { new StringEnumConverter(new CamelCaseNamingStrategy()) },
                ContractResolver  = new DefaultContractResolver {
                    NamingStrategy = new CamelCaseNamingStrategy()
                }
            };

            api.Json = JToken.FromObject(api, serializer);

            var followingApi = catalog.Apis.FirstOrDefault(api => string.Compare(api.Id, id, StringComparison.Ordinal) > 0);

            if (followingApi is object)
            {
                followingApi.Json.AddBeforeSelf(api.Json);
            }
            else
            {
                // Looks like this API will be last in the list.
                catalog.Apis.Last().Json.AddAfterSelf(api.Json);
            }

            // Done. Let's write out the catalog and display what we've done.
            File.WriteAllText(ApiCatalog.CatalogPath, catalog.FormatJson());
            Console.WriteLine($"Added {id} to the API catalog with the following configuration:");
            Console.WriteLine(api.Json.ToString(Formatting.Indented));
        }
Example #20
0
        public object AddServiceDirectory(AddServiceDirectory addservice)
        {
            dynamic TBAddServiceResult;
            int     str = -1;

            try
            {
                Imgname Result = ServiceDirectory.createService(addservice);

                if (!string.IsNullOrEmpty(Result.imgName))
                {
                    str = GlobalFuns.UploadImage(addservice.groupId, Result.imgName, "servicedirectory");
                }
                else
                {
                    str = 0;
                }

                //if (Result != null)
                //{
                if (str == 0)
                {
                    //TBAddServiceResult = new { status = "0", message = "success" };
                    ServiceDirectorySearch serv = new ServiceDirectorySearch();
                    serv.groupId  = addservice.groupId;
                    serv.moduleId = addservice.moduleId;

                    DateTime dt = DateTime.Now;
                    if (addservice.updatedOn != null)
                    {
                        dt = Convert.ToDateTime(addservice.updatedOn);
                        dt = dt.AddSeconds(-1);
                    }

                    serv.updatedOn = dt.ToString("yyyy/MM/dd HH:mm:ss");

                    ServiceDirector res = ServiceDirectory.GetServiceDirectoryListSync(serv);

                    if (res != null)
                    {
                        TBAddServiceResult = new { status = "0", message = "success", updatedOn = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), res };
                    }
                    else
                    {
                        TBAddServiceResult = new { status = "1", message = "failed", updatedOn = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") };
                    }
                }
                else
                {
                    TBAddServiceResult = new { status = "1", message = "failed" }
                };
                //}
                //else
                //{
                //    TBAddServiceResult = new { status = "0", message = "Record not found" };
                //}
            }
            catch
            {
                TBAddServiceResult = new { status = "1", message = "failed" };
            }

            return(new { TBAddServiceResult });
        }