Пример #1
0
        public async Task RegisterServiceAsync(string serviceName, string groupName, Instance instance)
        {
            _logger?.LogInformation("[REGISTER-SERVICE] {0} registering service {1} with instance: {2}", namespaceId, serviceName, instance);

            string groupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);

            if (instance.Ephemeral)
            {
                BeatInfo beatInfo = beatReactor.BuildBeatInfo(groupedServiceName, instance);
                beatReactor.AddBeatInfo(groupedServiceName, beatInfo);
            }

            var paramters = new Dictionary <string, string>()
            {
                { CommonParams.NAMESPACE_ID, namespaceId },
                { CommonParams.SERVICE_NAME, groupedServiceName },
                { CommonParams.GROUP_NAME, groupName },
                { CommonParams.CLUSTER_NAME, instance.ClusterName },
                { CommonParams.IP_PARAM, instance.Ip },
                { CommonParams.PORT_PARAM, instance.Port.ToString() },
                { CommonParams.WEIGHT_PARAM, instance.Weight.ToString() },
                { CommonParams.ENABLE_PARAM, instance.Enabled.ToString() },
                { CommonParams.HEALTHY_PARAM, instance.Healthy.ToString() },
                { CommonParams.EPHEMERAL_PARAM, instance.Ephemeral.ToString() },
                { CommonParams.META_PARAM, instance.Metadata.ToJsonString() },
            };

            await ReqApi(UtilAndComs.NacosUrlInstance, paramters, HttpMethod.Post).ConfigureAwait(false);
        }
Пример #2
0
        public async Task RegisterServiceAsync(string serviceName, string groupName, Instance instance)
        {
            _logger?.LogInformation("[REGISTER-SERVICE] {0} registering service {1} with instance: {2}", namespaceId, serviceName, instance);

            string groupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);

            if (instance.Ephemeral)
            {
                BeatInfo beatInfo = beatReactor.BuildBeatInfo(groupedServiceName, instance);
                beatReactor.AddBeatInfo(groupedServiceName, beatInfo);
            }

            var paramters = new Dictionary <string, string>()
            {
                { CommonParams.NAMESPACE_ID, namespaceId },
                { CommonParams.SERVICE_NAME, groupedServiceName },
                { CommonParams.GROUP_NAME, groupName },
                { CommonParams.CLUSTER_NAME, instance.ClusterName },
                { "ip", instance.Ip },
                { "port", instance.Port.ToString() },
                { "weight", instance.Weight.ToString() },
                { "enable", instance.Enabled.ToString() },
                { "healthy", instance.Healthy.ToString() },
                { "ephemeral", instance.Ephemeral.ToString() },
                { "metadata", instance.Metadata.ToJsonString() },
            };

            await ReqApi(UtilAndComs.NacosUrlInstance, paramters, HttpMethod.Post);
        }
        public ClassDeclarationSyntax StubMethod(ClassDeclarationSyntax classDclr, IMethodSymbol methodSymbol, INamedTypeSymbol stubbedInterface, SemanticModel semanticModel)
        {
            if (!methodSymbol.IsOrdinaryMethod())
            {
                return(classDclr);
            }

            MethodDeclarationSyntax methodDclr = SF.MethodDeclaration(
                SF.ParseTypeName(methodSymbol.ReturnType.GetFullyQualifiedName()), methodSymbol.GetGenericName());

            methodDclr = methodDclr.WithParameterList(methodDclr.ParameterList.AddParameters(
                                                          RoslynUtils.GetMethodParameterSyntaxList(methodSymbol).ToArray()));
            methodDclr = methodDclr.WithSemicolonToken(SF.Token(SyntaxKind.None))
                         .WithExplicitInterfaceSpecifier(
                SF.ExplicitInterfaceSpecifier(
                    SF.IdentifierName(methodSymbol.GetContainingInterfaceGenericQualifiedName())));

            string delegateTypeName = NamingUtils.GetDelegateTypeName(methodSymbol, stubbedInterface);
            string parameters       = StubbingUtils.FormatParameters(methodSymbol);
            var    outParameters    = methodSymbol.Parameters.Where(p => p.RefKind == RefKind.Out);

            var methodBlock = StubbingUtils.GetInvocationBlockSyntax(delegateTypeName, methodSymbol.GetGenericName(),
                                                                     parameters, outParameters, methodSymbol.ReturnType, semanticModel);

            classDclr = classDclr.AddMembers(methodDclr.WithBody(methodBlock));

            return(classDclr);
        }
Пример #4
0
        public async Task <ServiceInfo> QueryInstancesOfService(string serviceName, string groupName, string clusters, int udpPort, bool healthyOnly)
        {
            string groupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);

            var paramters = new Dictionary <string, string>()
            {
                { CommonParams.NAMESPACE_ID, namespaceId },
                { CommonParams.SERVICE_NAME, groupedServiceName },
                { CommonParams.CLUSTER_NAME, clusters },
                { "udpPort", udpPort.ToString() },

                // TODO:
                { "clientIP", "127.0.0.1" },
                { "healthyOnly", healthyOnly.ToString() },
            };

            var result = await ReqApi(UtilAndComs.NacosUrlBase + "/instance/list", paramters, HttpMethod.Get);

            if (!string.IsNullOrWhiteSpace(result))
            {
                return(result.ToObj <ServiceInfo>());
            }

            return(new ServiceInfo(groupedServiceName, clusters));
        }
Пример #5
0
        /// <summary>
        /// Cache registered instance for redo.
        /// </summary>
        /// <param name="serviceName">service name</param>
        /// <param name="groupName">group name</param>
        /// <param name="instance">registered instance</param>
        public void CacheInstanceForRedo(string serviceName, string groupName, Instance instance)
        {
            string key      = NamingUtils.GetGroupedName(serviceName, groupName);
            var    redoData = InstanceRedoData.Build(serviceName, groupName, instance);

            _registeredInstances.AddOrUpdate(key, redoData, (x, y) => redoData);
        }
Пример #6
0
        /// <summary>
        /// Cache subscriber for redo.
        /// </summary>
        /// <param name="serviceName">service name</param>
        /// <param name="groupName">group name</param>
        /// <param name="cluster">cluster</param>
        public void CacheSubscriberForRedo(string serviceName, string groupName, string cluster)
        {
            string key      = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), cluster);
            var    redoData = SubscriberRedoData.Build(serviceName, groupName, cluster);

            _subscribes.AddOrUpdate(key, redoData, (x, y) => redoData);
        }
Пример #7
0
        /// <summary>
        /// Ensure that the current skin is in a state it can accept user modifications.
        /// This will create a copy of any internal skin and being tracking in the database if not already.
        /// </summary>
        public void EnsureMutableSkin()
        {
            CurrentSkinInfo.Value.PerformRead(s =>
            {
                if (!s.Protected)
                {
                    return;
                }

                string[] existingSkinNames = realm.Run(r => r.All <SkinInfo>()
                                                       .Where(skin => !skin.DeletePending)
                                                       .AsEnumerable()
                                                       .Select(skin => skin.Name).ToArray());

                // if the user is attempting to save one of the default skin implementations, create a copy first.
                var skinInfo = new SkinInfo
                {
                    Creator           = s.Creator,
                    InstantiationInfo = s.InstantiationInfo,
                    Name = NamingUtils.GetNextBestName(existingSkinNames, $"{s.Name} (modified)")
                };

                var result = skinModelManager.Import(skinInfo);

                if (result != null)
                {
                    // save once to ensure the required json content is populated.
                    // currently this only happens on save.
                    result.PerformRead(skin => Save(skin.CreateInstance(this)));
                    CurrentSkinInfo.Value = result;
                }
            });
        }
Пример #8
0
 protected virtual void ValidateResourceName(string name)
 {
     if (!NamingUtils.IsValidResourceName(name))
     {
         throw new ArgumentException($"The resource name {name} is not valid! Only alphanumeric characters, dots, underscores and dashes are allowed! Also please note that two or more subsequent dots, underscores and dashes are reserved for internal use, and are allowed only in the middle of the resource name.");
     }
 }
Пример #9
0
        public CompilationUnitSyntax StubInterface(CompilationUnitSyntax cu, InterfaceDeclarationSyntax interfaceDclr,
                                                   SemanticModel semanticModel)
        {
            INamedTypeSymbol           interfaceType = semanticModel.GetDeclaredSymbol(interfaceDclr);
            NamespaceDeclarationSyntax namespaceNode = GetNamespaceNode(interfaceDclr);
            string interfaceName             = interfaceType.GetGenericName();
            string stubName                  = NamingUtils.GetStubName(interfaceName);
            ClassDeclarationSyntax classDclr = SF.ClassDeclaration(SF.Identifier(stubName))
                                               .AddModifiers(SF.Token(RoslynUtils.GetVisibilityKeyword(interfaceType)))
                                               .WithBaseList(RoslynUtils.BaseList(interfaceName))
                                               .AddAttributeLists(AttributeListList(Attribute("CompilerGenerated")).ToArray());

            classDclr = RoslynUtils.CopyGenericConstraints(interfaceType, classDclr);
            classDclr = AddStubContainerField(classDclr, stubName);
            classDclr = StubProperties(interfaceType, classDclr);
            classDclr = StubMethods(interfaceType, classDclr);

            string fullNameSpace = semanticModel.GetDeclaredSymbol(namespaceNode).ToString();
            NamespaceDeclarationSyntax namespaceDclr = SF.NamespaceDeclaration(SF.IdentifierName(fullNameSpace))
                                                       .WithUsings(namespaceNode.Usings);

            namespaceDclr = namespaceDclr.AddMembers(classDclr);
            cu            = cu.AddMembers(namespaceDclr);
            return(cu);
        }
        public bool IsSubscribed(string groupName, string serviceName, string clusters)
        {
            string key = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), clusters);

            return(listenerMap.TryGetValue(key, out var eventListeners) &&
                   eventListeners != null && eventListeners.Any());
        }
Пример #11
0
        public ClassDeclarationSyntax StubMethod(ClassDeclarationSyntax classDclr, IMethodSymbol methodSymbol,
                                                 INamedTypeSymbol stubbedInterface)
        {
            if (!methodSymbol.IsOrdinaryMethod())
            {
                return(classDclr);
            }

            MethodDeclarationSyntax methodDclr = SF.MethodDeclaration(
                SF.ParseTypeName(methodSymbol.ReturnType.GetFullyQualifiedName()), methodSymbol.GetGenericName());

            methodDclr = methodDclr.WithParameterList(methodDclr.ParameterList.AddParameters(
                                                          RoslynUtils.GetMethodParameterSyntaxList(methodSymbol).ToArray()));
            methodDclr = methodDclr.WithSemicolonToken(SF.Token(SyntaxKind.None))
                         .WithExplicitInterfaceSpecifier(
                SF.ExplicitInterfaceSpecifier(
                    SF.IdentifierName(methodSymbol.GetContainingInterfaceGenericQualifiedName())));

            string delegateTypeName = NamingUtils.GetDelegateTypeName(methodSymbol, stubbedInterface);
            string parameters       = StubbingUtils.FormatParameters(methodSymbol);

            string callDelegateStmt = StubbingUtils.GenerateInvokeDelegateStmt(delegateTypeName, methodSymbol.GetGenericName(), parameters);

            if (!methodSymbol.ReturnsVoid)
            {
                callDelegateStmt = callDelegateStmt.Insert(0, "return ");
            }

            classDclr = classDclr.AddMembers(
                methodDclr.WithBody(SF.Block(SF.ParseStatement(callDelegateStmt))));

            return(classDclr);
        }
        public async Task <ServiceInfo> Subscribe(string serviceName, string groupName, string clusters)
        {
            var request  = new SubscribeServiceRequest(namespaceId, serviceName, groupName, clusters, true);
            var response = await RequestToServer <SubscribeServiceResponse>(request).ConfigureAwait(false);

            namingGrpcConnectionEventListener.CacheSubscriberForRedo(NamingUtils.GetGroupedName(serviceName, groupName), clusters);
            return(response.ServiceInfo);
        }
Пример #13
0
        public async Task Unsubscribe(string serviceName, string groupName, string clusters)
        {
            var request = new SubscribeServiceRequest(namespaceId, serviceName, groupName, clusters, true);

            await RequestToServer <SubscribeServiceResponse>(request);

            namingGrpcConnectionEventListener.RemoveSubscriberForRedo(NamingUtils.GetGroupedName(serviceName, groupName), clusters);
        }
 public UpdateModel(string serviceName, string groupName, string clusters)
 {
     this.ServiceName        = serviceName;
     this.GroupName          = groupName;
     this.Clusters           = clusters;
     this.GroupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);
     this.ServiceKey         = ServiceInfo.GetKey(GroupedServiceName, clusters);
 }
Пример #15
0
        public void TestEvenMoreAlreadyTaken()
        {
            string[] existingNames = Enumerable.Range(1, 30).Select(i => $"New Difficulty ({i})").Append("New Difficulty").ToArray();

            string nextBestName = NamingUtils.GetNextBestName(existingNames, "New Difficulty");

            Assert.AreEqual("New Difficulty (31)", nextBestName);
        }
Пример #16
0
 private void RedoRegisterEachService()
 {
     foreach (var item in _registeredInstanceCached)
     {
         var serviceName = NamingUtils.GetServiceName(item.Key);
         var groupName   = NamingUtils.GetGroupName(item.Key);
         RedoRegisterEachInstance(serviceName, groupName, item.Value);
     }
 }
Пример #17
0
        /// <summary>
        /// Instance deregister, mark unregistering status as true.
        /// </summary>
        /// <param name="serviceName">service name</param>
        /// <param name="groupName">group name</param>
        public void InstanceDeregister(string serviceName, string groupName)
        {
            string key = NamingUtils.GetGroupedName(serviceName, groupName);

            if (_registeredInstances.TryGetValue(key, out var data))
            {
                data.Unregistering = true;
            }
        }
Пример #18
0
        /// <summary>
        /// Subscriber deregister, mark unregistering status as true.
        /// </summary>
        /// <param name="serviceName">service name</param>
        /// <param name="groupName">group name</param>
        /// <param name="cluster">cluster</param>
        public void SubscriberDeregister(string serviceName, string groupName, string cluster)
        {
            string key = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), cluster);

            if (_subscribes.TryGetValue(key, out var data))
            {
                data.Unregistering = true;
            }
        }
Пример #19
0
        internal void RemoveInstanceForRedo(string serviceName, string groupName, Instance instance)
        {
            string key = NamingUtils.GetGroupedName(serviceName, groupName);

            if (_registeredInstanceCached.TryGetValue(key, out var instances))
            {
                instances.Remove(instance);
            }
        }
Пример #20
0
        private void RedoRegisterEachService()
        {
            _logger?.LogInformation("Grpc re-connect, redo register services");

            foreach (var item in _registeredInstanceCached)
            {
                var serviceName = NamingUtils.GetServiceName(item.Key);
                var groupName   = NamingUtils.GetGroupName(item.Key);
                RedoRegisterEachInstance(serviceName, groupName, item.Value);
            }
        }
Пример #21
0
        public void TestAlreadyTakenWithDifferentCase()
        {
            string[] existingNames =
            {
                "new difficulty"
            };

            string nextBestName = NamingUtils.GetNextBestName(existingNames, "New Difficulty");

            Assert.AreEqual("New Difficulty (1)", nextBestName);
        }
Пример #22
0
        public void TestAlreadyTakenWithBrackets()
        {
            string[] existingNames =
            {
                "new difficulty (copy)"
            };

            string nextBestName = NamingUtils.GetNextBestName(existingNames, "New Difficulty (copy)");

            Assert.AreEqual("New Difficulty (copy) (1)", nextBestName);
        }
        internal Dtos.ServiceInfo GetServiceInfo(string serviceName, string groupName, string clusters)
        {
            string groupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);
            string key = ServiceInfo.GetKey(groupedServiceName, clusters);

            /*if (failoverReactor.isFailoverSwitch())
             * {
             *  return failoverReactor.getService(key);
             * }*/

            return(serviceInfoMap.TryGetValue(key, out var serviceInfo) ? serviceInfo : null);
        }
        public void StopUpdateIfContain(string serviceName, string groupName, string clusters)
        {
            string serviceKey = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), clusters);

            if (_timerMap.TryRemove(serviceKey, out var t))
            {
                t?.Change(Timeout.Infinite, Timeout.Infinite);
                t?.Dispose();

                _logger?.LogInformation("stop update task, servicekey:{0}", serviceKey);
            }
        }
        private static string GetArgs(IEnumerable <Argument> args)
        {
            var sb = new StringBuilder();

            sb.Append(string.Join(", ", args.Select(arg =>
            {
                var annotation = arg.TypeSignature.Type == CType.Bool ? "[MarshalAs(UnmanagedType.U1)] " : "";
                var argName    = ReplaceReserved(NamingUtils.SnakeToLowerCamel(arg.Name));
                return($"{annotation}{MapArgType(arg.TypeSignature)} {argName}");
            })));
            return(sb.ToString());
        }
Пример #26
0
        public void TestNotTaken()
        {
            string[] existingNames =
            {
                "Something",
                "Entirely",
                "Different"
            };

            string nextBestName = NamingUtils.GetNextBestName(existingNames, "New Difficulty");

            Assert.AreEqual("New Difficulty", nextBestName);
        }
Пример #27
0
        internal Dtos.ServiceInfo GetServiceInfo(string serviceName, string groupName, string clusters)
        {
            _logger?.LogDebug("failover-mode:{0}", _failoverReactor.IsFailoverSwitch());
            string groupedServiceName = NamingUtils.GetGroupedName(serviceName, groupName);
            string key = ServiceInfo.GetKey(groupedServiceName, clusters);

            if (_failoverReactor.IsFailoverSwitch())
            {
                return(_failoverReactor.GetService(key));
            }

            return(_serviceInfoMap.TryGetValue(key, out var serviceInfo) ? serviceInfo : null);
        }
Пример #28
0
        public void TestNotTakenButClose()
        {
            string[] existingNames =
            {
                "New Difficulty(1)",
                "New Difficulty (abcd)",
                "New Difficulty but not really"
            };

            string nextBestName = NamingUtils.GetNextBestName(existingNames, "New Difficulty");

            Assert.AreEqual("New Difficulty", nextBestName);
        }
        public void ScheduleUpdateIfAbsent(string serviceName, string groupName, string clusters)
        {
            string serviceKey = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), clusters);

            if (_timerMap.TryGetValue(serviceKey, out _))
            {
                return;
            }

            var task = UpdateTask(serviceName, groupName, clusters);

            _timerMap.TryAdd(serviceKey, task);
        }
        private async Task RunUpdateTask(string serviceName, string groupName, string clusters)
        {
            int delayTime  = -1;
            var serviceKey = ServiceInfo.GetKey(NamingUtils.GetGroupedName(serviceName, groupName), clusters);

            try
            {
                if (!changeNotifier.IsSubscribed(groupName, serviceName, clusters) && !_updatingMap.ContainsKey(serviceKey))
                {
                    // TODO logger
                    return;
                }

                if (!serviceInfoHolder.GetServiceInfoMap().TryGetValue(serviceKey, out var serviceObj))
                {
                    serviceObj = await namingClientProxy.QueryInstancesOfService(serviceName, groupName, clusters, 0, false);

                    serviceInfoHolder.ProcessServiceInfo(serviceObj);
                    delayTime = DEFAULT_DELAY;

                    // TODO lastRefTime serviceObj.LastRefTime
                    return;
                }

                if (serviceObj.LastRefTime <= 0)
                {
                    serviceObj = await namingClientProxy.QueryInstancesOfService(serviceName, groupName, clusters, 0, false);

                    serviceInfoHolder.ProcessServiceInfo(serviceObj);
                }

                // TODO lastRefTime serviceObj.LastRefTime
                if (serviceObj.Hosts == null || serviceObj.Hosts.Any())
                {
                    // incFailCount
                    return;
                }

                delayTime = (int)serviceObj.CacheMillis * DEFAULT_UPDATE_CACHE_TIME_MULTIPLE;

                // resetFailCount
            }
            catch (System.Exception)
            {
                // logger
            }
            finally
            {
                // next
            }
        }