Esempio n. 1
0
        public object ConvertToEngineNativeObject(object obj)
        {
            var result = obj;

            var lastScriptExecutionResponse = GetLastScriptExecutionResponse();

            if (lastScriptExecutionResponse?.State != ScriptState.Running.ToString())
            {
                try {
                    if (obj is Newtonsoft.Json.Linq.JArray ||
                        obj is Newtonsoft.Json.Linq.JObject)
                    {
                        var jsonString = obj.ToString();
                        result = _engine.JsonObjectToNativeEngineObject(jsonString);
                    }
                } catch (Exception e) {
                    throw new RunspaceEndpointException(e.Message, e);
                }
            }
            else
            {
                throw new RunspaceEndpointException(
                          500,
                          ApiErrorCodes.GetErrorCode(nameof(RunspaceEndpointResources.AnotherScriptIsRunning)),
                          string.Format(RunspaceEndpointResources.AnotherScriptIsRunning, _lastScriptId));
            }

            return(result);
        }
Esempio n. 2
0
        public ActionResult <WebConsole> Post()
        {
            ActionResult <WebConsole> result = null;

            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                if (RunspaceProviderSingleton.Instance.RunspaceProvider.CanCreateNewWebConsole())
                {
                    var webConsoleData = RunspaceProviderSingleton.Instance.RunspaceProvider.CreateWebConsole(
                        authzToken.UserName,
                        authzToken,
                        new SolutionStsClient(_loggerFactory, _stsSettings),
                        // Assumes VC Address is same as STS Address
                        new Uri(_stsSettings.StsServiceEndpoint).Host);

                    result = StatusCode(200, new WebConsole(webConsoleData));
                }
                else
                {
                    _logger.LogInformation($"Runspace provider can't create new web console: {APIGatewayResources.RunspaceController_Post_MaxnumberOfRunspacesReached}");
                    result = StatusCode(
                        500,
                        new ErrorDetails(
                            ApiErrorCodes.GetErrorCode(nameof(APIGatewayResources.WebConsoleController_Post_MaxNumberOfWebConsolesReached)),
                            APIGatewayResources.WebConsoleController_Post_MaxNumberOfWebConsolesReached));
                }
            } catch (Exception exc) {
                result = StatusCode(500, new ErrorDetails(exc));
            }

            return(result);
        }
Esempio n. 3
0
        public ScriptExecutionResponse StartScriptExecution(
            string content,
            IScriptParameter[] parameters = null,
            Runspace.Types.OutputObjectsFormat outputObjectsFormat = Runspace.Types.OutputObjectsFormat.Text,
            string name = null)
        {
            var lastScriptExecutionResponse = GetLastScriptExecutionResponse();

            if (lastScriptExecutionResponse?.State != ScriptState.Running.ToString())
            {
                try {
                    _cancelationToken = new CancellationTokenSource();
                    _lastScriptId     = Guid.NewGuid().ToString();
                    _lastScriptName   = name;

                    _engine.ExecuteScriptAsync(
                        content,
                        parameters,
                        outputObjectsFormat,
                        _cancelationToken.Token);

                    lastScriptExecutionResponse = GetLastScriptExecutionResponse();
                } catch (Exception e) {
                    throw new RunspaceEndpointException(e.Message, e);
                }
            }
            else
            {
                throw new RunspaceEndpointException(
                          500,
                          ApiErrorCodes.GetErrorCode(nameof(RunspaceEndpointResources.AnotherScriptIsRunning)),
                          string.Format(RunspaceEndpointResources.AnotherScriptIsRunning, _lastScriptId));
            }
            return(lastScriptExecutionResponse);
        }
Esempio n. 4
0
        public ActionResult <ArgumentScriptTemplate> Get([FromRoute] string id)
        {
            var result = PCLIScriptsReader.GetArgumentTransformationScript(id);

            return(result == null
            ? NotFound(
                       new ErrorDetails(
                           ApiErrorCodes.GetErrorCode(nameof(APIGatewayResources.ArgumentScriptsController_ArgumentTransformationScriptNotFound)),
                           string.Format(APIGatewayResources.ArgumentScriptsController_ArgumentTransformationScriptNotFound, id)))
            : (ActionResult <ArgumentScriptTemplate>)Ok(result));
        }
Esempio n. 5
0
 public void CancelScriptExecution(string id)
 {
     if (_lastScriptId == id)
     {
         _cancelationToken.Cancel();
     }
     else
     {
         throw new RunspaceEndpointException(
                   404,
                   ApiErrorCodes.GetErrorCode(nameof(RunspaceEndpointResources.ScriptNotScheduled)),
                   string.Format(RunspaceEndpointResources.ScriptNotScheduled, id));
     }
 }
Esempio n. 6
0
 public ScriptExecutionResponse GetLastScriptStatus()
 {
     if (!string.IsNullOrEmpty(_lastScriptId))
     {
         return(GetLastScriptExecutionResponse());
     }
     else
     {
         throw new RunspaceEndpointException(
                   404,
                   ApiErrorCodes.GetErrorCode(nameof(RunspaceEndpointResources.ScriptNotScheduled)),
                   string.Format(RunspaceEndpointResources.ScriptNotScheduled, string.Empty));
     }
 }
        public ActionResult Cancel([FromRoute] string id)
        {
            ActionResult result;

            // Get Script Execution from ScriptExecutionMediator
            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                var scriptResult = ScriptExecutionMediatorSingleton.
                                   Instance.
                                   ScriptExecutionMediator.
                                   GetScriptExecution(authzToken.UserName, id);

                if (scriptResult != null)
                {
                    // Cancel Script Execution
                    ScriptExecutionMediatorSingleton.
                    Instance.
                    ScriptExecutionMediator.
                    CancelScriptExecution(authzToken.UserName, id);

                    result = Ok();
                }
                else
                {
                    result = NotFound(
                        new ErrorDetails(
                            ApiErrorCodes.GetErrorCode(
                                APIGatewayResources.ScriptsController_ScriptNotFound),
                            string.Format(APIGatewayResources.ScriptsController_ScriptNotFound, id)));
                }
            } catch (RunspaceEndpointException runspaceEndointException) {
                result = StatusCode(
                    runspaceEndointException.HttpErrorCode,
                    new ErrorDetails(
                        ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode),
                        runspaceEndointException.Message,
                        runspaceEndointException.ToString()));
            } catch (Exception exc) {
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.ScriptsController_RunspaceFailedToCancelScriptExecution)),
                        APIGatewayResources.ScriptsController_RunspaceFailedToCancelScriptExecution,
                        exc.ToString()));
            }

            return(result);
        }
Esempio n. 8
0
        public ActionResult <ArgumentScript> Create([FromBody] ArgumentScript argumentScript)
        {
            var template = PCLIScriptsReader.GetArgumentTransformationScript(argumentScript.TemplateId);

            if (template == null)
            {
                return(NotFound(
                           new ErrorDetails(
                               ApiErrorCodes.GetErrorCode(nameof(APIGatewayResources.ArgumentScriptsController_ArgumentTransformationScriptNotFound)),
                               string.Format(APIGatewayResources.ArgumentScriptsController_ArgumentTransformationScriptNotFound, argumentScript.TemplateId))));
            }

            return(Ok(
                       new PCLIScriptsGenerator(
                           template.ScriptTemplate,
                           argumentScript.PlaceholderValueList).Generate()));
        }
        // Out of scope for MVP release
        // It is allowed to retrieve partial representation of the **script execution** resources giving desired fields on the **fields** query parameter.
        // Partial objects allow lowering traffic from server to client. You'll probably not need to get script content and parameters when list all script executions.
        // When fields are requested in the query parameter other fields will remain null.
        // <param name="fields"></param>
        //public ActionResult<DataTypes.ScriptExecution[]> List([FromQuery]string[] fields) {
        public ActionResult <DataTypes.ScriptExecution[]> List()
        {
            ActionResult <DataTypes.ScriptExecution[]> result = null;

            // Get Script Execution from ScriptExecutionMediator
            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                var scriptExecutionResults = ScriptExecutionMediatorSingleton.
                                             Instance.
                                             ScriptExecutionMediator.
                                             ListScriptExecutions(authzToken.UserName);

                if (scriptExecutionResults != null)
                {
                    var resultList = new List <DataTypes.ScriptExecution>();

                    foreach (var scriptExecutionResult in scriptExecutionResults)
                    {
                        resultList.Add(new DataTypes.ScriptExecution(scriptExecutionResult));
                    }
                    result = resultList.ToArray();
                }
                else
                {
                    result = Ok(new DataTypes.ScriptExecution[] {});
                }
            } catch (RunspaceEndpointException runspaceEndointException) {
                result = StatusCode(
                    runspaceEndointException.HttpErrorCode,
                    new ErrorDetails(
                        ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode),
                        runspaceEndointException.Message,
                        runspaceEndointException.ToString()));
            } catch (Exception exc) {
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.ScriptsController_ScriptStorageService_FailedToRetrieveScripts)),
                        APIGatewayResources.ScriptsController_ScriptStorageService_FailedToRetrieveScripts,
                        exc.ToString()));
            }
            return(result);
        }
Esempio n. 10
0
        // Out of scope for MVP release
        // Since the number of output object could be large the retrieval operation supports pagination.
        // There are two query parameters limit and start which can be used to move through the output objects list.
        // Start 0 means the last retrieved output object.
        // <param name="limit">Maximum number of records to be retrieved</param>
        // <param name="start">Position in the history of output records where the retrieval is requested from</param>
        //public ActionResult<string[]> Get([FromRoute] string id, [FromQuery] int limit = 20, [FromQuery] int start = 0) {
        public ActionResult <string[]> Get([FromRoute] string id)
        {
            ActionResult <string[]>       result       = null;
            IScriptExecutionOutputObjects scriptOutput = null;

            // Get Script Execution from ScriptExecutionMediator
            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                scriptOutput = ScriptExecutionMediatorSingleton.
                               Instance.
                               ScriptExecutionMediator.
                               GetScriptExecutionOutput(authzToken.UserName, id);

                if (scriptOutput != null)
                {
                    result = Ok(scriptOutput.OutputObjects);
                }
                else
                {
                    result = NotFound(
                        new ErrorDetails(
                            ApiErrorCodes.GetErrorCode(
                                nameof(APIGatewayResources.ScriptsController_ScriptNotFound)),
                            string.Format(APIGatewayResources.ScriptsController_ScriptNotFound, id)));
                }
            } catch (RunspaceEndpointException runspaceEndointException) {
                result = StatusCode(
                    runspaceEndointException.HttpErrorCode,
                    new ErrorDetails(
                        ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode),
                        runspaceEndointException.Message,
                        runspaceEndointException.ToString()));
            } catch (Exception exc) {
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.ScriptOutputController_ScriptStorageService_FailedToRetrieveScriptOutput)),
                        APIGatewayResources.ScriptOutputController_ScriptStorageService_FailedToRetrieveScriptOutput,
                        exc.ToString()));
            }
            return(result);
        }
Esempio n. 11
0
        public void Logout()
        {
            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                // Unregister session from active sessions
                Sessions.Instance.UnregisterSession(authzToken);

                Ok();
            } catch (Exception e) {
                StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.SessionsController_SessionsService_FailedToDeleteSession)),
                        APIGatewayResources.SessionsController_SessionsService_FailedToDeleteSession,
                        e.ToString()));
            }
        }
Esempio n. 12
0
        public ActionResult Delete([FromRoute] string id)
        {
            ActionResult result;

            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);
                RunspaceProviderSingleton.Instance.RunspaceProvider.KillWebConsole(authzToken.UserName, id);
                result = Ok();
            } catch (Exception exc) {
                _logger.LogError(exc, "Delete runspace operation failed.");
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.WebConsoleController_Kill_RunspaceProviderKillWebConsoleFailed)),
                        string.Format(
                            APIGatewayResources.WebConsoleController_Kill_RunspaceProviderKillWebConsoleFailed,
                            id),
                        exc.ToString()));
            }

            return(result);
        }
Esempio n. 13
0
        public ActionResult <WebConsole> Get([FromRoute] string id)
        {
            ActionResult <WebConsole> result = null;

            try {
                var authzToken     = SessionToken.FromHeaders(Request.Headers);
                var webConsoleData =
                    RunspaceProviderSingleton.
                    Instance.
                    RunspaceProvider.
                    GetWebConsole(authzToken.UserName, id);
                result = Ok(new WebConsole(webConsoleData));
            } catch (Exception e) {
                _logger.LogError(e, "Get web console operation failed.");
                result = NotFound(
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(nameof(APIGatewayResources.WebConsoleNotFound)),
                        string.Format(
                            APIGatewayResources.WebConsoleNotFound,
                            id)));
            }
            return(result);
        }
Esempio n. 14
0
        public ActionResult <WebConsole[]> List()
        {
            ActionResult <WebConsole[]> result = null;

            try {
                var authzToken         = SessionToken.FromHeaders(Request.Headers);
                var webConsoleDataList =
                    RunspaceProviderSingleton.
                    Instance.
                    RunspaceProvider.
                    ListWebConsole(authzToken.UserName);
                if (webConsoleDataList != null)
                {
                    List <WebConsole> webConsoleResponseList = new List <WebConsole>();
                    foreach (var webConsoleData in webConsoleDataList)
                    {
                        webConsoleResponseList.Add(new WebConsole(webConsoleData));
                    }

                    result = Ok(webConsoleResponseList.ToArray());
                }
                else
                {
                    result = Ok(new DataTypes.Runspace[] { });
                }
            } catch (Exception e) {
                _logger.LogError(e, "List web consoles operation failed.");
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.WebConsoleController_List_RunspaceProviderListWebConsoleFailed)),
                        APIGatewayResources.WebConsoleController_List_RunspaceProviderListWebConsoleFailed,
                        e.ToString()));
            }
            return(result);
        }
Esempio n. 15
0
        // Out of scope for MVP release
        // Since the stream messages number could be large depending on the script the operation uses pagination.
        // There are two query parameters limit and start which can be used to move through the stream records list. Record at index 0 is the last registered stream records. Moving up increasing the start of the stream records moves you back in the history of stream records.
        // <param name="limit">Maximum number of records to be retrieved</param>
        // <param name="start">Position in the history of records where the records retrieval is requested from.</param>
        // public ActionResult<StreamRecord[]> Get([FromRoute] string id, [FromRoute(Name ="stream-type")] StreamType streamType, [FromQuery] int limit = 20, [FromQuery] int start = 0) {
        public ActionResult <StreamRecord[]> Get([FromRoute] string id, [FromRoute(Name = "stream-type")] StreamType streamType)
        {
            ActionResult <StreamRecord[]> result       = null;
            IScriptExecutionDataStreams   scriptResult = null;

            // Get Script Execution from ScriptExecutionMediator
            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                scriptResult = ScriptExecutionMediatorSingleton.
                               Instance.
                               ScriptExecutionMediator.
                               GetScriptExecutionDataStreams(authzToken.UserName, id);

                if (scriptResult != null)
                {
                    switch (streamType)
                    {
                    case StreamType.debug:
                        result = Ok(
                            StreamRecord.FromStreamRecords(scriptResult.Streams.Debug));
                        break;

                    case StreamType.error:
                        result = Ok(
                            StreamRecord.FromStreamRecords(scriptResult.Streams.Error));
                        break;

                    case StreamType.information:
                        result = Ok(
                            StreamRecord.FromStreamRecords(scriptResult.Streams.Information));
                        break;

                    case StreamType.verbose:
                        result = Ok(
                            StreamRecord.FromStreamRecords(scriptResult.Streams.Verbose));
                        break;

                    case StreamType.warning:
                        result = Ok(
                            StreamRecord.FromStreamRecords(scriptResult.Streams.Warning));
                        break;
                    }
                }
                else
                {
                    result = NotFound(
                        new ErrorDetails(
                            ApiErrorCodes.GetErrorCode(
                                nameof(APIGatewayResources.ScriptsController_ScriptNotFound)),
                            string.Format(APIGatewayResources.ScriptsController_ScriptNotFound, id)));
                }
            } catch (RunspaceEndpointException runspaceEndointException) {
                result = StatusCode(
                    runspaceEndointException.HttpErrorCode,
                    new ErrorDetails(
                        ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode),
                        runspaceEndointException.Message,
                        runspaceEndointException.ToString()));
            } catch (Exception exc) {
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.ScriptStreamsController_ScriptStorageService_FailedToRetrieveScriptStreams)),
                        APIGatewayResources.ScriptStreamsController_ScriptStorageService_FailedToRetrieveScriptStreams,
                        exc.ToString()));
            }
            return(result);
        }
        public async Task <ActionResult <DataTypes.ScriptExecution> > Post([FromBody] DataTypes.ScriptExecution script_execution)
        {
            ActionResult <DataTypes.ScriptExecution> result = null;

            // Get Runspace Endpoint or throw Runspace Not Found
            IRunspaceData runspaceInfo = null;

            try {
                var authzToken = SessionToken.FromHeaders(Request.Headers);

                runspaceInfo =
                    RunspaceProviderSingleton.
                    Instance.
                    RunspaceProvider.
                    Get(authzToken.UserName, script_execution.RunspaceId);
            } catch (Exception) {
            }

            if (runspaceInfo == null)
            {
                result = NotFound(
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.RunspaceNotFound)),
                        string.Format(
                            APIGatewayResources.RunspaceNotFound, script_execution.RunspaceId)));
            }
            else if (runspaceInfo.State != RunspaceState.Ready)
            {
                result = StatusCode(
                    500,
                    new ErrorDetails(
                        ApiErrorCodes.GetErrorCode(
                            nameof(APIGatewayResources.RunspaceNotReady)),
                        string.Format(
                            APIGatewayResources.RunspaceNotReady,
                            script_execution.RunspaceId,
                            runspaceInfo.State)));
            }
            else
            {
                // Add Script Execution in the ScriptExecutionMediator
                try {
                    var authzToken = SessionToken.FromHeaders(Request.Headers);

                    var scriptResult =
                        await ScriptExecutionMediatorSingleton.Instance.ScriptExecutionMediator.StartScriptExecution(
                            authzToken.UserName,
                            runspaceInfo,
                            script_execution);

                    result = StatusCode(
                        202,
                        new DataTypes.ScriptExecution(scriptResult));
                } catch (RunspaceEndpointException runspaceEndointException) {
                    result = StatusCode(
                        runspaceEndointException.HttpErrorCode,
                        new ErrorDetails(
                            ApiErrorCodes.CalculateScriptsErrorCode(runspaceEndointException.ErrorCode),
                            runspaceEndointException.Message,
                            runspaceEndointException.ToString()));
                } catch (Exception exc) {
                    result = StatusCode(
                        500,
                        new ErrorDetails(
                            ApiErrorCodes.GetErrorCode(
                                nameof(APIGatewayResources.ScriptsController_RunspaceFailedToProcessScriptRequest)),
                            APIGatewayResources.ScriptsController_RunspaceFailedToProcessScriptRequest,
                            exc.ToString()));
                }
            }


            return(result);
        }