Esempio n. 1
0
        private GrainInterfaceData GetOrAddGrainInterfaceData(Type iface, bool isGenericGrainClass)
        {
            var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface);

            // If already exist
            GrainInterfaceData grainInterfaceData;

            if (table.TryGetValue(interfaceId, out grainInterfaceData))
            {
                return(grainInterfaceData);
            }

            // If not create new entry
            var interfaceName = TypeUtils.GetRawClassName(TypeUtils.GetFullName(iface));

            grainInterfaceData = new GrainInterfaceData(interfaceId, iface, interfaceName);
            table[interfaceId] = grainInterfaceData;

            // Add entry to mapping iface string -> data
            var interfaceTypeKey = GetTypeKey(iface, isGenericGrainClass);

            typeToInterfaceData[interfaceTypeKey] = grainInterfaceData;

            // If we are adding a concrete implementation of a generic interface
            // add also the latter to the map: GrainReference and InvokeMethodRequest
            // always use the id of the generic one
            if (iface.IsConstructedGenericType)
            {
                GetOrAddGrainInterfaceData(iface.GetGenericTypeDefinition(), true);
            }

            return(grainInterfaceData);
        }
Esempio n. 2
0
        public static List <T> ObjectToList <T>(object data)
        {
            if (data is List <T> )
            {
                return((List <T>)data);
            }

            T[] dataArray;
            if (data is ArrayList)
            {
                dataArray = (T[])(data as ArrayList).ToArray(typeof(T));
            }
            else if (data is ICollection <T> )
            {
                dataArray = (data as ICollection <T>).ToArray();
            }
            else
            {
                throw new InvalidCastException(string.Format(
                                                   "Connet convert type {0} to type List<{1}>",
                                                   TypeUtils.GetFullName(data.GetType()),
                                                   TypeUtils.GetFullName(typeof(T))));
            }
            var list = new List <T>();

            list.AddRange(dataArray);
            return(list);
        }
Esempio n. 3
0
        public IDictionary <string, GrainTypeData> GetGrainClassTypes(bool strict)
        {
            var result = new Dictionary <string, GrainTypeData>();
            IDictionary <string, Type> grainStateTypes = GetGrainStateTypes(strict);

            Type[] grainTypes = strict
                ? TypeUtils.GetTypes(TypeUtils.IsConcreteGrainClass).ToArray()
                : TypeUtils.GetTypes(discoveredAssemblyLocations, TypeUtils.IsConcreteGrainClass).ToArray();

            foreach (var grainType in grainTypes)
            {
                var className = TypeUtils.GetFullName(grainType);
                if (result.ContainsKey(className))
                {
                    throw new InvalidOperationException(
                              string.Format("Precondition violated: GetLoadedGrainTypes should not return a duplicate type ({0})", className));
                }

                var  parameterizedName = grainType.Namespace + "." + TypeUtils.GetParameterizedTemplateName(grainType);
                Type grainStateType;
                grainStateTypes.TryGetValue(parameterizedName, out grainStateType);
                GrainTypeData typeData = GetTypeData(grainType, grainStateType);
                result.Add(className, typeData);
            }

            LogGrainTypesFound(logger, result);
            return(result);
        }
Esempio n. 4
0
 public GrainTypeData(Type type, Type stateObjectType)
 {
     Type                 = type;
     IsReentrant          = Type.GetCustomAttributes(typeof(ReentrantAttribute), true).Length > 0;
     IsStatelessWorker    = Type.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Length > 0;
     GrainClass           = TypeUtils.GetFullName(type);
     RemoteInterfaceTypes = GetRemoteInterfaces(type);;
     StateObjectType      = stateObjectType;
 }
Esempio n. 5
0
 public GrainTypeData(Type type)
 {
     Type             = type;
     this.IsReentrant = type.GetCustomAttributes(typeof(ReentrantAttribute), true).Any();
     // TODO: shouldn't this use GrainInterfaceUtils.IsStatelessWorker?
     this.IsStatelessWorker = type.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any();
     this.GrainClass        = TypeUtils.GetFullName(type);
     RemoteInterfaceTypes   = GetRemoteInterfaces(type);
     this.MayInterleave     = GetMayInterleavePredicate(type) ?? (_ => false);
 }
Esempio n. 6
0
        public IDictionary <string, GrainTypeData> GetGrainClassTypes(bool strict)
        {
            var result = new Dictionary <string, GrainTypeData>();

            Type[] grainTypes = strict
                ? TypeUtils.GetTypes(TypeUtils.IsConcreteGrainClass, logger).ToArray()
                : TypeUtils.GetTypes(discoveredAssemblyLocations, TypeUtils.IsConcreteGrainClass, logger).ToArray();

            foreach (var grainType in grainTypes)
            {
                var className = TypeUtils.GetFullName(grainType);
                if (excludedGrains.Contains(className))
                {
                    continue;
                }

                if (result.ContainsKey(className))
                {
                    throw new InvalidOperationException(
                              string.Format("Precondition violated: GetLoadedGrainTypes should not return a duplicate type ({0})", className));
                }

                Type grainStateType = null;

                // check if grainType derives from Grai<nT> where T is a concrete class

                var parentType = grainType.GetTypeInfo().BaseType;
                while (parentType != typeof(Grain) && parentType != typeof(object))
                {
                    TypeInfo parentTypeInfo = parentType.GetTypeInfo();
                    if (parentTypeInfo.IsGenericType)
                    {
                        var definition = parentTypeInfo.GetGenericTypeDefinition();
                        if (definition == typeof(Grain <>) || definition == typeof(LogConsistentGrainBase <>))
                        {
                            var stateArg = parentType.GetGenericArguments()[0];
                            if (stateArg.GetTypeInfo().IsClass || stateArg.GetTypeInfo().IsValueType)
                            {
                                grainStateType = stateArg;
                                break;
                            }
                        }
                    }

                    parentType = parentTypeInfo.BaseType;
                }

                GrainTypeData typeData = GetTypeData(grainType, grainStateType);
                result.Add(className, typeData);
            }

            LogGrainTypesFound(logger, result);
            return(result);
        }
Esempio n. 7
0
        public GrainTypeData(Type type, Type stateObjectType)
        {
            var typeInfo = type.GetTypeInfo();

            Type        = type;
            IsReentrant = typeInfo.GetCustomAttributes(typeof(ReentrantAttribute), true).Any();
            // TODO: shouldn't this use GrainInterfaceUtils.IsStatelessWorker?
            IsStatelessWorker    = typeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any();
            GrainClass           = TypeUtils.GetFullName(typeInfo);
            RemoteInterfaceTypes = GetRemoteInterfaces(type);;
            StateObjectType      = stateObjectType;
        }
Esempio n. 8
0
        public IDictionary <string, GrainTypeData> GetGrainClassTypes(bool strict)
        {
            var result = new Dictionary <string, GrainTypeData>();
            IDictionary <string, Type> grainStateTypes = GetGrainStateTypes(strict);

            Type[] grainTypes = strict
                ? TypeUtils.GetTypes(TypeUtils.IsConcreteGrainClass).ToArray()
                : TypeUtils.GetTypes(discoveredAssemblyLocations, TypeUtils.IsConcreteGrainClass).ToArray();

            foreach (var grainType in grainTypes)
            {
                var className = TypeUtils.GetFullName(grainType);
                if (result.ContainsKey(className))
                {
                    throw new InvalidOperationException(
                              string.Format("Precondition violated: GetLoadedGrainTypes should not return a duplicate type ({0})", className));
                }

                var  parameterizedName = grainType.Namespace + "." + TypeUtils.GetParameterizedTemplateName(grainType);
                Type grainStateType;
                grainStateTypes.TryGetValue(parameterizedName, out grainStateType);

                if (grainStateType == null) // check if grainType derives from Grain<T> where T is a concrete class
                {
                    var parentType = grainType.BaseType;
                    while (parentType != typeof(Grain) && parentType != typeof(object))
                    {
                        if (parentType.IsGenericType)
                        {
                            var definition = parentType.GetGenericTypeDefinition();
                            if (definition == typeof(Grain <>))
                            {
                                var stateArg = parentType.GetGenericArguments()[0];
                                if (stateArg.IsClass)
                                {
                                    grainStateType = stateArg;
                                    break;
                                }
                            }
                        }

                        parentType = parentType.BaseType;
                    }
                }

                GrainTypeData typeData = GetTypeData(grainType, grainStateType);
                result.Add(className, typeData);
            }

            LogGrainTypesFound(logger, result);
            return(result);
        }
Esempio n. 9
0
        public GrainTypeData(Type type, MultiClusterRegistrationStrategyManager registrationManager)
        {
            var typeInfo = type.GetTypeInfo();

            Type        = type;
            IsReentrant = typeInfo.GetCustomAttributes(typeof(ReentrantAttribute), true).Any();
            // TODO: shouldn't this use GrainInterfaceUtils.IsStatelessWorker?
            IsStatelessWorker                = typeInfo.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any();
            GrainClass                       = TypeUtils.GetFullName(typeInfo);
            RemoteInterfaceTypes             = GetRemoteInterfaces(type);
            MayInterleave                    = GetMayInterleavePredicate(typeInfo) ?? (_ => false);
            MultiClusterRegistrationStrategy = registrationManager?.GetMultiClusterRegistrationStrategy(type);
        }
Esempio n. 10
0
 private static T CheckReturnBoundaryReference <T>(string what, T obj) where T : class
 {
     if (obj == null)
     {
         return(null);
     }
     if (obj is MarshalByRefObject || obj is ISerializable)
     {
         // Referernce to the provider can safely be passed across app-domain boundary in unit test process
         return(obj);
     }
     throw new InvalidOperationException(string.Format("Cannot return reference to {0} {1} if it is not MarshalByRefObject or Serializable",
                                                       what, TypeUtils.GetFullName(obj.GetType())));
 }
Esempio n. 11
0
 internal static string GetTypeKey(Type interfaceType, bool isGenericGrainClass)
 {
     if (isGenericGrainClass && interfaceType.IsGenericType)
     {
         return(interfaceType.GetGenericTypeDefinition().AssemblyQualifiedName);
     }
     else
     {
         return(TypeUtils.GetTemplatedName(
                    TypeUtils.GetFullName(interfaceType),
                    interfaceType,
                    interfaceType.GetGenericArguments(),
                    t => false));
     }
 }
Esempio n. 12
0
        internal void AddEntry(Type iface, Type grain, PlacementStrategy placement, MultiClusterRegistrationStrategy registrationStrategy, bool primaryImplementation)
        {
            lock (this)
            {
                var grainTypeInfo       = grain.GetTypeInfo();
                var grainName           = TypeUtils.GetFullName(grainTypeInfo);
                var isGenericGrainClass = grainTypeInfo.ContainsGenericParameters;
                var grainTypeCode       = GrainInterfaceUtils.GetGrainClassTypeCode(grain);

                var grainInterfaceData = GetOrAddGrainInterfaceData(iface, isGenericGrainClass);

                var implementation = new GrainClassData(grainTypeCode, grainName, isGenericGrainClass);
                if (!implementationIndex.ContainsKey(grainTypeCode))
                {
                    implementationIndex.Add(grainTypeCode, implementation);
                }
                if (!placementStrategiesIndex.ContainsKey(grainTypeCode))
                {
                    placementStrategiesIndex.Add(grainTypeCode, placement);
                }
                if (!registrationStrategiesIndex.ContainsKey(grainTypeCode))
                {
                    registrationStrategiesIndex.Add(grainTypeCode, registrationStrategy);
                }

                grainInterfaceData.AddImplementation(implementation, primaryImplementation);
                if (primaryImplementation)
                {
                    primaryImplementations[grainInterfaceData.GrainInterface] = grainName;
                }
                else
                {
                    if (!primaryImplementations.ContainsKey(grainInterfaceData.GrainInterface))
                    {
                        primaryImplementations.Add(grainInterfaceData.GrainInterface, grainName);
                    }
                }

                if (localTestMode)
                {
                    var assembly = grainTypeInfo.Assembly.CodeBase;
                    if (!loadedGrainAsemblies.Contains(assembly))
                    {
                        loadedGrainAsemblies.Add(assembly);
                    }
                }
            }
        }
Esempio n. 13
0
        private string GetTypeKey(Type interfaceType, bool isGenericGrainClass)
        {
            var typeInfo = interfaceType.GetTypeInfo();

            if (isGenericGrainClass && typeInfo.IsGenericType)
            {
                return(typeInfo.GetGenericTypeDefinition().AssemblyQualifiedName);
            }
            else
            {
                return(TypeUtils.GetTemplatedName(
                           TypeUtils.GetFullName(interfaceType),
                           interfaceType,
                           interfaceType.GetGenericArguments(),
                           t => false));
            }
        }
Esempio n. 14
0
        private void AddToGrainInterfaceToClassMap(Type grainClass, IEnumerable <Type> grainInterfaces, bool isUnordered)
        {
            var grainClassCompleteName = TypeUtils.GetFullName(grainClass);
            var grainClassTypeCode     = CodeGeneration.GrainInterfaceData.GetGrainClassTypeCode(grainClass);
            var placement = GrainTypeData.GetPlacementStrategy(grainClass);

            foreach (var iface in grainInterfaces)
            {
                var ifaceCompleteName    = TypeUtils.GetFullName(iface);
                var ifaceName            = TypeUtils.GetRawClassName(ifaceCompleteName);
                var isPrimaryImplementor = IsPrimaryImplementor(grainClass, iface);
                var ifaceId = CodeGeneration.GrainInterfaceData.GetGrainInterfaceId(iface);
                grainInterfaceMap.AddEntry(ifaceId, iface, grainClassTypeCode, ifaceName, grainClassCompleteName, grainClass.Assembly.CodeBase,
                                           placement, isPrimaryImplementor);
            }

            if (isUnordered)
            {
                grainInterfaceMap.AddToUnorderedList(grainClassTypeCode);
            }
        }
Esempio n. 15
0
        private static Dictionary <string, GrainTypeData> CreateGrainTypeMap(GrainClassFeature grainClassFeature, GrainClassOptions grainClassOptions)
        {
            var result = new Dictionary <string, GrainTypeData>();

            var excluded = grainClassOptions.ExcludedGrainTypes;

            foreach (var grainClassMetadata in grainClassFeature.Classes)
            {
                var grainType = grainClassMetadata.ClassType;
                var className = TypeUtils.GetFullName(grainType);

                if (excluded != null && excluded.Contains(className))
                {
                    continue;
                }

                result[className] = new GrainTypeData(grainType);
            }

            return(result);
        }
Esempio n. 16
0
        internal void AddEntry(Type iface, Type grain, PlacementStrategy placement, string directory, bool primaryImplementation)
        {
            lock (this)
            {
                var grainName           = TypeUtils.GetFullName(grain);
                var isGenericGrainClass = grain.ContainsGenericParameters;
                var grainTypeCode       = GrainInterfaceUtils.GetGrainClassTypeCode(grain);

                var grainInterfaceData = GetOrAddGrainInterfaceData(iface, isGenericGrainClass);

                var implementation = new GrainClassData(grainTypeCode, grainName, isGenericGrainClass);
                if (!implementationIndex.ContainsKey(grainTypeCode))
                {
                    implementationIndex.Add(grainTypeCode, implementation);
                }
                if (!placementStrategiesIndex.ContainsKey(grainTypeCode))
                {
                    placementStrategiesIndex.Add(grainTypeCode, placement);
                }
                if (!directoriesIndex.ContainsKey(grainTypeCode))
                {
                    directoriesIndex.Add(grainTypeCode, directory);
                }

                grainInterfaceData.AddImplementation(implementation, primaryImplementation);
                if (primaryImplementation)
                {
                    primaryImplementations[grainInterfaceData.GrainInterface] = grainName;
                }
                else
                {
                    if (!primaryImplementations.ContainsKey(grainInterfaceData.GrainInterface))
                    {
                        primaryImplementations.Add(grainInterfaceData.GrainInterface, grainName);
                    }
                }
            }
        }
Esempio n. 17
0
        private void AddToGrainInterfaceToClassMap(Type grainClass, IEnumerable <Type> grainInterfaces, bool isUnordered)
        {
            var grainTypeInfo          = grainClass.GetTypeInfo();
            var grainClassCompleteName = TypeUtils.GetFullName(grainTypeInfo);
            var isGenericGrainClass    = grainTypeInfo.ContainsGenericParameters;
            var grainClassTypeCode     = GrainInterfaceUtils.GetGrainClassTypeCode(grainClass);
            var placement            = GrainTypeData.GetPlacementStrategy(grainClass, this.defaultPlacementStrategy);
            var registrationStrategy = GrainTypeData.GetMultiClusterRegistrationStrategy(grainClass);

            foreach (var iface in grainInterfaces)
            {
                var ifaceCompleteName    = TypeUtils.GetFullName(iface);
                var ifaceName            = TypeUtils.GetRawClassName(ifaceCompleteName);
                var isPrimaryImplementor = IsPrimaryImplementor(grainClass, iface);
                var ifaceId = GrainInterfaceUtils.GetGrainInterfaceId(iface);
                grainInterfaceMap.AddEntry(ifaceId, iface, grainClassTypeCode, ifaceName, grainClassCompleteName,
                                           grainTypeInfo.Assembly.CodeBase, isGenericGrainClass, placement, registrationStrategy, isPrimaryImplementor);
            }

            if (isUnordered)
            {
                grainInterfaceMap.AddToUnorderedList(grainClassTypeCode);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// This method crawls the assemblies and looks for the index
        /// definitions (determined by extending IIndexable{TProperties}
        /// interface and adding annotations to properties in TProperties).
        ///
        /// In order to avoid having any dependency on OrleansIndexing
        /// project, all the required types are loaded via reflection.
        /// </summary>
        /// <param name="strict">determines the lookup strategy for
        /// looking into the assemblies</param>
        /// <returns>A dictionary of grain interface types to their
        /// corresponding index information. The index information is
        /// a dictionary from index IDs defined on a grain interface to
        /// a triple. The triple consists of: 1) the index object (that
        /// implements IndexInterface, 2) the IndexMetaData object for
        /// this index, and 3) the IndexUpdateGenerator instance for this index.
        /// This triple is untyped, because IndexInterface, IndexMetaData
        /// and IndexUpdateGenerator types are not visible in this project.
        ///
        /// This method returns an empty dictionary if the OrleansIndexing
        /// project is not available.
        /// </returns>
        public IDictionary <Type, IDictionary <string, Tuple <object, object, object> > > GetGrainClassIndexes(bool strict)
        {
            var result = new Dictionary <Type, IDictionary <string, Tuple <object, object, object> > >();

            try
            {
                //iIndexableGrainType = Type.GetType("Orleans.Indexing.IIndexableGrain, OrleansIndexing");
                genericIIndexableGrainType             = Type.GetType("Orleans.Indexing.IIndexableGrain`1" + AssemblySeparator + OrleansIndexingAssembly);
                genericFaultTolerantIndexableGrainType = Type.GetType("Orleans.Indexing.IndexableGrain`1" + AssemblySeparator + OrleansIndexingAssembly);
                indexAttributeType = Type.GetType("Orleans.Indexing.IndexAttribute" + AssemblySeparator + OrleansIndexingAssembly);
                indexTypeProperty  = indexAttributeType.GetProperty("IndexType");
                indexFactoryType   = Type.GetType("Orleans.Indexing.IndexFactory" + AssemblySeparator + OrleansIndexingAssembly);
                createIndexMethod  = (Func <IGrainFactory, Type, string, bool, bool, int, PropertyInfo, Tuple <object, object, object> >)Delegate.CreateDelegate(
                    typeof(Func <IGrainFactory, Type, string, bool, bool, int, PropertyInfo, Tuple <object, object, object> >),
                    indexFactoryType.GetMethod("CreateIndex", BindingFlags.Static | BindingFlags.NonPublic));
                registerIndexWorkflowQueuesMethod = (Action <Type, Type>)Delegate.CreateDelegate(
                    typeof(Action <Type, Type>),
                    indexFactoryType.GetMethod("RegisterIndexWorkflowQueues", BindingFlags.Static | BindingFlags.NonPublic));
                isEagerProperty             = indexAttributeType.GetProperty("IsEager");
                isUniqueProperty            = indexAttributeType.GetProperty("IsUnique");
                maxEntriesPerBucketProperty = indexAttributeType.GetProperty("MaxEntriesPerBucket");
                totalIndexType = Type.GetType("Orleans.Indexing.TotalIndex" + AssemblySeparator + OrleansIndexingAssembly);
            }
            catch
            {
                //indexing project is not added as a dependency.
                return(result);
            }

            Type[] grainTypes = strict
                ? TypeUtils.GetTypes(TypeUtils.IsConcreteGrainClass, logger).ToArray()
                : TypeUtils.GetTypes(discoveredAssemblyLocations, TypeUtils.IsConcreteGrainClass, logger).ToArray();

            //for all discovered grain types
            foreach (var grainType in grainTypes)
            {
                if (result.ContainsKey(grainType))
                {
                    throw new InvalidOperationException(
                              string.Format("Precondition violated: GetLoadedGrainTypes should not return a duplicate type ({0})", TypeUtils.GetFullName(grainType)));
                }
                GetIndexesForASingleGrainType(result, grainType);
            }
            return(result);
        }
Esempio n. 19
0
        private static void CheckAllIndexesAreEitherLazyOrEager(Type propertiesArg, Type userDefinedIGrain, Type userDefinedGrainImpl)
        {
            bool isFaultTolerant = TypeUtils.IsSubclassOfRawGenericType(genericFaultTolerantIndexableGrainType, userDefinedGrainImpl);

            foreach (PropertyInfo p in propertiesArg.GetProperties())
            {
                var  indexAttrs        = p.GetCustomAttributes(indexAttributeType, false);
                bool isFirstIndexEager = false;
                if (indexAttrs.Count() > 0)
                {
                    isFirstIndexEager = (bool)isEagerProperty.GetValue(indexAttrs[0]);
                }
                foreach (var indexAttr in indexAttrs)
                {
                    bool isEager      = (bool)isEagerProperty.GetValue(indexAttr);
                    Type indexType    = (Type)indexTypeProperty.GetValue(indexAttr);
                    bool isTotalIndex = totalIndexType.IsAssignableFrom(indexType);

                    //Total Index cannot be configured as being lazy
                    if (isTotalIndex && isEager)
                    {
                        throw new InvalidOperationException(string.Format("A Total Index cannot be configured to be updated eagerly. The only option for updating a Total Index is lazy updating. Total Index of type {0} is defined to be updated eagerly on property {1} of class {2} on {3} grain interface.", TypeUtils.GetFullName(indexType), p.Name, TypeUtils.GetFullName(propertiesArg), TypeUtils.GetFullName(userDefinedIGrain)));
                    }
                    else if (isFaultTolerant && isEager)
                    {
                        throw new InvalidOperationException(string.Format("A fault-tolerant grain implementation cannot be configured to eagerly update its indexes. The only option for updating the indexes of a fault-tolerant indexable grain is lazy updating. The index of type {0} is defined to be updated eagerly on property {1} of class {2} on {3} grain implementation class.", TypeUtils.GetFullName(indexType), p.Name, TypeUtils.GetFullName(propertiesArg), TypeUtils.GetFullName(userDefinedGrainImpl)));
                    }
                    else if (isEager != isFirstIndexEager)
                    {
                        throw new InvalidOperationException(string.Format("Some indexes on property class {0} of {1} grain interface are defined to be updated eagerly while others are configured as lazy updating. You should fix this by configuring all indexes to be updated lazily or eagerly. If you have at least one Total Index among your indexes, then all other indexes should be configured as lazy, too.", TypeUtils.GetFullName(propertiesArg), TypeUtils.GetFullName(userDefinedIGrain)));
                    }
                }
            }
        }