Example #1
0
        public O getObserver(MetricsHelper <T> helper, O del)
        {
            OImpl o = getObserver(helper);

            if (o != null)
            {
                o.setDelegate(del);
                return(o);
            }
            return(del);
        }
Example #2
0
        public O?GetObserver(MetricsHelper <T> helper, O?del)
        {
            OImpl?o = GetObserver(helper);

            if (o != null)
            {
                o.SetDelegate(del);
                return(o);
            }
            return(del);
        }
Example #3
0
        private void Init()
        {
            _maxDispatchedCheckpoint = 0;
            DumpProjections();

            TenantContext.Enter(_config.TenantId);

            _housekeeper.Init();

            _eventstore = Wireup
                          .Init()
                          .LogTo(t => new NEventStoreLog4NetLogger(LoggerFactory.Create(t)))
                          .UsingMongoPersistence(() => _config.EventStoreConnectionString, new DocumentObjectSerializer())
                          .InitializeStorageEngine()
                          .Build();

            ConfigureProjections();

            // cleanup
            _housekeeper.RemoveAll(_eventstore.Advanced);

            var allSlots = _projectionsBySlot.Keys.ToArray();

            var allClients = new List <ICommitPollingClient> ();

            //recreate all polling clients.
            foreach (var bucket in _config.BucketInfo)
            {
                var client = _pollingClientFactory.Create(_eventstore.Advanced, "bucket: " + String.Join(",", bucket.Slots));
                allClients.Add(client);
                _bucketToClient.Add(bucket, client);
            }

            _clients = allClients.ToArray();

            foreach (var slotName in allSlots)
            {
                MetricsHelper.CreateMeterForDispatcherCountSlot(slotName);
                var startCheckpoint = GetStartCheckpointForSlot(slotName);
                Logger.InfoFormat("Slot {0} starts from {1}", slotName, startCheckpoint);

                var name = slotName;
                //find right consumer
                var slotBucket = _config.BucketInfo.SingleOrDefault(b =>
                                                                    b.Slots.Any(s => s.Equals(slotName, StringComparison.OrdinalIgnoreCase))) ??
                                 _config.BucketInfo.Single(b => b.Slots[0] == "*");
                var client = _bucketToClient[slotBucket];
                client.AddConsumer(commit => DispatchCommit(commit, name, startCheckpoint));
            }

            MetricsHelper.SetProjectionEngineCurrentDispatchCount(() => _countOfConcurrentDispatchingCommit);
        }
Example #4
0
        static void Main(string[] args)
        {
            var runtimeInfo = PlatformServices.Default.Application.RuntimeFramework;

            Console.WriteLine("Platform full name is {0}", runtimeInfo.FullName);
            Console.WriteLine("Identifier is {0}", runtimeInfo.Identifier);
            Console.WriteLine("Profile is {0}", runtimeInfo.Profile);
            Console.WriteLine("Version is {0}", runtimeInfo.Version);

            Console.WriteLine("GPU temp is " + MetricsHelper.GpuTemp());
            Console.WriteLine("CPU temp is " + MetricsHelper.CpuTemp());
            Console.WriteLine("Memory CPU/GPU is " + MetricsHelper.DedicatedMemoryCpu() + "/" + MetricsHelper.DedicatedMemoryGpu());
        }
        public void SetUp(IProjection[] projections, int version)
        {
            var versionInfo = _checkpoints.FindOneById("VERSION");

            if (versionInfo == null)
            {
                versionInfo = new Checkpoint("VERSION", "0");
            }

            int currentVersion = int.Parse(versionInfo.Value);

            string projectionStartFormCheckpointValue = new LongCheckpoint(0).Value;

            if (currentVersion == 0)
            {
                var eventsVersion = _checkpoints.FindOneById("events");
                if (eventsVersion != null)
                {
                    projectionStartFormCheckpointValue = eventsVersion.Value;
                }
            }

            //set all projection to active = false
            _checkpoints.Update(
                Query <Checkpoint> .NE(c => c.Slot, null),
                Update <Checkpoint> .Set(c => c.Active, false),
                UpdateFlags.Multi
                );

            foreach (var projection in projections)
            {
                Add(projection, projectionStartFormCheckpointValue);
            }

            // mark db
            if (version > currentVersion)
            {
                versionInfo.Value = new LongCheckpoint(version).Value;
                _checkpoints.Save(versionInfo);
            }

            foreach (var slot in projections.Select(p => p.GetSlotName()).Distinct())
            {
                var slotName = slot;
                MetricsHelper.SetCheckpointCountToDispatch(slot, () => GetCheckpointCount(slotName));
                _checkpointSlotTracker[slot] = 0;
                _slotRebuildTracker[slot]    = false;
            }

            MetricsHelper.SetCheckpointCountToDispatch("", GetCheckpointMaxCount);
        }
Example #6
0
        private bool Match(string attribute, Regex regex, MetricsHelper <T> helper, bool reject)
        {
            string value;

            try
            {
                value = helper.Resolve(attribute);
            }
            catch (Exception)
            {
                return(!reject);
            }
            return(regex.IsMatch(value));
        }
Example #7
0
        public Observer getObserver <S, ObserverImpl, Observer>(string mapName, MetricsHelper <S> helper, Observer del)
            where S : Metrics, new()
            where ObserverImpl : ObserverWithDelegate <S, Observer>, Observer, new()
            where Observer : Ice.Instrumentation.Observer
        {
            ObserverImpl obsv = base.getObserver <S, ObserverImpl>(mapName, helper);

            if (obsv != null)
            {
                obsv.setDelegate(del);
                return((Observer)obsv);
            }
            return(del);
        }
Example #8
0
        public Observer?GetObserver <S, ObserverImpl, Observer>(string mapName, MetricsHelper <S> helper, Observer?del)
            where S : Metrics, new()
            where ObserverImpl : ObserverWithDelegate <S, Observer>, Observer, new()
            where Observer : class, IObserver
        {
            ObserverImpl?obsv = GetObserver <S, ObserverImpl>(mapName, helper);

            if (obsv != null)
            {
                obsv.SetDelegate(del);
                return(obsv);
            }
            return(del);
        }
Example #9
0
        public O?GetObserver(MetricsHelper <T> helper, object?observer)
        {
            lock (this)
            {
                List <MetricsMap <T> .Entry>?metricsObjects = null;
                O?old = null;
                try
                {
                    old = (O?)observer;
                }
                catch (InvalidCastException)
                {
                }
                foreach (MetricsMap <T> m in _maps)
                {
                    MetricsMap <T> .Entry?e = m.GetMatching(helper, old?.GetEntry(m));
                    if (e != null)
                    {
                        if (metricsObjects == null)
                        {
                            metricsObjects = new List <MetricsMap <T> .Entry>(_maps.Count);
                        }
                        metricsObjects.Add(e);
                    }
                }

                if (metricsObjects == null)
                {
                    if (old != null)
                    {
                        old.Detach();
                    }
                    return(null);
                }

                O obsv;
                try
                {
                    obsv = new O();
                }
                catch (Exception)
                {
                    Debug.Assert(false);
                    return(null);
                }
                obsv.Init(metricsObjects, old);
                return(obsv);
            }
        }
Example #10
0
        addEndpointAttributes <T>(MetricsHelper <T> .AttributeResolver r, Type cl) where T : IceMX.Metrics
        {
            r.add("endpoint", cl.GetMethod("getEndpoint"));

            Type cli = typeof(Ice.EndpointInfo);

            r.add("endpointType", cl.GetMethod("getEndpointInfo"), cli.GetMethod("type"));
            r.add("endpointIsDatagram", cl.GetMethod("getEndpointInfo"), cli.GetMethod("datagram"));
            r.add("endpointIsSecure", cl.GetMethod("getEndpointInfo"), cli.GetMethod("secure"));
            r.add("endpointTimeout", cl.GetMethod("getEndpointInfo"), cli.GetField("timeout"));
            r.add("endpointCompress", cl.GetMethod("getEndpointInfo"), cli.GetField("compress"));

            cli = typeof(Ice.IPEndpointInfo);
            r.add("endpointHost", cl.GetMethod("getEndpointInfo"), cli.GetField("host"));
            r.add("endpointPort", cl.GetMethod("getEndpointInfo"), cli.GetField("port"));
        }
Example #11
0
        AddEndpointAttributes <T>(MetricsHelper <T> .AttributeResolver r, Type cl) where T : IceMX.Metrics
        {
            r.Add("endpoint", cl.GetMethod("GetEndpoint") !);

            Type cli = typeof(EndpointInfo);

            r.Add("endpointType", cl.GetMethod("GetEndpointInfo") !, cli.GetMethod("Type") !);
            r.Add("endpointIsDatagram", cl.GetMethod("GetEndpointInfo") !, cli.GetMethod("Datagram") !);
            r.Add("endpointIsSecure", cl.GetMethod("GetEndpointInfo") !, cli.GetMethod("Secure") !);
            r.Add("endpointTimeout", cl.GetMethod("GetEndpointInfo") !, cli.GetField("Timeout") !);
            r.Add("endpointCompress", cl.GetMethod("GetEndpointInfo") !, cli.GetField("Compress") !);

            cli = typeof(IPEndpointInfo);
            r.Add("endpointHost", cl.GetMethod("GetEndpointInfo") !, cli.GetField("Host") !);
            r.Add("endpointPort", cl.GetMethod("GetEndpointInfo") !, cli.GetField("Port") !);
        }
Example #12
0
        public void EvaluateFxAssets()
        {
            List <string> metrics = new List <string> {
                "ImpliedQuote"
            };
            List <string> keys = new List <string> {
                "AUDUSD-FxForward-1D", "AUDUSD-FxSpot-SP", "AUDUSD-FxForward-1M"
            };
            var valuations = Engine.EvaluateMetricsForAssetSet(metrics, _fxcurveId, keys, DateTime.Today);

            object[,] result = MetricsHelper.BuildEvaluationResults(keys, metrics, valuations.assetQuote);
            Assert.AreEqual(keys[0], result[0, 0]);
            Assert.AreEqual("ImpliedQuote", result[0, 1]);
            Assert.AreEqual(typeof(decimal), result[0, 2].GetType());
            Assert.AreNotEqual(0, result[0, 2]);
        }
        private void Callback(object state)
        {
            ClockedData data = new ClockedData();

            try
            {
                data.CpuTemp = MetricsHelper.CpuTemp();
                data.GpuTemp = MetricsHelper.GpuTemp();
            }
            catch (Exception ex)
            {
                this.m_logger.LogError(ex, "Error creating clocked metrics");
            }
            data.Date = DateTime.Now;
            this.m_hub.Clients.All.InvokeAsync("data", data);
        }
Example #14
0
 public void StartManualPolling(
     String checkpointTokenFrom,
     Int32 bufferSize  = 4000,
     String pollerName = "CommitPollingClient")
 {
     _bufferSize             = bufferSize;
     _checkpointTokenCurrent = checkpointTokenFrom;
     LastException           = null;
     //prepare single poller thread.
     CreateTplChain();
     _pollerThread = new Thread(PollerFunc);
     _pollerThread.IsBackground = true;
     _pollerThread.Name         = pollerName;
     _pollerThread.Start();
     MetricsHelper.SetCommitPollingClientBufferSize(pollerName, () => GetClientBufferSize());
 }
Example #15
0
        AddEndpointAttributes <T>(MetricsHelper <T> .AttributeResolver r, Type cl) where T : Metrics
        {
            r.Add("endpoint", cl.GetMethod("GetEndpoint") !);

            Type cli = typeof(Endpoint);

            r.Add("endpointType", cl.GetMethod("GetEndpoint") !, cli.GetProperty("Type") !);
            r.Add("endpointIsDatagram", cl.GetMethod("GetEndpoint") !, cli.GetProperty("IsDatagram") !);
            r.Add("endpointIsSecure", cl.GetMethod("GetEndpoint") !, cli.GetProperty("IsSecure") !);
            r.Add("endpointTimeout", cl.GetMethod("GetEndpoint") !, cli.GetProperty("Timeout") !);
            r.Add("endpointCompress", cl.GetMethod("GetEndpoint") !, cli.GetProperty("HasCompressionFlag") !);

            cli = typeof(IPEndpoint);
            r.Add("endpointHost", cl.GetMethod("GetEndpoint") !, cli.GetField("Host") !);
            r.Add("endpointPort", cl.GetMethod("GetEndpoint") !, cli.GetField("Port") !);
        }
Example #16
0
        public void Init(MetricsHelper <T> helper, List <MetricsMap <T> .Entry> objects, Observer <T>?previous)
        {
            _objects = objects;

            if (previous == null)
            {
                return;
            }

            _previousDelay = previous._previousDelay + (long)(previous.ElapsedTicks / (Frequency / 1000000.0));
            foreach (MetricsMap <T> .Entry e in previous._objects)
            {
                if (!_objects.Contains(e))
                {
                    e.Detach(_previousDelay);
                }
            }
        }
Example #17
0
        private void Init()
        {
            _maxDispatchedCheckpoint = 0;
            DumpProjections();

            _stopping = new ManualResetEventSlim(false);
            TenantContext.Enter(_config.TenantId);

            _housekeeper.Init();

            _eventstore = Wireup
                          .Init()
                          .LogTo(t => new NEventStoreLog4NetLogger(LoggerFactory.Create(t)))
                          .UsingMongoPersistence(() => _config.EventStoreConnectionString, new DocumentObjectSerializer())
                          .InitializeStorageEngine()
                          .Build();

            ConfigureProjections();

            // cleanup
            _housekeeper.RemoveAll(_eventstore.Advanced);

            var allSlots = _projectionsBySlot.Keys.ToArray();

            _client.Create(_eventstore.Advanced, _config.PollingMsInterval);

            var subscriptions = new List <IDisposable>();

            _observeCommits = _client.ObserveFrom(GetStartGlobalCheckpoint());

            foreach (var slotName in allSlots)
            {
                MetricsHelper.CreateMeterForDispatcherCountSlot(slotName);
                var startCheckpoint = GetStartCheckpointForSlot(slotName);
                Logger.InfoFormat("Slot {0} starts from {1}", slotName, startCheckpoint);

                var name = slotName;
                subscriptions.Add(
                    _observeCommits.Subscribe(commit => DispatchCommit(commit, name, LongCheckpoint.Parse(startCheckpoint)),
                                              HandleError));
            }

            _subscriptions = subscriptions.ToArray();
        }
Example #18
0
        public void Evaluate()
        {
            var metrics = new List <string> {
                "ImpliedQuote", "MarketQuote"
            };
            var keys = new List <string> {
                "AUD-CPIndex-1D", "AUD-CPIndex-2M", "AUD-ZCCPISwap-2Y"
            };
            var valuations = ExcelApi.ExcelAPITests.Engine.EvaluateMetricsForAssetSet(metrics, _curveId, keys, DateTime.Today);

            object[,] result = MetricsHelper.BuildEvaluationResults(metrics, valuations.assetQuote);
            Assert.AreEqual(keys[0], result[0, 0]);
            Assert.AreEqual(metrics[0], result[0, 1]);
            Assert.AreEqual(typeof(decimal), result[0, 2].GetType());
            Assert.AreNotEqual(0, result[0, 2]);
            Assert.AreEqual(metrics[1], result[0, 3]);
            Assert.AreEqual(typeof(decimal), result[0, 4].GetType());
            Assert.AreNotEqual(0, result[0, 4]);
        }
Example #19
0
        AddConnectionAttributes <T>(MetricsHelper <T> .AttributeResolver r, Type cl) where T : Metrics
        {
            Type cli = typeof(ConnectionInfo);

            r.Add("incoming", cl.GetMethod("GetConnectionInfo") !, cli.GetField("Incoming") !);
            r.Add("adapterName", cl.GetMethod("GetConnectionInfo") !, cli.GetField("AdapterName") !);
            r.Add("connectionId", cl.GetMethod("GetConnectionInfo") !, cli.GetField("ConnectionId") !);

            cli = typeof(IPConnectionInfo);
            r.Add("localHost", cl.GetMethod("GetConnectionInfo") !, cli.GetField("LocalAddress") !);
            r.Add("localPort", cl.GetMethod("GetConnectionInfo") !, cli.GetField("LocalPort") !);
            r.Add("remoteHost", cl.GetMethod("GetConnectionInfo") !, cli.GetField("RemoteAddress") !);
            r.Add("remotePort", cl.GetMethod("GetConnectionInfo") !, cli.GetField("RemotePort") !);

            cli = typeof(UDPConnectionInfo);
            r.Add("mcastHost", cl.GetMethod("GetConnectionInfo") !, cli.GetField("McastAddress") !);
            r.Add("mcastPort", cl.GetMethod("GetConnectionInfo") !, cli.GetField("McastPort") !);

            AddEndpointAttributes(r, cl);
        }
Example #20
0
        addConnectionAttributes <T>(MetricsHelper <T> .AttributeResolver r, Type cl) where T : IceMX.Metrics
        {
            Type cli = typeof(Ice.ConnectionInfo);

            r.add("incoming", cl.GetMethod("getConnectionInfo"), cli.GetField("incoming"));
            r.add("adapterName", cl.GetMethod("getConnectionInfo"), cli.GetField("adapterName"));
            r.add("connectionId", cl.GetMethod("getConnectionInfo"), cli.GetField("connectionId"));

            cli = typeof(Ice.IPConnectionInfo);
            r.add("localHost", cl.GetMethod("getConnectionInfo"), cli.GetField("localAddress"));
            r.add("localPort", cl.GetMethod("getConnectionInfo"), cli.GetField("localPort"));
            r.add("remoteHost", cl.GetMethod("getConnectionInfo"), cli.GetField("remoteAddress"));
            r.add("remotePort", cl.GetMethod("getConnectionInfo"), cli.GetField("remotePort"));

            cli = typeof(Ice.UDPConnectionInfo);
            r.add("mcastHost", cl.GetMethod("getConnectionInfo"), cli.GetField("mcastAddress"));
            r.add("mcastPort", cl.GetMethod("getConnectionInfo"), cli.GetField("mcastPort"));

            AttrsUtil.addEndpointAttributes <T>(r, cl);
        }
Example #21
0
        public void Global_initialization_of_all_tests()
        {
            MetricsHelper.InitMetrics(new MetricsBuilder());

            //Nunit3 fix for test adapter of visual studio, it uses visual studio test directory
            Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MongoRegistration.ConfigureMongoForJarvisFramework(
                "NEventStore.Persistence.MongoDB"
                );
            MongoFlatMapper.EnableFlatMapping(true);
            MongoRegistration.RegisterAssembly(GetType().Assembly);
            var overrideTestDb = Environment.GetEnvironmentVariable("TEST_MONGODB");

            if (String.IsNullOrEmpty(overrideTestDb))
            {
                return;
            }

            Console.WriteLine("Mongodb database is overriden with TEST_MONGODB environment variable:" + overrideTestDb);
            var overrideTestDbQueryString = Environment.GetEnvironmentVariable("TEST_MONGODB_QUERYSTRING") ?? "";

            overrideTestDbQueryString = overrideTestDbQueryString.Trim();
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

            connectionStringsSection.ConnectionStrings["eventstore"].ConnectionString = overrideTestDb.TrimEnd('/') + "/jarvis-framework-es-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["saga"].ConnectionString       = overrideTestDb.TrimEnd('/') + "/jarvis-framework-saga-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["readmodel"].ConnectionString  = overrideTestDb.TrimEnd('/') + "/jarvis-framework-readmodel-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["system"].ConnectionString     = overrideTestDb.TrimEnd('/') + "/jarvis-framework-system-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["engine"].ConnectionString     = overrideTestDb.TrimEnd('/') + "/jarvis-framework-engine-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["rebus"].ConnectionString      = overrideTestDb.TrimEnd('/') + "/jarvis-rebus-test" + overrideTestDbQueryString;
            connectionStringsSection.ConnectionStrings["log"].ConnectionString        = overrideTestDb.TrimEnd('/') + "/jarvis-log-test" + overrideTestDbQueryString;

            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");

            TestLogger.GlobalEnabled = false;
        }
Example #22
0
            internal MetricsMap <S> .Entry?GetMatching <S>(string mapName, MetricsHelper <S> helper)
                where S : Metrics, new()
            {
                ISubMap?m;

                lock (_map)
                {
                    if (_subMaps == null || !_subMaps.TryGetValue(mapName, out m))
                    {
                        m = _map.CreateSubMap(mapName);
                        if (m == null)
                        {
                            return(null);
                        }
                        if (_subMaps == null)
                        {
                            _subMaps = new Dictionary <string, ISubMap>();
                        }
                        _subMaps.Add(mapName, m);
                    }
                }
                return(((SubMap <S>)m).GetMatching(helper));
            }
        private void RegisterHealthChecks(string pollerName)
        {
            MetricsHelper.SetCommitPollingClientBufferSize(pollerName, () => GetClientBufferSize());
            //Set health check for polling
            HealthChecks.RegisterHealthCheck("Polling-" + pollerName, () =>
            {
                if (Status == CommitPollingClientStatus.Stopped)
                {
                    //poller is stopped, system healty
                    return(HealthCheckResult.Healthy("Automatic polling stopped"));
                }
                else if (Status == CommitPollingClientStatus.Faulted || LastException != null)
                {
                    //poller is stopped, system healty
                    var exceptionText = (LastException != null ? LastException.ToString() : "");
                    exceptionText     = exceptionText.Replace("{", "{{").Replace("}", "}}");
                    return(HealthCheckResult.Unhealthy("Faulted (exception in consumer): " + exceptionText));
                }
                var elapsed = DateTime.UtcNow - _innerClient.LastActivityTimestamp;
                if (elapsed.TotalMilliseconds > 5000)
                {
                    //more than 5 seconds without a poll, polling probably is stopped
                    return(HealthCheckResult.Unhealthy(String.Format("poller stuck, last polling {0} ms ago", elapsed)));
                }

                return(HealthCheckResult.Healthy("Poller alive"));
            });
            //Now register health check for the internal NES poller, to diagnose errors in polling.
            HealthChecks.RegisterHealthCheck("Polling internal errors: ", () =>
            {
                if (_innerClient != null && !String.IsNullOrEmpty(_innerClient.LastPollingError))
                {
                    return(HealthCheckResult.Unhealthy($"Inner NES poller has error: {_innerClient.LastPollingError}"));
                }
                return(HealthCheckResult.Healthy("Inner NES Poller Ok"));
            });
        }
Example #24
0
        internal O?GetObserver(MetricsHelper <T> helper, object?observer)
        {
            lock (_mutex)
            {
                List <MetricsMap <T> .Entry>?metricsObjects = null;
                var old = observer as O;

                foreach (MetricsMap <T> m in _maps)
                {
                    MetricsMap <T> .Entry?e = m.GetMatching(helper, old?.GetEntry(m));
                    if (e != null)
                    {
                        metricsObjects ??= new List <MetricsMap <T> .Entry>(_maps.Count);
                        metricsObjects.Add(e);
                    }
                }

                if (metricsObjects == null)
                {
                    old?.Detach();
                    return(null);
                }

                try
                {
                    var obsv = new O();
                    obsv.Init(metricsObjects, old);
                    return(obsv);
                }
                catch (Exception ex)
                {
                    Debug.Assert(false, ex.ToString());
                    return(null);
                }
            }
        }
        private bool RunOneTest(string testName, BaseTest test)
        {
            bool      result    = true;
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            try
            {
                logger.Info("Executing test: " + testName);

                result = test.Execute();
                if (!result)
                {
                    logger.Error("Error in running test: " + testName);
                }
                else
                {
                    logger.Info("Successful in running test: " + testName);
                }
            }
            catch (Exception e)
            {
                result = false;
                logger.Error("Error while running test: " + testName + ". Exception: " + e);
            }

            stopWatch.Stop();

            MetricsHelper.PushTestMetric(Convert.ToInt64(stopWatch.Elapsed.TotalSeconds),
                                         this.SuiteName,
                                         testName,
                                         result.ToString());

            return(result);
        }
Example #26
0
        public ObserverImpl?GetObserver <S, ObserverImpl>(string mapName, MetricsHelper <S> helper)
            where S : Metrics, new()
            where ObserverImpl : Observer <S>, new()
        {
            List <MetricsMap <S> .Entry>?metricsObjects = null;

            foreach (MetricsMap <T> .Entry entry in _objects !)
            {
                MetricsMap <S> .Entry?e = entry.GetMatching(mapName, helper);
                if (e != null)
                {
                    if (metricsObjects == null)
                    {
                        metricsObjects = new List <MetricsMap <S> .Entry>(_objects.Count);
                    }
                    metricsObjects.Add(e);
                }
            }

            if (metricsObjects == null)
            {
                return(null);
            }

            try
            {
                var obsv = new ObserverImpl();
                obsv.Init(metricsObjects, null);
                return(obsv);
            }
            catch (Exception)
            {
                Debug.Assert(false);
                return(null);
            }
        }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData = modelData;
            switch (ModelIdentifier)
            {
            case "CapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;

            case "DiscountCapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;
            }
            var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics);
            // Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored
            var bEvalLastForewardVolatiltiy = false;

            if (metrics.Contains(RateOptionMetrics.VolatilityAtExpiry))
            {
                bEvalLastForewardVolatiltiy = true;
                metrics.RemoveAll(
                    metricItem => metricItem != RateOptionMetrics.VolatilityAtExpiry);
            }
            var metricsToEvaluate = metrics.ToArray();
            IRateOptionAssetParameters analyticModelParameters = new RateOptionAssetParameters();

            AnalyticResults = new RateOptionAssetResults();
            var marketEnvironment = modelData.MarketEnvironment;

            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                DiscountCurve     = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                DiscountCurveName = DiscountCurve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurve     = DiscountCurve;
                ForecastCurveName = DiscountCurveName;
                var volatilities = CreateList((double)Volatility, TimesToExpiry.Count);
                analyticModelParameters.Volatilities = volatilities;
            }
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                DiscountCurve       = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                DiscountCurveName   = DiscountCurve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurve       = ((ISwapLegEnvironment)marketEnvironment).GetForecastRateCurve();
                ForecastCurveName   = ForecastCurve.GetPricingStructureId().UniqueIdentifier;
                VolatilityCurve     = ((ISwapLegEnvironment)marketEnvironment).GetVolatilitySurface();
                VolatilityCurveName = VolatilityCurve.GetPricingStructureId().UniqueIdentifier;
                analyticModelParameters.Volatilities = GetVolatilties(VolatilityCurve, TimesToExpiry, Strikes);
            }
            if (marketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                if (DiscountCurveName != null)
                {
                    DiscountCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(DiscountCurveName);
                }
                if (ForecastCurveName != null)
                {
                    ForecastCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(ForecastCurveName);
                }
                if (VolatilityCurveName != null)
                {
                    VolatilityCurve = (IVolatilitySurface)modelData.MarketEnvironment.GetPricingStructure(VolatilityCurveName);
                }
                analyticModelParameters.Volatilities = GetVolatilties(VolatilityCurve, TimesToExpiry, Strikes);
            }
            analyticModelParameters.FlatVolatility = Volatility;
            //2. Set the premium
            if (Premium == null)
            {
                Premium = CalculatePremium();
            }
            if (Premium != null)
            {
                analyticModelParameters.Premium = (double)Premium;
            }
            if (bEvalLastForewardVolatiltiy)
            {
                //3. Set the start diccount factor and vol.
                analyticModelParameters.PremiumPaymentDiscountFactor =
                    GetDiscountFactor(DiscountCurve, AdjustedStartDate, modelData.ValuationDate);
                //4. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                               metricsToEvaluate);
            }
            else
            {
                analyticModelParameters.IsDiscounted = false;
                analyticModelParameters.IsPut        = !IsCap;
                analyticModelParameters.Notionals    = Notionals;
                analyticModelParameters.ForwardRates = ResetRates;
                //2. Get the discount factors
                analyticModelParameters.PaymentDiscountFactors =
                    GetDiscountFactors(DiscountCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                analyticModelParameters.ForecastDiscountFactors =
                    GetDiscountFactors(ForecastCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //3. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                analyticModelParameters.Strikes       = Strikes;
                analyticModelParameters.Rate          = (double)CalculateImpliedParRate(modelData.ValuationDate);
                analyticModelParameters.TimesToExpiry = TimesToExpiry;
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                               metricsToEvaluate);
            }
            return(GetValue(AnalyticResults));
        }
Example #28
0
 internal void Attach(MetricsHelper <T> helper)
 {
     ++_object.Total;
     ++_object.Current;
     helper.InitMetrics(_object);
 }
Example #29
0
 internal MetricsMap <S> .Entry?GetMatching(MetricsHelper <S> helper) => _map.GetMatching(helper, null);
Example #30
0
        public Entry?GetMatching(MetricsHelper <T> helper, Entry?previous)
        {
            //
            // Check the accept and reject filters.
            //
            foreach (KeyValuePair <string, Regex> e in _accept)
            {
                if (!Match(e.Key, e.Value, helper, false))
                {
                    return(null);
                }
            }

            foreach (KeyValuePair <string, Regex> e in _reject)
            {
                if (Match(e.Key, e.Value, helper, true))
                {
                    return(null);
                }
            }

            //
            // Compute the key from the GroupBy property.
            //
            string key;

            try
            {
                if (_groupByAttributes.Count == 1)
                {
                    key = helper.Resolve(_groupByAttributes[0]);
                }
                else
                {
                    var os = new StringBuilder();
                    IEnumerator <string> q = _groupBySeparators.GetEnumerator();
                    foreach (string p in _groupByAttributes)
                    {
                        os.Append(helper.Resolve(p));
                        if (q.MoveNext())
                        {
                            os.Append(q.Current);
                        }
                    }
                    key = os.ToString();
                }
            }
            catch (Exception)
            {
                return(null);
            }

            //
            // Lookup the metrics object.
            //
            lock (this)
            {
                if (previous != null && previous.GetId().Equals(key))
                {
                    Debug.Assert(_objects[key] == previous);
                    return(previous);
                }

                if (!_objects.TryGetValue(key, out MetricsMap <T> .Entry? e))
                {
                    try
                    {
                        var t = new T();
                        t.Id = key;
                        e    = new Entry(this, t);
                        _objects.Add(key, e);
                    }
                    catch (Exception)
                    {
                        Debug.Assert(false);
                    }
                }
                e.Attach(helper);
                return(e);
            }
        }