static ServiceInfo RegisterService(ServiceInfo info) { ServiceInfo result = null; using (var registryRepo = new RegistryRepository(new RegistryDatabaseFactory())) { result = registryRepo.InsertOrUpdateService(info); } return result; }
public ServiceInfo Sync(ServiceInfo message, TimeSpan timeout) { var corrId = Guid.NewGuid().ToString(); var props = channel.CreateBasicProperties(); props.ReplyTo = replyQueueName; props.CorrelationId = corrId; props.ContentType = "application/json"; props.ContentEncoding = "utf-8"; var messageBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicPublish("", queueName, props, messageBytes); BasicDeliverEventArgs ea = null; var timeoutDate = DateTime.UtcNow + timeout; while (DateTime.UtcNow <= timeoutDate) { try { var ok = consumer.Queue.Dequeue(Convert.ToInt32(timeout.TotalMilliseconds), out ea); if (!ok) { //PRC call timeout return null; } if (ea.BasicProperties.CorrelationId == corrId) { var json = Encoding.UTF8.GetString(ea.Body); return JsonConvert.DeserializeObject<ServiceInfo>(json); } } catch (Exception ex) { Console.WriteLine($"RPC Sync error {ex.Message} connection is {connection.IsOpen}"); Thread.Sleep(500); if(connection.IsOpen) { return null; } } } //PRC call timeout return null; }
public static ServiceInfo CreateServiceDefinition(ServiceInfo ms = null) { if (ms == null) { ms = new ServiceInfo(); ms.State = ServiceState.Running; ms.Tags = new List<string>(); } ms.Host = new HostInfo { Guid = GetUUID(), Name = Environment.MachineName, OSVersion = Environment.OSVersion.ToString(), CPUs = Environment.ProcessorCount, TotalMemory = GetTotalMemory(), FreeMemory = GetFreeMemory(), }; ms.HostGuid = ms.Host.Guid; ms.BuildDate = ProcessHelpers.GetBuildTimestamp(); ms.Version = ProcessHelpers.GetBuildVersion(); ms.HostName = Environment.MachineName; ms.LocalPath = Environment.CurrentDirectory; ms.MemoryUsage = Convert.ToInt64((Environment.WorkingSet / 1024f) / 1024f); #if DEBUG if (!ms.Tags.Contains("debug")) { ms.Tags.Add("debug"); } #endif using (var proc = Process.GetCurrentProcess()) { ms.Pid = proc.Id; if (string.IsNullOrEmpty(ms.Name)) { ms.Name = proc.ProcessName.Replace(".exe", string.Empty); } ms.StartDate = proc.StartTime.ToUniversalTime(); ms.CpuTime = proc.TotalProcessorTime.TotalSeconds; } if (ms.Port == 0) { ms.Port = ProcessHelpers.GetFreeTcpPort(); } return ms; }
public ServiceInfo Register(ServiceInfo service) { ServiceInfo info = null; using (var connection = connectionFactory.CreateConnection()) { using (var channel = connection.CreateModel()) { var correlationId = Guid.NewGuid().ToString(); var consumer = SetUpConsumer(channel, service, correlationId); BasicDeliverEventArgs ea = null; var timeoutDate = DateTime.UtcNow + timeout; while (DateTime.UtcNow <= timeoutDate) { try { var ok = consumer.Queue.Dequeue(Convert.ToInt32(timeout.TotalMilliseconds), out ea); if (!ok) { logger.Error($"RegistryClient.Register has timeout after {timeout.TotalSeconds} seconds"); return null; } if (ea.BasicProperties.CorrelationId == correlationId) { var json = Encoding.UTF8.GetString(ea.Body); info = serializer.DeserializeObject<ServiceInfo>(ea.Body); ServiceDefinition = info; return info; } } catch (Exception ex) { logger.LogException(ex, $"RegistryClient.Register RPC error {ex.Message}"); return info; } } logger.Error($"RegistryClient.Register has timeout after {timeout.TotalSeconds} seconds"); return info; } } }
static void Main(string[] args) { serviceDefinition = ServiceInfoFactory.CreateServiceDefinition(new ServiceInfo { Port = Convert.ToInt32(ServiceConfig.Reader.Port) }); var store = new RegistryDatabaseFactory(); store.Create(); store.ApplySchema(); store.r.Connection.Dispose(); if (args.Length == 0 || args.Contains("-ampq")) { serviceRegistryServer = new RpcServer<ServiceInfo>(ConnectionConfig.GetFactoryDefault(), RegistrySettings.RegistryQueue, RegisterService); serviceRegistryServer.StartInBackground(); statsConsumer = StartStatsConsumer(); Console.WriteLine("Registry AMPQ started"); } if (args.Length == 0 || args.Contains("-web")) { webServer = WebApp.Start<Startup>(url: ServiceConfig.Reader.GetBaseAddress()); Console.WriteLine("Web server started"); } Console.ReadLine(); if (statsConsumer != null) { statsConsumer.StopConsumer(); serviceRegistryServer.Stop(); } if (webServer != null) { webServer.Dispose(); } }
public ServiceInfo ToServiceInfo() { var model = new ServiceInfo(); model.BuildDate = this.BuildDate; model.Guid = this.Guid; model.HostGuid = this.HostGuid; model.HostName = this.HostName; model.Id = this.Id; model.LastPingDate = this.LastPingDate; model.LocalPath = this.LocalPath; model.MemoryUsage = this.MemoryUsage; model.CpuTime = this.CpuTime; model.Name = this.Name; model.Pid = this.Pid; model.Port = this.Port; model.RegisterDate = this.RegisterDate; model.StartDate = this.StartDate; model.State = (ServiceState)this.State; model.Tags = this.Tags; model.Version = this.Version; return model; }
public static ServiceModel FromServiceInfo(ServiceInfo info) { var model = new ServiceModel(); model.BuildDate = info.BuildDate; model.Guid = info.Guid; model.HostGuid = info.HostGuid; model.HostName = info.HostName; model.Id = info.Id; model.LastPingDate = info.LastPingDate; model.LocalPath = info.LocalPath; model.MemoryUsage = info.MemoryUsage; model.CpuTime = info.CpuTime; model.Name = info.Name; model.Pid = info.Pid; model.Port = info.Port; model.RegisterDate = info.RegisterDate; model.StartDate = info.StartDate; model.State = (int)info.State; model.Tags = info.Tags; model.Version = info.Version; return model; }
public async Task<ServiceInfo> InsertOrUpdateServiceAsync(ServiceInfo info) { if (string.IsNullOrEmpty(info.Guid)) { info.Guid = Guid.NewGuid().ToString(); } info.LastPingDate = DateTime.UtcNow; var model = ServiceModel.FromServiceInfo(info); var host = InsertOrUpdateHost(info.Host); var th = r.RunAsync(r.Services.OrderByDescending("idx_date").Where(x => x.Guid == info.Guid).Limit(1)); await th.MoveNext(); var service = th.Current; if (service == null) { model.RegisterDate = DateTime.UtcNow; var response = r.Run(r.Services.Insert(model)); model.Id = response.GeneratedKeys.FirstOrDefault(); } else { // merge tags for db with received ones foreach (var tag in service.Tags) { if (!model.Tags.Contains(tag)) { model.Tags.Add(tag); } } // insert new if pid changed if (info.Pid != service.Pid) { model.Id = null; model.RegisterDate = DateTime.UtcNow; var response = r.Run(r.Services.Insert(model)); model.Id = response.GeneratedKeys.FirstOrDefault(); //update last instance status service.State = (int)ServiceState.Stopped; r.Run(r.Services.Update(h => service)); } else { model.Id = service.Id; model.RegisterDate = service.RegisterDate; r.Run(r.Services.Update(h => model)); } } return model.ToServiceInfo(); }
public QueueingBasicConsumer SetUpConsumer(IModel channel, ServiceInfo service, string correlationId) { var replyQueueName = channel.QueueDeclare(); var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(replyQueueName, true, consumer); var props = channel.CreateBasicProperties(); props.Headers = new Dictionary<string, object>(); props.Headers.Add("x-version", service.Version); props.ReplyTo = replyQueueName; props.CorrelationId = correlationId; props.ContentType = serializer.ContentType; props.ContentEncoding = serializer.ContentEncoding; var messageBytes = serializer.SerializeObject(service); channel.QueueDeclare(queue: RegistrySettings.RegistryQueue, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicPublish("", RegistrySettings.RegistryQueue, props, messageBytes); return consumer; }
public static void SaveToDisk(ServiceInfo ms) { var ser = new JsonMessageSerializer(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ms.Name + ".json"); File.WriteAllBytes(path, ser.SerializeObject(ms)); }