public async Task <object> ExecuteEndpointAsync(ExecutionContext context, AbstractEndpoint endpoint)
 {
     return(await Task.Run(() =>
     {
         return ExecuteEndpoint(context, endpoint);
     }));
 }
        private bool IsMatch(AbstractEndpoint callback, string url, Dictionary <string, object> matchedVariables)
        {
            if (callback.Parts == null)
            {
                return(false);
            }

            var urlParts = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            for (var i = 0; i < urlParts.Length; i++)
            {
                if (i >= callback.Parts.Length)
                {
                    return(false);
                }

                if (!urlParts[i].Equals(callback.Parts[i].Value, StringComparison.OrdinalIgnoreCase) && !callback.Parts[i].IsVariable)
                {
                    return(false);
                }

                if (callback.Parts[i].IsVariable)
                {
                    matchedVariables.Add(callback.Parts[i].Value, urlParts[i]);
                }
            }

            return(true);
        }
        private void RegisterReplyMessageCorrelator()
        {
            lock (_replyMessageCorrelatorMonitor) {
                if (_replyMessageCorrelator != null)
                {
                    return;
                }
                AbstractEndpoint correlator = null;
                IMessageHandler  handler    = new LocalReplyProducingMessageHandler();

                if (_replyChannel is ISubscribableChannel)
                {
                    correlator = new EventDrivenConsumer((ISubscribableChannel)_replyChannel, handler);
                }
                else if (_replyChannel is IPollableChannel)
                {
                    PollingConsumer endpoint = new PollingConsumer(
                        (IPollableChannel)_replyChannel, handler);
                    endpoint.Trigger       = new IntervalTrigger(TimeSpan.FromMilliseconds(10));
                    endpoint.ObjectFactory = ObjectFactory;
                    endpoint.AfterPropertiesSet();
                    correlator = endpoint;
                }
                if (IsRunning)
                {
                    if (correlator == null)
                    {
                        throw new InvalidOperationException("correlator must not be null");
                    }

                    ((ILifecycle)correlator).Start();
                }
                _replyMessageCorrelator = correlator;
            }
        }
Example #4
0
        protected virtual AbstractEndpoint CreateEndpoint(IMessageHandler handler, MethodInfo method, List <Attribute> annotations)
        {
            AbstractEndpoint endpoint = null;
            var inputChannelName      = MessagingAttributeUtils.ResolveAttribute <string>(annotations, InputChannelProperty);

            if (!string.IsNullOrEmpty(inputChannelName))
            {
                IMessageChannel inputChannel;
                try
                {
                    inputChannel = ChannelResolver.ResolveDestination(inputChannelName);
                    if (inputChannel == null)
                    {
                        inputChannel = new DirectChannel(ApplicationContext, inputChannelName);
                        ApplicationContext.Register(inputChannelName, inputChannel);
                    }
                }
                catch (DestinationResolutionException)
                {
                    inputChannel = new DirectChannel(ApplicationContext, inputChannelName);
                    ApplicationContext.Register(inputChannelName, inputChannel);
                }

                endpoint = DoCreateEndpoint(handler, inputChannel, annotations);
            }

            return(endpoint);
        }
        public void Register(AbstractEndpoint callback)
        {
            if (!callback.HasCallback)
            {
                return;
            }

            logger.Debug($"Register() {callback.Name} {callback.Url} {callback.SessionId}");


            if (string.IsNullOrEmpty(callback.Url))
            {
                Unregister(callback.Name, callback.SessionId);

                if (callback.Schedule != null)
                {
                    ScheduledEndpointManager?.SetEndpointSchedule(callback);
                }

                if (callback.SessionId == null)
                {
                    Endpoints.TryAdd(callback.Name, callback);
                }
                else
                {
                    if (!SessionManager.SessionExists(callback.SessionId))
                    {
                        SessionManager.StartSession(callback.SessionId);
                    }

                    if (SessionManager.SessionExists(callback.SessionId))
                    {
                        var session = SessionManager.GetSession(callback.SessionId);
                        session.Endpoints.TryAdd(callback.Name, callback);
                    }
                }
            }
            else
            {
                if (callback.UrlRegEx == null)
                {
                    callback.Parts = callback.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Select(m => new Part(m, m.StartsWith(":"))).ToArray();

                    if (callback.Parts.GroupBy(m => m.Value).Any(m => m.Count() > 1))
                    {
                        throw new Exception("Duplicate variable name in URL.");
                    }
                }

                var existingEndpoint = RestEndpoints.FirstOrDefault(m => m.Method == callback.Method && m.Url.Equals(callback.Url, StringComparison.OrdinalIgnoreCase));

                if (existingEndpoint != null)
                {
                    RestEndpoints.Remove(existingEndpoint);
                }

                RestEndpoints.Add(callback);
            }
        }
Example #6
0
 private static string CustomBuildPathForComponentCode(abs.IAbstractEndpoint endpoint, IService service, string subPath, bool useNewServiceName)
 {
     var result = string.Format(@"{0}\Components\{1}", endpoint.Project.Name, (useNewServiceName) ? service.InstanceName : service.OriginalInstanceName);
     if (subPath != string.Empty && subPath != null)
     {
         result = string.Format(@"{0}\Infrastructure\{1}\{2}", endpoint.Project.Name, subPath, (useNewServiceName) ? service.InstanceName : service.OriginalInstanceName);
     }
     return result;
 }
 public void RegisterEndpoint(string endpointName, AbstractEndpoint endpoint)
 {
     if (endpoint is AbstractPollingEndpoint)
     {
         //DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint);
         //if (accessor.getPropertyValue("trigger") == null) {
         ((AbstractPollingEndpoint)endpoint).Trigger = new IntervalTrigger(new TimeSpan(0, 0, 0, 0, 10));
         //}
     }
     RegisterObject(endpointName, endpoint, this);
 }
Example #8
0
        public object ExecuteEndpoint(ExecutionContext context, AbstractEndpoint endpoint)
        {
            var executionService = this.executionServices.FirstOrDefault(m => m.Language == endpoint.Language);

            if (executionService == null)
            {
                throw new Exception($"Execution service for {endpoint.Language} not defined.");
            }

            return(executionService.ExecuteEndpoint(context, endpoint));
        }
        private void InitializeEndpoint()
        {
            lock (_initializationMonitor) {
                if (_initialized)
                {
                    return;
                }

                AssertUtils.ArgumentHasText(_inputChannelName, "inputChannelName is required");

                AssertUtils.IsTrue(_objectFactory.ContainsObject(_inputChannelName), "no such input channel '" + _inputChannelName + "' for endpoint '" + _objectName + "'");

                IMessageChannel channel = (IMessageChannel)_objectFactory.GetObject(_inputChannelName, typeof(IMessageChannel));
                if (channel is ISubscribableChannel)
                {
                    if (_pollerMetadata != null)
                    {
                        throw new ArgumentException("A poller should not be specified for endpoint '" + _objectName
                                                    + "', since '" + _inputChannelName + "' is a SubscribableChannel (not pollable).");
                    }
                    _endpoint = new EventDrivenConsumer((ISubscribableChannel)channel, _handler);
                }
                else if (channel is IPollableChannel)
                {
                    PollingConsumer pollingConsumer = new PollingConsumer((IPollableChannel)channel, _handler);
                    if (_pollerMetadata == null)
                    {
                        _pollerMetadata = IntegrationContextUtils.GetDefaultPollerMetadata(_objectFactory);
                        AssertUtils.ArgumentNotNull(_pollerMetadata, "No poller has been defined for endpoint '" + _objectName + "', and no default poller is available within the context.");
                    }
                    pollingConsumer.Trigger               = _pollerMetadata.Trigger;
                    pollingConsumer.MaxMessagesPerPoll    = _pollerMetadata.MaxMessagesPerPoll;
                    pollingConsumer.ReceiveTimeout        = _pollerMetadata.ReceiveTimeout;
                    pollingConsumer.TaskExecutor          = _pollerMetadata.TaskExecutor;
                    pollingConsumer.TransactionManager    = _pollerMetadata.TransactionManager;
                    pollingConsumer.TransactionDefinition = _pollerMetadata.TransactionDefinition;
                    pollingConsumer.AdviceChain           = _pollerMetadata.AdviceChain;
                    _endpoint = pollingConsumer;
                }
                else
                {
                    throw new ArgumentException("unsupported channel type: [" + channel.GetType() + "]");
                }
                _endpoint.AutoStartup   = _autoStartup;
                _endpoint.ObjectName    = _objectName;
                _endpoint.ObjectFactory = _objectFactory;
                _endpoint.AfterPropertiesSet();
                _initialized = true;
            }
        }
        private async Task <IActionResult> RunScript(AbstractEndpoint endpoint, Dictionary <string, object> parameters = null, bool noSerialization = false)
        {
            try {
                var variables = new Dictionary <string, object> {
                    { "Request", Request },
                    { "Response", Response },
                    { "User", HttpContext?.User?.Identity?.Name },
                    { "MemoryCache", _memoryCache },
                    { "UDConnectionManager", _connectionManager }
                };

                try
                {
                    if (HttpContext.Request.Cookies.ContainsKey("location") == true)
                    {
                        var location = HttpContext.Request.Cookies["location"];
                        if (!string.IsNullOrEmpty(location))
                        {
                            location = Encoding.UTF8.GetString(Convert.FromBase64String(location));
                            var locationObject = JsonConvert.DeserializeObject <Location>(location);
                            variables.Add("Location", locationObject);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("RunScript() Exception processing geolocation. " + ex.Message);
                }

                ExecutionContext executionContext = new ExecutionContext(endpoint, variables, parameters, HttpContext?.User);
                executionContext.NoSerialization = noSerialization;

                if (HttpContext.Request.Headers.TryGetValue("UDConnectionId", out StringValues connectionId))
                {
                    executionContext.SessionId    = _connectionManager.GetSessionId(connectionId);
                    executionContext.ConnectionId = connectionId;
                }

                var result = await _executionService.ExecuteEndpointAsync(executionContext, endpoint);

                var actionResult = ConvertToActionResult(result);

                return(actionResult);
            }
            catch (Exception ex) {
                Log.Warn("RunScript() " + ex.Message + Environment.NewLine + ex.StackTrace);
                throw ex;
            }
        }
        public ExecutionContext(AbstractEndpoint endpoint, Dictionary <string, object> variables, Dictionary <string, object> parameters, ClaimsPrincipal user)
        {
            Endpoint   = endpoint;
            Variables  = variables;
            Parameters = parameters;
            User       = user;

            if (Variables == null)
            {
                Variables = new Dictionary <string, object>();
            }

            if (Parameters == null)
            {
                Parameters = new Dictionary <string, object>();
            }
        }
        public object ExecuteEndpoint(ExecutionContext context, AbstractEndpoint endpoint)
        {
            if (endpoint.Language != Common.Models.Language.PowerShell)
            {
                throw new Exception($"Invalid language {endpoint.Language}");
            }

            var psEndpoint = endpoint as Endpoint;

            var scriptBuilder  = new StringBuilder();
            var scriptBlockAst = psEndpoint.ScriptBlock.Ast as ScriptBlockAst;

            string header = string.Empty;

            if (scriptBlockAst.ParamBlock == null && context.Parameters.Any())
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("Parameters--------------");
                    foreach (var variable in context.Parameters)
                    {
                        Log.Debug($"{variable.Key} = {variable.Value}");
                    }
                }

                var paramBlockBuilder = new StringBuilder();

                if (scriptBlockAst.UsingStatements != null)
                {
                    foreach (var usingStatement in scriptBlockAst.UsingStatements)
                    {
                        paramBlockBuilder.AppendLine(usingStatement.ToString());
                    }
                }

                paramBlockBuilder.Append("param(");

                foreach (var parameter in context.Parameters)
                {
                    paramBlockBuilder.Append($"${parameter.Key},");
                }
                paramBlockBuilder.Remove(paramBlockBuilder.Length - 1, 1);
                paramBlockBuilder.Append(")");
                paramBlockBuilder.AppendLine();
                header = paramBlockBuilder.ToString();
            }
            else if (scriptBlockAst.ParamBlock != null)
            {
                header = scriptBlockAst.ParamBlock.ToString();
            }

            scriptBuilder.AppendLine(header);

            if (_dashboardService.Debugger.ShouldBreak(endpoint.Name))
            {
                scriptBuilder.AppendLine("Wait-Debugger");
            }

            foreach (var statement in scriptBlockAst.EndBlock.Statements)
            {
                scriptBuilder.AppendLine(statement.ToString());
            }

            Collection <PSObject> output;
            string json;

            using (var ps = PowerShell.Create())
            {
                using (var runspaceRef = _runspace.GetRunspace())
                {
                    runspaceRef.Runspace.ResetRunspaceState();
                    Runspace.DefaultRunspace  = runspaceRef.Runspace;
                    runspaceRef.Runspace.Name = endpoint.Name;
                    ps.Runspace = runspaceRef.Runspace;

                    var host = (UDHost)_host.GetValue(ps.Runspace);
                    var ui   = (UDHostUserInterface)host.UI;

                    if (endpoint.Variables != null)
                    {
                        Log.Debug("Scope variables--------------");
                        SetVariables(ps.Runspace, endpoint.Variables);
                    }

                    if (context.Variables != null)
                    {
                        Log.Debug("Context variables--------------");
                        SetVariables(ps.Runspace, context.Variables);
                    }

                    SetVariable(ps, "DashboardHub", _hubContext);
                    SetVariable(ps, "Cache", _memoryCache);
                    SetVariable(ps, "StateRequestService", _stateRequestService);
                    SetVariable(ps, "ConnectionId", context.ConnectionId);
                    SetVariable(ps, Constants.SessionId, context.SessionId);
                    SetVariable(ps, "ArgumentList", context.Endpoint.ArgumentList?.ToList());
                    SetVariable(ps, Constants.UDPage, context.Endpoint.Page);

                    ui.HubContext   = _hubContext;
                    ui.ConnectionId = context.ConnectionId;

                    if (context.User != null)
                    {
                        SetVariable(ps, "ClaimsPrinciple", context.User);
                        SetVariable(ps, "ClaimsPrincipal", context.User);
                    }

                    ps.AddStatement().AddScript(scriptBuilder.ToString());

                    foreach (var parameter in context.Parameters)
                    {
                        ps.AddParameter(parameter.Key, parameter.Value);
                    }

                    try
                    {
                        output = ps.Invoke();

                        if (!context.IgnoreNonTerminatingErrors)
                        {
                            if (ps.HadErrors)
                            {
                                if (ps.Streams.Error.Any())
                                {
                                    var error = ps.Streams.Error[0].Exception.Message;

                                    foreach (var errorRecord in ps.Streams.Error)
                                    {
                                        Log.Warn($"Error executing endpoint {endpoint.Name}. {errorRecord} {Environment.NewLine} {errorRecord.ScriptStackTrace}");
                                    }

                                    return(new { Error = new Error {
                                                     Message = error
                                                 } });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex, $"Error executing endpoint {endpoint.Name}.");

                        return(new { Error = new Error {
                                         Message = ex.Message, Location = ex.StackTrace
                                     } });
                    }
                }
            }

            if (context.NoSerialization)
            {
                return(output.Select(m => m.BaseObject).ToArray());
            }

            json = output.FirstOrDefault()?.BaseObject as string;
            if (json != null)
            {
                return(json);
            }

            return(output.Where(m => m != null).Select(m => m.BaseObject).ToList());
        }
Example #13
0
 public Logger(AbstractEndpoint endpoint)
 {
     this.endpoint     = endpoint;
     this.loggingLevel = LogLevel.INFO;
 }
Example #14
0
 private static string CustomBuildNamespaceForComponentCode(abs.IAbstractEndpoint endpoint, IService service)
 {
     return endpoint == null ? string.Empty : string.Format(@"{0}.Components.{1}", endpoint.Project.Data.RootNamespace, service.CodeIdentifier);
 }
        public async Task SetEndpointSchedule(AbstractEndpoint endpoint)
        {
            var        dataMap = new JobDataMap();
            IJobDetail job;

            dataMap.Add(nameof(ScheduledEndpointJob.Endpoint), endpoint);
            dataMap.Add(nameof(ScheduledEndpointJob.ExecutionService), _executionService);
            dataMap.Add(nameof(ScheduledEndpointJob.MemoryCache), _memoryCache);

            if (endpoint.Schedule.Consecutive)
            {
                job = JobBuilder.Create <ScheduledEndpointJobConsecutive>()
                      .WithIdentity(endpoint.Name)
                      .UsingJobData(dataMap)
                      .Build();
            }
            else
            {
                job = JobBuilder.Create <ScheduledEndpointJob>()
                      .WithIdentity(endpoint.Name)
                      .UsingJobData(dataMap)
                      .Build();
            }

            ITrigger trigger = null;

            if (endpoint.Schedule.Cron != null)
            {
                if (endpoint.Schedule.Consecutive)
                {
                    trigger = TriggerBuilder.Create()
                              .WithIdentity(endpoint.Name)
                              .StartNow()
                              .WithSchedule(CronScheduleBuilder.CronSchedule(endpoint.Schedule.Cron)
                                            .WithMisfireHandlingInstructionIgnoreMisfires())
                              .Build();
                }
                else
                {
                    trigger = TriggerBuilder.Create()
                              .WithIdentity(endpoint.Name)
                              .StartNow()
                              .WithSchedule(CronScheduleBuilder.CronSchedule(endpoint.Schedule.Cron))
                              .Build();
                }
            }
            else
            {
                if (endpoint.Schedule.Repeat > 0)
                {
                    if (job.ConcurrentExecutionDisallowed)
                    {
                        trigger = TriggerBuilder.Create()
                                  .WithIdentity(endpoint.Name)
                                  .StartNow()
                                  .WithSimpleSchedule(x => x
                                                      .WithIntervalInSeconds((int)endpoint.Schedule.Every.TotalSeconds)
                                                      .WithRepeatCount(endpoint.Schedule.Repeat)
                                                      .WithMisfireHandlingInstructionIgnoreMisfires())
                                  .Build();
                    }
                    else
                    {
                        trigger = TriggerBuilder.Create()
                                  .WithIdentity(endpoint.Name)
                                  .StartNow()
                                  .WithSimpleSchedule(x => x
                                                      .WithIntervalInSeconds((int)endpoint.Schedule.Every.TotalSeconds)
                                                      .WithRepeatCount(endpoint.Schedule.Repeat))
                                  .Build();
                    }
                }
                else
                {
                    if (job.ConcurrentExecutionDisallowed)
                    {
                        trigger = TriggerBuilder.Create()
                                  .WithIdentity(endpoint.Name)
                                  .StartNow()
                                  .WithSimpleSchedule(x => x
                                                      .WithIntervalInSeconds((int)endpoint.Schedule.Every.TotalSeconds)
                                                      .RepeatForever()
                                                      .WithMisfireHandlingInstructionIgnoreMisfires())
                                  .Build();
                    }
                    else
                    {
                        trigger = TriggerBuilder.Create()
                                  .WithIdentity(endpoint.Name)
                                  .StartNow()
                                  .WithSimpleSchedule(x => x
                                                      .WithIntervalInSeconds((int)endpoint.Schedule.Every.TotalSeconds)
                                                      .RepeatForever())
                                  .Build();
                    }
                }
            }
            await _scheduler.ScheduleJob(job, trigger);
        }