public IHttpActionResult PutServiceAddress(int id, ServiceAddress serviceAddress) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != serviceAddress.ID) { return(BadRequest()); } db.Entry(serviceAddress).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ServiceAddressExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public override async Task Start(ServiceAddress serviceAddress) { _logger.Debug($"准备启动服务主机,监听地址:{serviceAddress}。"); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2 var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new MicroMessageHandler(_coderFactory.GetDecoder())); pipeline.AddLast(new ServerHandler(async(contenxt, message) => { var sender = new DotNettyServerSender(_coderFactory.GetEncoder(), contenxt); await OnReceived(sender, message); })); })); var endPoint = serviceAddress.ToEndPoint(); _channel = await bootstrap.BindAsync(endPoint); _logger.Info($"服务主机启动成功,监听地址:{serviceAddress}。"); }
/// <inheritdoc /> /// <summary> 启动服务 </summary> /// <param name="serviceAddress">主机终结点。</param> /// <returns>一个任务。</returns> public override Task Start(ServiceAddress serviceAddress) { serviceAddress.Protocol = Constants.Protocol; serviceAddress.Codec = Constants.Codec; try { Task.Factory.StartNew(async() => { await MicroListener.Start(serviceAddress); }); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation( $"服务已启动:{serviceAddress},Gzip:{serviceAddress.Gzip},Codec:{Constants.Codec},Protocol:{Constants.Protocol}"); } } catch (Exception ex) { _logger.LogError(ex, ex.Message); } var assemblies = _entryFactory.GetContracts(); return(_serviceRegister.Regist(assemblies, serviceAddress)); }
public void DownloadUpdates(string cycle) { if (File.Exists(waitFilePath)) { return; } //Delete All Files Dictionary <String, bool> updateCheckList = new Dictionary <string, bool>(); //Loop through subs for HHDownload set, download foreach (Subscription subscription in Subscriptions) { if (subscription.Type.Equals("DownloadSet") && HasCurrentCycle(subscription.Cycle, cycle)) { if (File.Exists(Path.Combine(subscription.Destination, subscription.FileName))) { File.Delete(Path.Combine(subscription.Destination, subscription.FileName)); } bool fileDownloaded = RequestHandler.StartDownloadSetRequest( ServiceAddress.GetDownloadUpdateURL(Settings, User, subscription) , subscription); updateCheckList.Add(subscription.Name, fileDownloaded); } } }
public async Task Regist(IEnumerable <Assembly> assemblyList, ServiceAddress serverAddress) { using (var client = CreateClient()) { foreach (var ass in assemblyList) { var assName = ass.GetName(); var service = new AgentServiceRegistration { ID = $"{ass.GetName().Name}_{serverAddress}".Md5(), Name = assName.Name, Tags = new[] { $"{Consts.Mode}" }, EnableTagOverride = true, Address = serverAddress.Address(), Port = serverAddress.Port, Meta = new Dictionary <string, string> { { "serverAddress", serverAddress.ToJson() } } }; _services.Add(service.ID); var result = await client.Agent.ServiceRegister(service); if (result.StatusCode != HttpStatusCode.OK) { _logger.Warn( $"服务注册失败 [{assName.Name},{serverAddress}]:{result.StatusCode},{result.RequestTime}"); } else { _logger.Info($"服务注册成功 [{assName.Name},{serverAddress}]"); } } } }
public override async Task Start(ServiceAddress serviceAddress) { _address = serviceAddress; //var endpoint = serviceAddress.ToEndPoint() as IPEndPoint; _host = new HostBuilder() .UseContentRoot(AppDomain.CurrentDomain.BaseDirectory) .ConfigureLogging((context, builder) => { builder.AddFilter("System", level => level >= LogLevel.Warning); builder.AddFilter("Microsoft", level => level >= LogLevel.Warning); builder.AddConsole(); }) .ConfigureWebHostDefaults(builder => { builder .UseKestrel(options => { options.AllowSynchronousIO = true; options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(65); options.Listen(IPAddress.Any, serviceAddress.Port); }) .Configure(BuildApplication); }) .ConfigureServices(ConfigureServices) .Build(); await _host.RunAsync(); }
private async Task <ResultMessage> BaseInvoke(MethodInfo targetMethod, object[] args) { var services = (await _serviceFinder.Find(targetMethod.DeclaringType) ?? new List <ServiceAddress>()).ToList(); var invokeMessage = Create(targetMethod, args); ServiceAddress service = null; var builder = Policy .Handle <Exception>(ex => ex.GetBaseException() is SocketException) //服务器异常 .OrResult <ResultMessage>(r => r.Code != 200); //服务未找到 //熔断,3次异常,熔断5分钟 var breaker = builder.CircuitBreakerAsync(3, TimeSpan.FromMinutes(5)); //重试3次 var retry = builder.RetryAsync(3, (result, count) => { _logger.Warn(result.Exception != null ? $"{service}{targetMethod.Name}:retry,{count},{result.Exception.Format()}" : $"{service}{targetMethod.Name}:retry,{count},{result.Result.Code}"); services.Remove(service); }); var policy = Policy.WrapAsync(retry, breaker); return(await policy.ExecuteAsync(async() => { if (!services.Any()) { throw ErrorCodes.NoService.CodeException(); } service = services.RandomSort().First(); return await InvokeAsync(service.ToEndPoint(), invokeMessage); })); }
/// <summary> /// Resets the internal state of the secure channel. /// </summary> /// <param name="node">The node.</param> /// <param name="address">The address.</param> public void Reset(Node node, ServiceAddress address) { // validate arguments if (node == null) { throw new ArgumentNullException(nameof(node), "The node cannot be null"); } else if (address == null) { throw new ArgumentNullException(nameof(node), "The address cannot be null"); } // check if already setup if (_node != null) { throw new InvalidOperationException("The secure channel is already configured"); } // set _node = node; _address = address; // reset internal keys _serverCertificate = null; _handshakeEncryptionKey = null; _handshakeEncryptionIV = null; _serverNonce = null; _serverEncryptionKey = null; }
public HttpClientMessageSender(IServiceProvider provider, ServiceAddress address, IMessageListener listener) { _provider = provider; _address = address; _listener = listener; _clientFactory = provider.GetService <IHttpClientFactory>(); }
public static void RegisterServices(this IServiceCollection services, List <string> registerList) { // 本地api注册到服务中心 var registerService = ConfigManager.Configuration["ServiceConfig:RegisterService"]; if (!string.IsNullOrEmpty(registerService)) { try { var discovery = GetServiceFromRoot <Modobay.Discovery.IDiscoveryServer>(); var reg = new Regex(registerService); foreach (var item in _apiInterfaceTypes.Select(x => x.FullName).ToList()) { if (reg.IsMatch(item)) { registerList.Add(item); } } var keep = discovery.Register(ServiceAddress.Replace(":", "_"), registerList); // todo pxg 暂时屏蔽 Schedule.ScheduleManager.CreateJob <Modobay.Discovery.KeepServiceScheduleJob>($"0/{keep} * * * * ? *"); } catch (Exception ex) { Lib.Log.WriteExceptionLog($"AppManager.AddServices:{ex.Message} <br> StackTrace:{ex.StackTrace}"); } } }
public override Task Start(ServiceAddress serviceAddress) { _grpcServer = new Server { Ports = { new ServerPort(serviceAddress.Service, serviceAddress.Port, ServerCredentials.Insecure) } }; var services = _entryFactory.Services; foreach (var type in services) { var baseType = type?.BaseType; var definitionType = baseType?.DeclaringType; var methodInfo = definitionType?.GetMethod("BindService", new[] { baseType }); if (methodInfo != null) { var instance = _provider.GetService(type); var service = methodInfo.Invoke(null, new[] { instance }); if (service is ServerServiceDefinition serviceDescriptor) { _grpcServer.Services.Add(serviceDescriptor); } } } _logger.LogInformation($"发现 GRPC服务:{_grpcServer.Services.Count()} 条"); _logger.LogInformation($"GRPC Service Start At:{serviceAddress}"); //AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); _grpcServer.Start(); return(Task.CompletedTask); }
/// <inheritdoc /> /// <summary> 创建客户端 </summary> /// <param name="serviceAddress">终结点。</param> /// <returns>传输客户端实例。</returns> public IMicroClient CreateClient(ServiceAddress serviceAddress) { //_logger.Debug($"准备为服务端地址:{endPoint}创建客户端。"); try { var lazyClient = _clients.GetOrAdd(serviceAddress.ToString(), k => new Lazy <IMicroClient>(() => { _logger.LogDebug($"创建客户端:{serviceAddress}创建客户端。"); var bootstrap = _bootstrap; var channel = bootstrap.ConnectAsync(serviceAddress.ToEndPoint(false)).Result; var listener = new MessageListener(); var sender = new DotNettyClientSender(_codecFactory.GetEncoder(), channel); channel.GetAttribute(ListenerKey).Set(listener); channel.GetAttribute(SenderKey).Set(sender); channel.GetAttribute(ServiceAddressKey).Set(serviceAddress); return(new MicroClient(_logger, sender, listener, _microExecutor)); } )); return(lazyClient.Value); } catch (Exception ex) { _logger.LogError(ex, "创建客户端失败"); _clients.TryRemove(serviceAddress.ToString(), out _); throw; } }
public async Task UpdateAsync(ServiceAddress entity) { using (var context = _contextCreator()) { _repository = new ConnectedRepository <ServiceAddress>(context); await _repository.UpdateAsync(entity); } }
public bool Add(ServiceAddress address, string serviceIdentity, string ip) { var bucket = _buckets.GetOrAdd(serviceIdentity, (sid) => { return(new ServiceAddressBucket(sid)); }); return(bucket.Add(address, ip)); }
public void Update(ServiceAddress entity) { using (var context = _contextCreator()) { _repository = new ConnectedRepository <ServiceAddress>(context); _repository.Update(entity); } }
public ActionResult DeleteConfirmed(int id) { ServiceAddress serviceAddress = db.ServiceAddressSet.Find(id); db.ServiceAddressSet.Remove(serviceAddress); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Attaches the service provider to the address. /// </summary> /// <param name="addr">The service address.</param> /// <param name="type">The service type.</param> /// <param name="execution">The service execution.</param> /// <param name="behaviour">The service behaviour.</param> /// <returns>The attached service.</returns> public Task <Service> AttachAsync(ServiceAddress addr, ServiceType type, ServiceExecution execution, ServiceBehaviour behaviour) { return(AttachAsync(addr, new ServiceConfiguration() { Type = type, Execution = execution }, behaviour)); }
public async Task <ActionResult> DeleteConfirmed(int id) { ServiceAddress serviceAddress = await db.ServiceAddresses.FindAsync(id); db.ServiceAddresses.Remove(serviceAddress); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public override async Task Regist(IEnumerable <Assembly> assemblyList, ServiceAddress serverAddress) { foreach (var assembly in assemblyList) { var serviceName = assembly.ServiceName(); var meta = new Dictionary <string, string> { { KeyService, serverAddress.ToJson() }, { KeyMode, $"{Constants.Mode}" }, { KeyVersion, assembly.GetName().Version.ToString() } }; var request = new CreateInstanceRequest { serviceName = serviceName, namespaceId = _config.Tenant, groupName = _config.Group, clusterName = string.Empty, ip = serverAddress.IpAddress, port = serverAddress.Port, weight = serverAddress.Weight, Meta = meta, enabled = true, healthy = true, ephemeral = false }; try { var result = await _client.CreateInstance(request); if (result == "ok") { _services.Add(new RemoveInstanceRequest { namespaceId = request.namespaceId, serviceName = request.serviceName, groupName = request.groupName, clusterName = request.clusterName, ip = request.ip, port = request.port, ephemeral = request.ephemeral }); _logger.LogInformation($"服务注册成功 [{serviceName},{serverAddress}]"); //发送心跳包 _listenerHelper.AddServiceBeat(request, t => { }, 15); } else { throw new SpearException($"注册实例失败,{result}"); } } catch (Exception ex) { _logger.LogWarning( $"服务注册失败 [{serviceName},{serverAddress}]:{ex.Message}"); } } }
/// <summary> /// Broadcasts the message to the provided service address and waits for any responses within the timeout. /// </summary> /// <param name="addr">The service adddress.</param> /// <param name="body">The body.</param> /// <param name="timeout">The timeout to receive all replies.</param> /// <param name="headers">The headers.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public Task <Envelope[]> BroadcastAsync(ServiceAddress addr, byte[] body, TimeSpan timeout, IDictionary <string, object> headers = null, CancellationToken cancellationToken = default(CancellationToken)) { return(BroadcastAsync(new Message() { Address = addr, Body = body, Headers = headers }, timeout, cancellationToken)); }
public void Connect(UvLoopHandle loop, ServiceAddress address, Action <UvConnectRequest, int, Exception, object> callback, object state) { var addr = GetAddress(address); var request = new UvConnectRequest(); request.Init(loop); request.Connect(this, ref addr, callback, state); }
/// <summary> /// Sends the message to the provided service address. /// </summary> /// <param name="addr">The service address.</param> /// <param name="body">The body.</param> /// <param name="headers">The headers.</param> /// <returns></returns> public Task SendAsync(ServiceAddress addr, byte[] body, IDictionary <string, object> headers = null) { return(SendAsync(new Message() { Address = addr, Body = body, Headers = headers })); }
/// <summary> 开启微服务 </summary> /// <param name="provider"></param> /// <param name="addressAction"></param> /// <returns></returns> public static void UseMicroService(this IServiceProvider provider, Action <ServiceAddress> addressAction) { var address = new ServiceAddress(); addressAction?.Invoke(address); var host = provider.GetService <IMicroHost>(); Task.Factory.StartNew(async() => await host.Start(address)); }
/// <summary> 执行请求 </summary> /// <param name="serviceAddress"></param> /// <param name="message"></param> /// <returns></returns> private async Task <ResultMessage> ClientInvokeAsync(ServiceAddress serviceAddress, InvokeMessage message) { //获取不同协议的客户端工厂 var clientFactory = _provider.GetService <IMicroClientFactory>(serviceAddress.Protocol); var client = clientFactory.CreateClient(serviceAddress); var result = await client.Send(message); return(result); }
/// <summary> 创建客户端 </summary> /// <param name="serviceAddress"></param> /// <returns></returns> protected override Task <IMicroClient> Create(ServiceAddress serviceAddress) { Logger.LogDebug($"创建客户端:{serviceAddress}创建客户端。"); var listener = new MessageListener(); var sender = new HttpClientMessageSender(Provider, serviceAddress, listener); IMicroClient client = new MicroClient(sender, listener, MicroExecutor, LoggerFactory); return(Task.FromResult(client)); }
public void DownloadConfirmations(string cycle) { foreach (Subscription subscription in Subscriptions) { if (subscription.Type.Equals("DownloadStartsWith") && HasCurrentCycle(subscription.Cycle, cycle)) { RequestHandler.StartDownloadStartsWithRequest(ServiceAddress.GetDownloadConfirmationURL(Settings, User, subscription), subscription); } } }
public void UploadOHH(string cycle) { foreach (Subscription subscription in Subscriptions) { if (subscription.Type.Equals("Upload") && HasCurrentCycle(subscription.Cycle, cycle)) { RequestHandler.startUploadOHH(ServiceAddress.GetUploadURL(Settings, User, subscription), subscription, Settings.BackupData); } } }
public ActionResult Edit([Bind(Include = "Id,DateModified,DateCreated")] ServiceAddress serviceAddress) { if (ModelState.IsValid) { db.Entry(serviceAddress).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(serviceAddress)); }
/// <summary> /// Gets a secure RPC proxy for the provided interface. /// </summary> /// <typeparam name="IT">The interface type.</typeparam> /// <param name="node">The node.</param> /// <param name="address">The service address.</param> /// <param name="configuration">The configuration.</param> /// <returns></returns> public static IT SecureProxy <IT>(this Node node, ServiceAddress address, SecureChannelConfiguration configuration) { // create channel SecureClientChannel channel = new SecureClientChannel(configuration); channel.Reset(node, address); // create proxy return(channel.Proxy <IT>()); }
/// <summary> /// Gets an RPC proxy for the provided interface. /// </summary> /// <typeparam name="IT">The interface type.</typeparam> /// <param name="address">The service address.</param> /// <param name="configuration">The configuration.</param> /// <returns></returns> public IT Proxy <IT>(ServiceAddress address, ProxyConfiguration configuration) { // create the channel BasicChannel channel = new BasicChannel(); channel.Reset(this, address); // create proxy return(channel.Proxy <IT>(configuration)); }
/// <summary> /// Creates an instance of the <see cref="T:Aneka.UI.Reporting.ReportManager"/> /// and initializes it with the given <see cref="T:Aneka.Entity.ServiceAddress"/> /// and <see cref="T:Aneka.Security.UserCredentials"/>. /// </summary> public ReportManager(ServiceAddress serviceAddress, UserCredentials userCredentials) { this.serviceAddress = serviceAddress; this.userCredentials = userCredentials; this.securityToken = userCredentials.ToByte(); }