public async Task <ActionResult <BaseResponse> > StopJob(string id) { var job = _jobStore.QueryJob(id); if (job == null) { return(BaseResponse.GetResponse("任务不存在")); } if (job.Status > (int)JobStatus.Stop) { var service = new ServiceRouteDescriptor(job.NodeHost, job.NodePort); var result = await _schedulerRemoting.StopJob(job.Id, service); if (result) { job.Status = (int)JobStatus.Stop; job.NextRunTime = null; var updatedProperties = new Expression <Func <JobEntity, object> >[] { p => p.Status, p => p.NextRunTime }; result = _jobStore.UpdateEntity(job, updatedProperties); if (!result) { await _schedulerRemoting.ResumeJob(job.Id, service); } } return(BaseResponse.GetResponse(result)); } return(BaseResponse.GetResponse("任务在当前状态下不能停止")); }
public T Get(ServiceRouteDescriptor service) { var callInvoker = new ClientCallInvoker(service, _endpointStrategy, _config.MaxRetry); var client = (T)Activator.CreateInstance(typeof(T), callInvoker); return(client); }
public ServerCallInvoker Get(ServiceRouteDescriptor service) { var target = GetTarget(service); if (_channels.TryGetValue(target, out Channel channel)) { return(new ServerCallInvoker(channel)); } lock (_lock) { if (!_channels.TryGetValue(target, out channel)) { var channelOptions = new List <ChannelOption>() { new ChannelOption(ChannelOptions.MaxReceiveMessageLength, int.MaxValue), new ChannelOption(ChannelOptions.MaxSendMessageLength, int.MaxValue) }; channel = new Channel(target, ChannelCredentials.Insecure, channelOptions); _channels.AddOrUpdate(target, channel, (key, value) => channel); } return(new ServerCallInvoker(channel)); } }
public async Task <bool> UploadFile(List <string> filePaths, ServiceRouteDescriptor service) { var client = _fileClientFactory.Get(service); var response = await FileTransfer.FileUpload(client, filePaths, Guid.NewGuid().ToString()); return(response.IsSuccess); }
public Task <bool> StartJob(JobEntity job, ServiceRouteDescriptor service) { var client = _clientFactory.Get(service); var jobRequest = Utils.MapperGrpcJob <JobEntity, Job>(job); var response = client.StartJob(jobRequest); return(Task.FromResult(response.Success)); }
public async Task <bool> UploadFile(string filePath, ServiceRouteDescriptor service) { var filePaths = new List <string>(1) { filePath }; return(await UploadFile(filePaths, service)); }
public static ServiceRouteDescriptor ConvertToDescriptor(this ServiceRoute serviceRoute) { var descriptor = new ServiceRouteDescriptor() { ServiceDescriptor = serviceRoute.ServiceDescriptor, AddressDescriptors = serviceRoute.Addresses.Select(p => p.Descriptor).ToArray() }; return(descriptor); }
public Task <bool> RunJobOnceNow(string jobId, ServiceRouteDescriptor service) { var client = _clientFactory.Get(service); var response = client.RunJobOnceNow(new Job() { Id = jobId }); return(Task.FromResult(response.Success)); }
public void Release(ServiceRouteDescriptor serviceRouteDescriptor) { lock (_syncLock) { if (_dic.ContainsKey(serviceRouteDescriptor)) { var count = _dic[serviceRouteDescriptor]; _dic.TryUpdate(serviceRouteDescriptor, count - 1, count); } } }
public async Task <bool> DeRegisterService(ServiceRouteDescriptor service) { var client = _consulClientProvider.GetClient(); if (client == null) { return(false); } var response = await client.Agent.ServiceDeregister(service.Id); return(response.StatusCode == HttpStatusCode.OK); }
private async Task <bool> SetRouteAsync(ServiceRouteDescriptor route, ConsulClient client) { var nodeData = _serializer.Serialize(route); _logger.LogDebug($"准备设置服务路由信息:{Encoding.UTF8.GetString(nodeData)}。"); var keyValuePair = new KVPair($"{_configInfo.RoutePath}{route.ServiceDescriptor.Id}") { Value = nodeData }; await client.KV.Put(keyValuePair); return(true); }
protected override async Task <bool> SetRouteAsync(ServiceRouteDescriptor route) { try { _logger.LogDebug($"准备添加{route.ServiceDescriptor.Id}服务路由。"); var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients(); foreach (var zooKeeperClient in zooKeeperClients) { await CreateSubdirectory(zooKeeperClient, _configInfo.RoutePath); var path = _configInfo.RoutePath; if (!path.EndsWith("/")) { path += "/"; } var nodePath = $"{path}{route.ServiceDescriptor.Id}"; var nodeData = _serializer.Serialize(route); _logger.LogDebug($"服务路由内容为:{Encoding.UTF8.GetString(nodeData)}。"); if (!nodeWatchers.ContainsKey(nodePath)) { var watcher = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData))); await zooKeeperClient.SubscribeDataChange(nodePath, watcher.HandleNodeDataChange); } if (!await zooKeeperClient.ExistsAsync(nodePath)) { _logger.LogDebug($"节点:{nodePath}不存在将进行创建。"); await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } else { var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray(); if (!DataEquals(nodeData, onlineData)) { await zooKeeperClient.SetDataAsync(nodePath, nodeData); _logger.LogDebug($"{nodePath}节点的缓存的服务路由与服务注册中心不一致,路由数据已被更新。"); } } } return(true); } catch (Exception ex) { _logger.LogError($"{route.ServiceDescriptor.Id}服务的路由注册失败,原因:{ex.Message}"); return(false); } }
public ConsulHostedService(IServiceRoute serviceRoute, RegisterServiceConfig registerServiceConfig) { _serviceRoute = serviceRoute; _registerServiceConfig = registerServiceConfig; _registerSrvice = new ServiceRouteDescriptor() { Id = ObjectId.Default().NextString(), Name = _registerServiceConfig.Name, Address = _registerServiceConfig.Address, Port = _registerServiceConfig.Port, HealthCheckType = _registerServiceConfig.HealthCheckType, HealthCheck = _registerServiceConfig.HealthCheck }; }
public virtual Task SetRouteAsync(ServiceRoute route) { if (route == null) { throw new ArgumentNullException(nameof(route)); } var descriptor = new ServiceRouteDescriptor { AddressDescriptors = route.Address?.Select(address => new ServiceAddressDescriptor { Value = _serializer.Serialize(address) }) ?? Enumerable.Empty <ServiceAddressDescriptor>(), ServiceDescriptor = route.ServiceDescriptor }; return(SetRouteAsync(descriptor)); }
protected override async Task <bool> SetRouteAsync(ServiceRouteDescriptor route) { var hostAddr = NetUtils.GetHostAddress(); var clients = await _consulClientProvider.GetClients(); foreach (var client in clients) { var nodeData = _serializer.Serialize(route); _logger.LogDebug($"准备设置服务路由信息:{Encoding.UTF8.GetString(nodeData)}。"); var keyValuePair = new KVPair($"{_configInfo.RoutePath}{route.ServiceDescriptor.Id}") { Value = nodeData }; await client.KV.Put(keyValuePair); } return(true); }
public async Task <bool> RegisterService(ServiceRouteDescriptor service) { var client = _consulClientProvider.GetClient(); if (client == null) { return(false); } var checkId = GenCheckId(service); var checkName = GenCheckName(service); var agentCheck = new AgentCheckRegistration { ID = checkId, Name = checkName, Interval = TimeSpan.FromMilliseconds(_config.ServiceCheckInterval), Status = HealthStatus.Passing, DeregisterCriticalServiceAfter = TimeSpan.FromMilliseconds(_config.ServiceCriticalInterval), }; switch (service.HealthCheckType.ToLower()) { case "http": agentCheck.HTTP = service.HealthCheck; break; case "tcp": agentCheck.TCP = service.HealthCheck; break; } var agentService = new AgentServiceRegistration { ID = service.Id, Name = service.Name, Address = service.Address, Port = service.Port, Tags = service.Tags, Check = agentCheck }; var response = await client.Agent.ServiceRegister(agentService); return(response.StatusCode == HttpStatusCode.OK); }
public void Revoke(ServiceRouteDescriptor service, ServerCallInvoker failedCallInvoker) { lock (_lock) { if (failedCallInvoker == null) { return; } var failedChannel = failedCallInvoker.Channel; if (!_channels.TryGetValue(GetTarget(service), out Channel channel)) { return; } _channels.TryRemove(failedChannel.Target, out failedChannel); // add black TODO failedChannel.ShutdownAsync(); } }
/// <summary> /// 设置服务路由。 /// </summary> /// <param name="routes">服务路由集合。</param> /// <returns>一个任务。</returns> public virtual Task SetRoutesAsync(IEnumerable <ServiceRoute> routes) { if (routes == null) { throw new ArgumentNullException(nameof(routes)); } var descriptors = routes.Where(route => route != null).Select(route => { var descriptor = new ServiceRouteDescriptor { AddressDescriptors = route.Address?.Select(address => new ServiceAddressDescriptor { Value = _serializer.Serialize(address) }) ?? Enumerable.Empty <ServiceAddressDescriptor>(), ServiceDescriptor = route.ServiceDescriptor }; descriptor.ServiceDescriptor.TimeStamp = DateTimeConverter.DateTimeToUnixTimestamp(DateTime.Now); return(descriptor); }); return(SetRoutesAsync(descriptors)); }
public async Task <bool> DownloadFile(string fileName, string saveDirectoryPath, ServiceRouteDescriptor service) { var fileNames = new List <string>(1) { fileName }; return(await DownloadFile(fileNames, saveDirectoryPath, service)); }
private static string GetKey(ServiceRouteDescriptor descriptor) { return(descriptor.Id); }
public ClientCallInvoker(ServiceRouteDescriptor service, IEndpointStrategy endpointStrategy, int maxRetry = 0) { _service = service; _strategy = endpointStrategy; _maxRetry = maxRetry; }
public void Release(ServiceRouteDescriptor serviceRouteDescriptor) { }
protected async Task RegisterRouteWithLockAsync(ServiceRouteDescriptor serviceRouteDescriptor) { using var locker = await _lockerProvider.CreateLockAsync(serviceRouteDescriptor.ServiceDescriptor.Id); await locker.Lock(async() => { await RegisterRouteAsync(serviceRouteDescriptor); }); }
public async Task <bool> DownloadFile(List <string> fileNames, string saveDirectoryPath, ServiceRouteDescriptor service) { var client = _fileClientFactory.Get(service); var response = await FileTransfer.FileDownload(client, fileNames, Guid.NewGuid().ToString(), saveDirectoryPath); return(response.IsSuccess); }
protected abstract Task <bool> SetRouteAsync(ServiceRouteDescriptor route);
private string GenCheckName(ServiceRouteDescriptor service) { return($"c{service.Name}"); }
protected override async Task <bool> SetRouteAsync(ServiceRouteDescriptor route) { throw new NotImplementedException(); }
private string GetTarget(ServiceRouteDescriptor service) { return($"{service.Address}:{service.Port}"); }
protected abstract Task RegisterRouteAsync(ServiceRouteDescriptor serviceRouteDescriptor);
private string GenCheckId(ServiceRouteDescriptor service) { return($"c{service.Id}"); }