Пример #1
0
        /// <summary>
        /// Deploy to a resource group
        /// </summary>
        /// <remarks>Default to "Complete" deployment</remarks>
        /// <param name="requestId"></param>
        /// <param name="correlationId"></param>
        /// <param name="subscriptionId">ISV Azure subscription id</param>
        /// <param name="resourceGroup">ISV Azure resource group</param>
        /// <param name="deploymentName">Deployment name</param>
        /// <param name="templatePath">Link to template file</param>
        /// <param name="parametersPath">Link to parameter file</param>
        /// <param name="rollbackToLastSuccessful">If true, the rolllback property will be set in the request body</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <DeploymentExtendedResult> PutDeploymentAsync(
            Guid requestId,
            Guid correlationId,
            string subscriptionId,
            string resourceGroup,
            string deploymentName,
            string templatePath                 = default,
            object template                     = default,
            string parametersPath               = default,
            object parameters                   = default,
            bool rollbackToLastSuccessful       = default,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if ((templatePath == null) == (template == null))
                {
                    throw new LunaBadRequestUserException(LoggingUtils.ComposeBadXorArgumentMessage("templatePath", "template"), UserErrorCode.InvalidParameter);
                }
                if ((parametersPath == null) == (parameters == null))
                {
                    throw new LunaBadRequestUserException(LoggingUtils.ComposeBadXorArgumentMessage("parametersPath", "parameters"), UserErrorCode.InvalidParameter);
                }

                var requestUrl = GetRequestUri(subscriptionId, resourceGroup, deploymentName);

                var body = rollbackToLastSuccessful ?
                           new DeploymentRequestBody
                {
                    Properties = new DeploymentProperties
                    {
                        Mode         = nameof(DeploymentMode.Complete),
                        TemplateLink = new TemplateLink {
                            Uri = templatePath
                        },
                        Template          = template,
                        Parameters        = parameters,
                        OnErrorDeployment = new OnErrorDeployment {
                            Type = nameof(DeploymentRollback.LastSuccessful)
                        }
                    }
                } :
                new DeploymentRequestBody
                {
                    Properties = new DeploymentProperties
                    {
                        Mode         = nameof(DeploymentMode.Complete),
                        TemplateLink = new TemplateLink {
                            Uri = templatePath
                        },
                        Template   = template,
                        Parameters = parameters
                    }
                }
                ;

                var requestBody = JsonConvert.SerializeObject(body);
                var bearerToken = await _keyVaultHelper.GetBearerToken(
                    _options.AzureActiveDirectory,
                    _options.ClientService.AuthenticationResourceId);

                var response = await SendRequestAndReturnResult(
                    HttpMethod.Put,
                    requestUrl,
                    requestId,
                    correlationId,
                    bearerToken,
                    null,
                    requestBody,
                    cancellationToken
                    );

                return(await DeploymentRequestResult.ParseAsync <DeploymentExtendedResult>(response));
            }
            catch (LunaServerException e)
            {
                throw new LunaProvisioningException("Cannot deploy template.", e.IsRetryable, ProvisioningState.ArmTemplatePending, e);
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int GetName(enum_GETNAME_TYPE type, out string name)
        {
            //
            // Gets the displayable name of the document that contains this document context.
            //

            LoggingUtils.PrintFunction();

            name = string.Empty;

            try
            {
                switch (type)
                {
                case enum_GETNAME_TYPE.GN_NAME:
                {
                    //
                    // Specifies a friendly name of the document or context.
                    //

                    name = Path.GetFileNameWithoutExtension(m_fileName);

                    break;
                }

                case enum_GETNAME_TYPE.GN_FILENAME:
                {
                    //
                    // Specifies the full path of the document or context.
                    //

                    name = m_fileName;

                    break;
                }

                case enum_GETNAME_TYPE.GN_BASENAME:
                {
                    //
                    // Specifies a base file name instead of a full path of the document or context.
                    //

                    name = Path.GetFileName(m_fileName);

                    break;
                }

                case enum_GETNAME_TYPE.GN_MONIKERNAME:
                {
                    //
                    // Specifies a unique name of the document or context in the form of a moniker.
                    //

                    name = m_fileName;

                    break;
                }

                case enum_GETNAME_TYPE.GN_URL:
                {
                    //
                    // Specifies a URL name of the document or context.
                    //

                    name = "file://" + m_fileName.Replace("\\", "/");

                    break;
                }

                case enum_GETNAME_TYPE.GN_TITLE:
                {
                    //
                    // Specifies a title of the document, if one exists.
                    //

                    name = Path.GetFileName(m_fileName);

                    break;
                }

                case enum_GETNAME_TYPE.GN_STARTPAGEURL:
                {
                    //
                    // Gets the starting page URL for processes.
                    //

                    name = "file://" + m_fileName.Replace("\\", "/");

                    break;
                }
                }

                if (string.IsNullOrEmpty(name))
                {
                    throw new InvalidOperationException();
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #3
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int GetThreadProperties100(uint requestedFields, THREADPROPERTIES100 [] propertiesArray)
        {
            //
            // Gets properties that describe a thread.
            //

            LoggingUtils.PrintFunction();

            try
            {
                //
                // 9.0 (2008) thread properties.
                //

                THREADPROPERTIES [] threadProperties9 = new THREADPROPERTIES [1];

                enum_THREADPROPERTY_FIELDS requestedFields90 = (enum_THREADPROPERTY_FIELDS)0x3f;// (requestedFields & 0x3f);

                LoggingUtils.RequireOk(GetThreadProperties(requestedFields90, threadProperties9));

                propertiesArray [0].bstrLocation = threadProperties9 [0].bstrLocation;

                propertiesArray [0].bstrName = threadProperties9 [0].bstrName;

                propertiesArray [0].bstrPriority = threadProperties9 [0].bstrPriority;

                propertiesArray [0].dwSuspendCount = threadProperties9 [0].dwSuspendCount;

                propertiesArray [0].dwThreadId = threadProperties9 [0].dwThreadId;

                propertiesArray [0].dwThreadState = threadProperties9 [0].dwThreadState;

                propertiesArray [0].dwFields |= (uint)threadProperties9 [0].dwFields;

                //
                // 10.0 (2010) thread properties.
                //

                if ((requestedFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME) != 0)
                {
                    propertiesArray [0].bstrDisplayName = m_threadDisplayName;

                    propertiesArray [0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME;

                    propertiesArray [0].DisplayNamePriority = (uint)enum_DISPLAY_NAME_PRIORITY100.DISPLAY_NAM_PRI_DEFAULT_100;

                    propertiesArray [0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME_PRIORITY;
                }

                if ((requestedFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY) != 0)
                {
                    if (m_threadId == 1)
                    {
                        propertiesArray [0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Main;
                    }
                    else
                    {
                        propertiesArray [0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Worker;
                    }

                    propertiesArray [0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY;
                }

                if ((requestedFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY) != 0)
                {
                    propertiesArray [0].AffinityMask = 0;

                    propertiesArray [0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY;
                }

                if ((requestedFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID) != 0)
                {
                    propertiesArray [0].priorityId = 0;

                    propertiesArray [0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID;
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int CanDetach()
        {
            LoggingUtils.PrintFunction();

            return(Constants.S_OK);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step)
        {
            //
            // Performs a step.
            //

            LoggingUtils.PrintFunction();

            try
            {
                JavaLangDebuggeeThread thread = pThread as JavaLangDebuggeeThread;

                uint threadId;

                LoggingUtils.RequireOk(thread.GetThreadId(out threadId));

                JdbClient.StepType stepType = (JdbClient.StepType)Step;

                switch (sk)
                {
                case enum_STEPKIND.STEP_INTO:
                {
                    m_debugger.JdbClient.StepInto(threadId, stepType, false);

                    break;
                }

                case enum_STEPKIND.STEP_OVER:
                {
                    m_debugger.JdbClient.StepOver(threadId, stepType, false);

                    break;
                }

                case enum_STEPKIND.STEP_OUT:
                {
                    m_debugger.JdbClient.StepOut(threadId, stepType, false);

                    break;
                }

                case enum_STEPKIND.STEP_BACKWARDS:
                {
                    throw new NotImplementedException();
                }
                }

                return(Constants.S_OK);
            }
            catch (NotImplementedException e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_NOTIMPL);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #6
0
        public async Task <Subscription> DeployArmTemplateAsync(Guid subscriptionId)
        {
            Subscription subscription = await _context.Subscriptions.FindAsync(subscriptionId);

            ValidateSubscriptionAndInputState(subscription);

            try
            {
                if (subscription.ResourceGroup == null)
                {
                    // If resource group is not created, transit to ProvisioningPending state to create resource group
                    return(await TransitToNextState(subscription, ProvisioningState.ProvisioningPending));
                }

                Offer offer = await FindOfferById(subscription.OfferId);

                Plan plan = await FindPlanById(subscription.PlanId);

                string deploymentName    = $"{plan.PlanName}{offer.OfferName}{new Random().Next(0, 9999).ToString("D4")}"; // deployment name cannot exceed 64 characters, otherwise returns 400
                string isvSubscriptionId = offer.HostSubscription.ToString();

                string templatePath = await GetTemplatePath(plan, subscription.ProvisioningType);

                if (templatePath == null)
                {
                    // If template is not specified, do nothing and transit to WebhookPending state
                    return(await TransitToNextState(subscription, ProvisioningState.WebhookPending));
                }

                // Reevaluate parameters if not subscribe. If it is subscribe, the parameters are evaluated when creating resource group
                if (!subscription.ProvisioningType.Equals(nameof(ProvisioningType.Subscribe)))
                {
                    await EvaluateParameters(offer, plan, subscription);
                }

                templatePath = await _storageUtility.GetFileReferenceWithSasKeyAsync(templatePath);

                JObject parameters = new JObject();
                using (WebClient client = new WebClient())
                {
                    string  content = client.DownloadString(templatePath);
                    Context context = await SetContext(offer.OfferName, subscription.Owner, subscriptionId, plan.PlanName, subscription.ProvisioningType);

                    var paramList = ARMTemplateHelper.GetArmTemplateParameters(content);
                    foreach (var param in paramList)
                    {
                        JProperty value = new JProperty("value", context.Parameters[param.Key]);
                        parameters.Add(param.Key, new JObject(value));
                    }
                }

                _logger.LogInformation(
                    LoggingUtils.ComposeHttpClientLogMessage(
                        _provisioningClient.GetType().Name,
                        nameof(_provisioningClient.PutDeploymentAsync),
                        subscriptionId));

                var result = await _provisioningClient.PutDeploymentAsync(
                    Guid.NewGuid(),
                    Guid.NewGuid(),
                    isvSubscriptionId,
                    subscription.ResourceGroup,
                    deploymentName,
                    parameters : parameters,
                    templatePath : templatePath);

                subscription.DeploymentName = result.Name;

                _logger.LogInformation($"Running ARM deployment {deploymentName} for subscription {isvSubscriptionId} in resource group {subscription.ResourceGroup}.");

                return(await TransitToNextState(subscription, ProvisioningState.ArmTemplateRunning));
            }
            catch (Exception e)
            {
                return(await HandleExceptions(subscription, e));
            }
        }
Пример #7
0
        public async Task <Subscription> UpdateOperationCompletedAsync(Guid subscriptionId, string activatedBy = "system")
        {
            Subscription subscription = await _context.Subscriptions.FindAsync(subscriptionId);

            ValidateSubscriptionAndInputState(subscription);

            try
            {
                Offer offer = await FindOfferById(subscription.OfferId);

                if (subscription.ProvisioningType.Equals(nameof(ProvisioningType.Unsubscribe)))
                {
                    var sub = await _fulfillmentClient.GetSubscriptionAsync(subscriptionId, Guid.NewGuid(), Guid.NewGuid());

                    subscription.TermEndTime = sub.Term.EndDate;
                }

                if (subscription.ProvisioningStatus.Equals(ProvisioningState.NotificationPending.ToString(), StringComparison.InvariantCultureIgnoreCase) &&
                    offer.ManualCompleteOperation)
                {
                    _logger.LogInformation($"ManualCompleteOperation of offer {offer.OfferName} is set to true. Will not complete the operation automatically.");

                    return(await TransitToNextState(subscription, ProvisioningState.ManualCompleteOperationPending));
                }

                // Don't need to update marketplace operation for delete data
                // 02-15-2021: Marketplace behavior change: Don't need to update marketplace operation for unsubscribe
                if (!subscription.ProvisioningType.Equals(nameof(ProvisioningType.DeleteData)) &&
                    !subscription.ProvisioningType.Equals(nameof(ProvisioningType.Unsubscribe)))
                {
                    Plan plan = await FindPlanById(subscription.PlanId);

                    OperationUpdate update = new OperationUpdate
                    {
                        PlanId   = plan.PlanName,
                        Quantity = subscription.Quantity,
                        Status   = OperationUpdateStatusEnum.Success
                    };

                    _logger.LogInformation(
                        LoggingUtils.ComposeHttpClientLogMessage(
                            _fulfillmentClient.GetType().Name,
                            nameof(_fulfillmentClient.UpdateSubscriptionOperationAsync),
                            subscriptionId));

                    var result = await _fulfillmentClient.UpdateSubscriptionOperationAsync(
                        subscriptionId,
                        subscription.OperationId ?? Guid.Empty,
                        update,
                        Guid.NewGuid(),
                        Guid.NewGuid(),
                        default);
                }

                switch (subscription.ProvisioningType)
                {
                case nameof(ProvisioningType.Update):
                case nameof(ProvisioningType.Reinstate):
                    subscription.Status = nameof(FulfillmentState.Subscribed);
                    break;

                case nameof(ProvisioningType.DeleteData):
                    subscription.Status = nameof(FulfillmentState.Purged);
                    break;

                case nameof(ProvisioningType.Suspend):
                    subscription.LastSuspendedTime = DateTime.UtcNow;
                    subscription.Status            = nameof(FulfillmentState.Suspended);
                    break;

                case nameof(ProvisioningType.Unsubscribe):
                    subscription.UnsubscribedTime = DateTime.UtcNow;
                    subscription.Status           = nameof(FulfillmentState.Unsubscribed);
                    break;

                default:
                    throw new ArgumentException($"Provisioning type {subscription.ProvisioningType} is not supported.");
                }
                subscription.ActivatedBy = activatedBy;
                return(await TransitToNextState(subscription, ProvisioningState.Succeeded));
            }
            catch (Exception e)
            {
                return(await HandleExceptions(subscription, e));
            }
        }
Пример #8
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int GetInfo(enum_PROCESS_INFO_FIELDS Fields, PROCESS_INFO [] infoArray)
        {
            //
            // Gets a description of the process.
            //

            LoggingUtils.PrintFunction();

            try
            {
                infoArray [0] = new PROCESS_INFO();

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_FILE_NAME) != 0)
                {
                    LoggingUtils.RequireOk(GetName(enum_GETNAME_TYPE.GN_FILENAME, out infoArray [0].bstrFileName));

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_FILE_NAME;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_BASE_NAME) != 0)
                {
                    LoggingUtils.RequireOk(GetName(enum_GETNAME_TYPE.GN_BASENAME, out infoArray [0].bstrBaseName));

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_BASE_NAME;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_TITLE) != 0)
                {
                    LoggingUtils.RequireOk(GetName(enum_GETNAME_TYPE.GN_TITLE, out infoArray [0].bstrTitle));

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_TITLE;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_PROCESS_ID) != 0)
                {
                    AD_PROCESS_ID [] processId = new AD_PROCESS_ID [1];

                    LoggingUtils.RequireOk(GetPhysicalProcessId(processId));

                    infoArray [0].ProcessId = processId [0];

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_PROCESS_ID;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_SESSION_ID) != 0)
                {
                    // We currently don't support multiple sessions, so all processes are in session 1.

                    infoArray [0].dwSessionId = 1;

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_SESSION_ID;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_ATTACHED_SESSION_NAME) != 0)
                {
                    // Oddly enough, SESSION_NAME is requested... even though the docs clearly state that it's deprecated.

                    infoArray [0].bstrAttachedSessionName = "[Attached session name is deprecated]";

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_ATTACHED_SESSION_NAME;
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_CREATION_TIME) != 0)
                {
                    // Not entirely clear how this should be implemented.

                    /*Microsoft.VisualStudio.OLE.Interop.FILETIME filetime;
                     *
                     * infoArray [0].CreationTime = filetime;
                     *
                     * infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_CREATION_TIME;*/
                }

                if ((Fields & enum_PROCESS_INFO_FIELDS.PIF_FLAGS) != 0)
                {
                    infoArray [0].Flags |= enum_PROCESS_INFO_FLAGS.PIFLAG_PROCESS_RUNNING;

                    if (DebuggeeProgram.AttachedEngine != null)
                    {
                        infoArray [0].Flags |= enum_PROCESS_INFO_FLAGS.PIFLAG_DEBUGGER_ATTACHED;
                    }

                    //enum_PROCESS_INFO_FLAGS.PIFLAG_DEBUGGER_ATTACHED
                    //enum_PROCESS_INFO_FLAGS.PIFLAG_PROCESS_STOPPED
                    //enum_PROCESS_INFO_FLAGS.PIFLAG_PROCESS_RUNNING

                    if (!NativeProcess.IsUserProcess)
                    {
                        infoArray [0].Flags |= enum_PROCESS_INFO_FLAGS.PIFLAG_SYSTEM_PROCESS;
                    }

                    infoArray [0].Fields |= enum_PROCESS_INFO_FIELDS.PIF_FLAGS;
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int CreateBoundBreakpoint(MiBreakpoint breakpoint, DebuggeeDocumentContext documentContext, DebuggeeCodeContext codeContext)
        {
            LoggingUtils.PrintFunction();

            try
            {
                if (breakpoint == null)
                {
                    throw new ArgumentNullException(nameof(breakpoint));
                }

                if (breakpoint.IsPending())
                {
                    //
                    // Address can't be satisfied. Unsatisfied likely indicates the modules or symbols associated with the context aren't loaded, yet.
                    //

                    DebuggeeAddress pendingAddress = new DebuggeeAddress(MiBreakpoint.Pending);

                    DebuggeeCodeContext pendingContext = new CLangDebuggeeCodeContext(m_debugger, pendingAddress, documentContext);

                    LoggingUtils.RequireOk(CreateErrorBreakpoint("Additional library symbols required.", breakpoint, documentContext, pendingContext));
                }
                else if (breakpoint.IsMultiple())
                {
                    //
                    // Breakpoint satisfied to multiple locations, no single memory address available.
                    //

                    CLangDebuggeeBreakpointBound boundBreakpoint = new CLangDebuggeeBreakpointBound(m_debugger, m_breakpointManager, this, codeContext, breakpoint);

                    lock (m_boundBreakpoints)
                    {
                        m_boundBreakpoints.Clear();

                        m_boundBreakpoints.Add(boundBreakpoint);
                    }

                    m_debugger.Engine.Broadcast(new DebugEngineEvent.BreakpointBound(this, boundBreakpoint), m_debugger.NativeProgram.DebugProgram, m_debugger.NativeProgram.GetThread(m_debugger.NativeProgram.CurrentThreadId));
                }
                else
                {
                    //
                    // Address satisfied, and the breakpoint is legitimately bound.
                    //

                    DebuggeeAddress boundAddress = new DebuggeeAddress(breakpoint.Address);

                    DebuggeeCodeContext addressContext = new CLangDebuggeeCodeContext(m_debugger, boundAddress, documentContext);

                    CLangDebuggeeBreakpointBound boundBreakpoint = new CLangDebuggeeBreakpointBound(m_debugger, m_breakpointManager, this, addressContext, breakpoint);

                    lock (m_boundBreakpoints)
                    {
                        m_boundBreakpoints.Clear();

                        m_boundBreakpoints.Add(boundBreakpoint);
                    }

                    m_debugger.Engine.Broadcast(new DebugEngineEvent.BreakpointBound(this, boundBreakpoint), m_debugger.NativeProgram.DebugProgram, m_debugger.NativeProgram.GetThread(m_debugger.NativeProgram.CurrentThreadId));
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #10
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void InstallApplicationAsync(AndroidDevice debuggingDevice, LaunchConfiguration launchConfig)
        {
            //
            // Asynchronous installation process, so the UI can be updated appropriately.
            //

            LoggingUtils.PrintFunction();

            ManualResetEvent installCompleteEvent = new ManualResetEvent(false);

            Exception installFailedException = null;

            System.Threading.Thread asyncInstallApplicationThread = new System.Threading.Thread(delegate()
            {
                try
                {
                    string targetLocalApk = launchConfig ["TargetApk"];

                    string targetRemoteTemporaryPath = "/data/local/tmp";

                    string targetRemoteTemporaryFile = targetRemoteTemporaryPath + '/' + Path.GetFileName(targetLocalApk);

                    bool keepData = launchConfig ["KeepAppData"].Equals("true");

                    string installerPackage = launchConfig ["InstallerPackage"];

                    //
                    // Construct 'am install' arguments for installing the application in a manner compatible with GDB.
                    //
                    // Note: Installations to /mnt/asec/ cause 'run-as' to fail regarding permissions.
                    //

                    StringBuilder installArgsBuilder = new StringBuilder();

                    installArgsBuilder.Append("-f "); // install package on internal flash. (required for debugging)

                    if (keepData)
                    {
                        installArgsBuilder.Append("-r "); // reinstall an existing app, keeping its data.
                    }

                    if (!string.IsNullOrWhiteSpace(installerPackage))
                    {
                        installArgsBuilder.Append(string.Format(CultureInfo.InvariantCulture, "-i {0} ", installerPackage));
                    }

                    installArgsBuilder.Append(targetRemoteTemporaryFile);

                    //
                    // Explicitly install the target APK using 'pm' tool, as this allows more customisation.
                    //
                    //  1) APKs must already be on the device for this tool to work. We push these manually.
                    //
                    //  2) Installations can fail for various reasons; errors are reported thusly:
                    //         pkg: /data/local/tmp/hello-gdbserver-Debug.apk
                    //       Failure [INSTALL_FAILED_INVALID_URI]
                    //

                    m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "[adb:push] {0} {1}", targetLocalApk, targetRemoteTemporaryPath), false);

                    debuggingDevice.Push(targetLocalApk, targetRemoteTemporaryPath);

                    m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "[adb:shell:pm] {0} {1}", "install", installArgsBuilder.ToString()), false);

                    string installReport = debuggingDevice.Shell("pm", "install " + installArgsBuilder.ToString(), int.MaxValue);

                    if (!installReport.Contains("Success"))
                    {
                        string sanitisedFailure = installReport;

                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "[adb:shell:pm] install failed: {0}", sanitisedFailure));
                    }

                    m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "[adb:shell:rm] {0}", targetRemoteTemporaryFile), false);

                    debuggingDevice.Shell("rm", targetRemoteTemporaryFile);
                }
                catch (Exception e)
                {
                    LoggingUtils.HandleException(e);

                    installFailedException = e;

                    throw;
                }
                finally
                {
                    installCompleteEvent.Set();
                }
            });

            asyncInstallApplicationThread.Start();

            while (!installCompleteEvent.WaitOne(0))
            {
                Application.DoEvents();

                System.Threading.Thread.Sleep(100);
            }

            if (installFailedException != null)
            {
                throw installFailedException;
            }
        }
Пример #11
0
        public LaunchConfiguration GetLaunchConfigurationFromProjectProperties(IDictionary <string, string> projectProperties)
        {
            LoggingUtils.PrintFunction();

            //
            // Retrieve standard project macro values, and determine the preferred debugger configuration.
            //

            string projectTargetName = EvaluateProjectProperty(projectProperties, "ConfigurationGeneral", "TargetName");

            string projectProjectDir = EvaluateProjectProperty(projectProperties, "ConfigurationGeneral", "ProjectDir");

            string debuggerMode = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigMode");

            string debuggerTargetApk = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigTargetApk");

            string debuggerUpToDateCheck = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigUpToDateCheck");

            string debuggerLaunchActivity = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigLaunchActivity");

            string debuggerDebugMode = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigDebugMode");

            string debuggerOpenGlTrace = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigOpenGlTrace");

            string debuggerKeepAppData = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigKeepAppData");

            string debuggerInstallerPackage = EvaluateProjectProperty(projectProperties, "AndroidPlusPlusDebugger", "DebuggerConfigInstallerPackage");

            if (string.IsNullOrEmpty(debuggerMode))
            {
                debuggerMode = "Custom";
            }
            else if (debuggerMode.Equals("vs-android"))
            {
                //
                // Support for vs-android.
                //

                string antBuildPath = EvaluateProjectProperty(projectProperties, "AntBuild", "AntBuildPath");

                string antBuildType = EvaluateProjectProperty(projectProperties, "AntBuild", "AntBuildType");

                string antBuildXml = Path.Combine(antBuildPath, "build.xml");

                XmlDocument buildXmlDocument = new XmlDocument();

                buildXmlDocument.Load(antBuildXml);

                string antBuildXmlProjectName = buildXmlDocument.DocumentElement.GetAttribute("name");

                debuggerTargetApk = Path.Combine(antBuildPath, "bin", string.Format(CultureInfo.InvariantCulture, "{0}-{1}.apk", antBuildXmlProjectName, antBuildType));
            }

            //
            // Ensure the provided target APK is found and absolute.
            //

            if (string.IsNullOrEmpty(debuggerTargetApk))
            {
                throw new FileNotFoundException("Could not locate target application. Empty path provided.");
            }
            else if (!Path.IsPathRooted(debuggerTargetApk) && !string.IsNullOrWhiteSpace(projectProjectDir))
            {
                debuggerTargetApk = Path.Combine(projectProjectDir, debuggerTargetApk);
            }

            if (!Path.IsPathRooted(debuggerTargetApk))
            {
                throw new InvalidOperationException("Could not evaluate an absolute path to the target application. Tried: " + debuggerTargetApk);
            }

            debuggerTargetApk = Path.GetFullPath(debuggerTargetApk); // normalises relative paths.

            if (!File.Exists(debuggerTargetApk))
            {
                throw new FileNotFoundException("Could not find required target application. Expected: " + debuggerTargetApk);
            }

            //
            // Find the selected Android SDK (and associated build-tools) deployment.
            //

            string androidSdkRoot = EvaluateProjectProperty(projectProperties, "ConfigurationGeneral", "AndroidSdkRoot");

            if (string.IsNullOrWhiteSpace(androidSdkRoot))
            {
                throw new DirectoryNotFoundException("Could not locate Android SDK. \"AndroidSdkRoot\" property is empty.");
            }
            else if (!Directory.Exists(androidSdkRoot))
            {
                throw new DirectoryNotFoundException("Could not locate Android SDK. \"AndroidSdkRoot\" property references a directory which does not exist. Expected: " + androidSdkRoot);
            }

            string androidSdkBuildToolsVersion = EvaluateProjectProperty(projectProperties, "ConfigurationGeneral", "AndroidSdkBuildToolsVersion");

            string androidSdkBuildToolsPath = Path.Combine(androidSdkRoot, "build-tools", androidSdkBuildToolsVersion);

            if (!Directory.Exists(androidSdkBuildToolsPath))
            {
                throw new DirectoryNotFoundException(string.Format(CultureInfo.CurrentCulture, "Could not locate Android SDK build-tools (v{0}). Expected: {1}", androidSdkBuildToolsVersion, androidSdkBuildToolsPath));
            }

            //
            // Spawn a AAPT.exe instance to gain some extra information about the APK we are trying to load.
            //

            string applicationPackageName = string.Empty;

            string applicationLaunchActivity = string.Empty;

            string aaptToolPath = Path.Combine(androidSdkBuildToolsPath, "aapt.exe");

            if (!File.Exists(aaptToolPath))
            {
                throw new FileNotFoundException("Could not locate AAPT tool (under Android SDK build-tools).", aaptToolPath);
            }

            using (SyncRedirectProcess getApkDetails = new SyncRedirectProcess(aaptToolPath, "dump --values badging " + PathUtils.SantiseWindowsPath(debuggerTargetApk)))
            {
                int exitCode = getApkDetails.StartAndWaitForExit();

                if (exitCode != 0)
                {
                    throw new InvalidOperationException("AAPT failed to dump required application badging information. Exit-code: " + exitCode);
                }

                string [] apkDetails = getApkDetails.StandardOutput.Replace("\r", "").Split(new char [] { '\n' });

                foreach (string singleLine in apkDetails)
                {
                    if (singleLine.StartsWith("package: ", StringComparison.OrdinalIgnoreCase))
                    {
                        //
                        // Retrieve package name from format: "package: name='com.example.hellogdbserver' versionCode='1' versionName='1.0'"
                        //

                        string [] packageData = singleLine.Substring("package: ".Length).Split(' ');

                        foreach (string data in packageData)
                        {
                            if (data.StartsWith("name=", StringComparison.OrdinalIgnoreCase))
                            {
                                applicationPackageName = data.Substring("name=".Length).Trim('\'');
                            }
                        }
                    }
                    else if (singleLine.StartsWith("launchable-activity: ", StringComparison.OrdinalIgnoreCase))
                    {
                        string [] launchActivityData = singleLine.Substring("launchable-activity: ".Length).Split(' ');

                        foreach (string data in launchActivityData)
                        {
                            if (data.StartsWith("name=", StringComparison.OrdinalIgnoreCase))
                            {
                                applicationLaunchActivity = data.Substring("name=".Length).Trim('\'');
                            }
                        }
                    }
                }
            }

            //
            // If a specific launch activity was not requested, ensure that the default one is referenced.
            //

            if (string.IsNullOrEmpty(debuggerLaunchActivity))
            {
                debuggerLaunchActivity = applicationLaunchActivity;
            }

            LaunchConfiguration launchConfig = new LaunchConfiguration();

            launchConfig ["TargetApk"] = debuggerTargetApk;

            launchConfig ["UpToDateCheck"] = debuggerUpToDateCheck;

            launchConfig ["PackageName"] = applicationPackageName;

            launchConfig ["LaunchActivity"] = debuggerLaunchActivity;

            launchConfig ["DebugMode"] = debuggerDebugMode;

            launchConfig ["OpenGlTrace"] = debuggerOpenGlTrace;

            launchConfig ["KeepAppData"] = debuggerKeepAppData;

            launchConfig ["InstallerPackage"] = debuggerInstallerPackage;

            return(launchConfig);
        }
Пример #12
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public object StartWithDebugging(int launchOptions, LaunchConfiguration launchConfig, LaunchProps [] launchProps, IDictionary <string, string> projectProperties)
        {
            LoggingUtils.PrintFunction();

            if (launchConfig == null)
            {
                throw new ArgumentNullException("launchConfig");
            }

            if (launchProps == null)
            {
                throw new ArgumentNullException("launchProps");
            }

            if (projectProperties == null)
            {
                throw new ArgumentNullException("projectProperties");
            }

            try
            {
                //
                // Refresh ADB service and evaluate a list of connected devices or emulators.
                //

                AndroidAdb.Refresh();

                AndroidDevice debuggingDevice = GetPrioritisedConnectedDevice();

                if (debuggingDevice == null)
                {
                    throw new InvalidOperationException("No device/emulator found or connected. Check status using \"adb devices\".");
                }

                //
                // Enforce required device/emulator properties.
                //

                foreach (LaunchProps prop in launchProps)
                {
                    debuggingDevice.Shell("setprop", string.Format(CultureInfo.InvariantCulture, "{0} {1}", prop.Item1, prop.Item2));
                }

                //
                // Construct VS launch settings to debug or attach to the specified target application.
                //

                bool shouldAttach = false;

#if false
                AndroidProcess [] debuggingDeviceProcesses = debuggingDevice.GetProcesses();

                foreach (AndroidProcess process in debuggingDeviceProcesses)
                {
                    if (process.Name.Equals(applicationPackageName))
                    {
                        shouldAttach = true;

                        break;
                    }
                }
#endif

                launchOptions |= (int)DebugLaunchOptions.Silent;

                DebugLaunchSettings debugLaunchSettings = new DebugLaunchSettings((DebugLaunchOptions)launchOptions);

                debugLaunchSettings.LaunchDebugEngineGuid = new Guid("8310DAF9-1043-4C8E-85A0-FF68896E1922");

                debugLaunchSettings.PortSupplierGuid = new Guid("3AEE417F-E5F9-4B89-BC31-20534C99B7F5");

                debugLaunchSettings.PortName = debuggingDevice.ID;

                debugLaunchSettings.Options = launchConfig.ToString();

                if (shouldAttach)
                {
                    debugLaunchSettings.Executable = launchConfig ["PackageName"];

                    debugLaunchSettings.LaunchOperation = DebugLaunchOperation.AlreadyRunning;
                }
                else
                {
                    //
                    // Determine whether the application is currently installed, and if it is;
                    // check last modified date to ensure we don't re-installed unchanged binaries.
                    //

                    bool upToDateCheck = launchConfig ["UpToDateCheck"].Equals("true");

                    bool appIsInstalled = false;

                    bool appIsOutOfDate = true;

                    if (upToDateCheck)
                    {
                        FileInfo targetApkFileInfo = new FileInfo(launchConfig ["TargetApk"]);

                        try
                        {
                            string [] adbPmPathOutput = debuggingDevice.Shell("pm", "path " + launchConfig ["PackageName"]).Replace("\r", "").Split(new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                            foreach (string line in adbPmPathOutput)
                            {
                                if (line.StartsWith("package:", StringComparison.OrdinalIgnoreCase))
                                {
                                    appIsInstalled = true;

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' already installed on target '{1}'.", launchConfig ["PackageName"], debuggingDevice.ID), false));

                                    string path = line.Substring("package:".Length);

                                    //
                                    // Get the target device/emulator's UTC current time.
                                    //
                                    //   This is done by specifying the '-u' argument to 'date'. Despite this though,
                                    //   the returned string will always claim to be in GMT:
                                    //
                                    //   i.e: "Fri Jan  9 14:35:23 GMT 2015"
                                    //

                                    DateTime debuggingDeviceUtcTime;

                                    try
                                    {
                                        string [] deviceDateOutput = debuggingDevice.Shell("date", "-u").Replace("\r", "").Split(new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                                        string debuggingDeviceUtcTimestamp = deviceDateOutput [0];

                                        string [] debuggingDeviceUtcTimestampComponents = debuggingDeviceUtcTimestamp.Split(new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                                        debuggingDeviceUtcTimestampComponents [4] = "-00:00";

                                        if (!DateTime.TryParseExact(string.Join(" ", debuggingDeviceUtcTimestampComponents), "ddd MMM  d HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out debuggingDeviceUtcTime))
                                        {
                                            break;
                                        }

                                        debuggingDeviceUtcTime = debuggingDeviceUtcTime.ToUniversalTime();
                                    }
                                    catch (Exception e)
                                    {
                                        throw new InvalidOperationException("Failed to evaluate device local time.", e);
                                    }

                                    //
                                    // Convert current device/emulator time to UTC, and probe the working machine's time too.
                                    //

                                    DateTime thisMachineUtcTime = DateTime.UtcNow;

                                    TimeSpan thisMachineUtcVersusDeviceUtc = debuggingDeviceUtcTime - thisMachineUtcTime;

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "Current UTC time on '{0}': {1}", debuggingDevice.ID, debuggingDeviceUtcTime.ToString()), false));

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "Current UTC time on '{0}': {1}", System.Environment.MachineName, thisMachineUtcTime.ToString()), false));

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "Difference in UTC time between '{0}' and '{1}': {2}", System.Environment.MachineName, debuggingDevice.ID, thisMachineUtcVersusDeviceUtc.ToString()), false));

                                    //
                                    // Check the last modified date; ls output currently uses this format:
                                    //
                                    // -rw-r--r-- system   system   11533274 2015-01-09 13:47 com.example.native_activity-2.apk
                                    //

                                    DateTime lastModifiedTimestampDeviceLocalTime;

                                    try
                                    {
                                        string [] extendedLsOutput = debuggingDevice.Shell("ls -l", path).Replace("\r", "").Split(new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                                        string [] extendedLsOutputComponents = extendedLsOutput [0].Split(new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                                        string date = extendedLsOutputComponents [4];

                                        string time = extendedLsOutputComponents [5];

                                        if (!DateTime.TryParseExact(date + " " + time, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out lastModifiedTimestampDeviceLocalTime))
                                        {
                                            break;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Failed to evaluate device local modified time of: {0}", path), e);
                                    }

                                    //
                                    // Calculate how long ago the APK was changed, according to the device's local time.
                                    //

                                    TimeSpan timeSinceLastModification = debuggingDeviceUtcTime - lastModifiedTimestampDeviceLocalTime;

                                    DateTime debuggingDeviceUtcTimeAtLastModification = debuggingDeviceUtcTime - timeSinceLastModification;

                                    DateTime thisMachineUtcTimeAtLastModification = thisMachineUtcTime - timeSinceLastModification;

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' was last modified on '{1}' at: {2}.", launchConfig ["PackageName"], debuggingDevice.ID, debuggingDeviceUtcTimeAtLastModification.ToString()), false));

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "{0} (on {1}) was around {2} (on {3}).", debuggingDeviceUtcTimeAtLastModification.ToString(), debuggingDevice.ID, thisMachineUtcTimeAtLastModification.ToString(), System.Environment.MachineName), false));

                                    LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' was last modified on '{1}' at: {2}.", Path.GetFileName(targetApkFileInfo.FullName), System.Environment.MachineName, targetApkFileInfo.LastWriteTime.ToString()), false));

                                    if ((targetApkFileInfo.LastWriteTime + thisMachineUtcVersusDeviceUtc) > thisMachineUtcTimeAtLastModification)
                                    {
                                        LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' was determined to be out-of-date. Reinstalling...", launchConfig ["PackageName"]), false));
                                    }
                                    else
                                    {
                                        appIsOutOfDate = false;
                                    }

                                    break;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            appIsInstalled = false;
                        }
                    }
                    else
                    {
                        LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate("Skipping up-to-date check.", false));
                    }

                    if (!appIsInstalled || appIsOutOfDate)
                    {
                        LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "Installing '{0}' to '{1}'...", launchConfig ["PackageName"], debuggingDevice.ID), false));

                        InstallApplicationAsync(debuggingDevice, launchConfig);

                        LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' installed successfully.", launchConfig ["PackageName"]), false));
                    }
                    else
                    {
                        LoggingUtils.RequireOk(m_debugConnectionService.LaunchDialogUpdate(string.Format(CultureInfo.InvariantCulture, "'{0}' on '{1}' is up-to-date. Skipping installation...", launchConfig ["PackageName"], debuggingDevice.ID), false));
                    }

                    debugLaunchSettings.Executable = launchConfig ["TargetApk"];

                    debugLaunchSettings.LaunchOperation = DebugLaunchOperation.Custom;
                }

                return(debugLaunchSettings);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                throw;
            }
        }
Пример #13
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public object StartWithoutDebugging(int launchOptions, LaunchConfiguration launchConfig, LaunchProps [] launchProps, IDictionary <string, string> projectProperties)
        {
            LoggingUtils.PrintFunction();

            if (launchConfig == null)
            {
                throw new ArgumentNullException("launchConfig");
            }

            if (launchProps == null)
            {
                throw new ArgumentNullException("launchProps");
            }

            if (projectProperties == null)
            {
                throw new ArgumentNullException("projectProperties");
            }

            try
            {
                //
                // Refresh ADB service and evaluate a list of connected devices or emulators.
                //

                AndroidAdb.Refresh();

                AndroidDevice debuggingDevice = GetPrioritisedConnectedDevice();

                if (debuggingDevice == null)
                {
                    throw new InvalidOperationException("No device/emulator found or connected. Check status using \"adb devices\".");
                }

                //
                // Construct VS launch settings to debug or attach to the specified target application.
                //

                launchOptions |= (int)DebugLaunchOptions.Silent;

                DebugLaunchSettings nonDebuglaunchSettings = new DebugLaunchSettings((DebugLaunchOptions)launchOptions);

                nonDebuglaunchSettings.LaunchDebugEngineGuid = new Guid("8310DAF9-1043-4C8E-85A0-FF68896E1922");

                nonDebuglaunchSettings.PortSupplierGuid = new Guid("3AEE417F-E5F9-4B89-BC31-20534C99B7F5");

                nonDebuglaunchSettings.PortName = debuggingDevice.ID;

                nonDebuglaunchSettings.Options = launchConfig.ToString();

                nonDebuglaunchSettings.Executable = launchConfig ["TargetApk"];

                nonDebuglaunchSettings.LaunchOperation = DebugLaunchOperation.Custom;

                return(nonDebuglaunchSettings);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                throw;
            }
        }
Пример #14
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int Compare(enum_CONTEXT_COMPARE contextCompare, IDebugMemoryContext2 [] compareToItems, uint compareToLength, out uint foundIndex)
        {
            //
            // Compares the memory context to each context in the given array in the manner indicated by compare flags,
            // returning an index of the first context that matches.
            //

            LoggingUtils.PrintFunction();

            try
            {
                if (compareToItems.Length != compareToLength)
                {
                    throw new ArgumentException("Comparing contexts of different sizes.");
                }

                //
                // Get the context info for the current object.
                //

                CONTEXT_INFO [] currentContextInfo = new CONTEXT_INFO [1];

                LoggingUtils.RequireOk(GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_ALLFIELDS, currentContextInfo));

                for (uint i = 0; i < compareToLength; ++i)
                {
                    DebuggeeCodeContext compareTo = compareToItems [i] as DebuggeeCodeContext;

                    if (compareTo == null)
                    {
                        continue;
                    }

                    CONTEXT_INFO [] compareToInfo = new CONTEXT_INFO [1];

                    LoggingUtils.RequireOk(compareTo.GetInfo(enum_CONTEXT_INFO_FIELDS.CIF_ALLFIELDS, compareToInfo));

                    if (!DebugEngine.ReferenceEquals(m_engine, compareTo.m_engine))
                    {
                        continue;
                    }

                    bool comparisonResult = false;

                    switch (contextCompare)
                    {
                    case enum_CONTEXT_COMPARE.CONTEXT_EQUAL:
                    {
                        comparisonResult = (currentContextInfo [0].bstrAddressAbsolute.CompareTo(compareToInfo [0].bstrAddressAbsolute) == 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN:
                    {
                        comparisonResult = (currentContextInfo [0].bstrAddressAbsolute.CompareTo(compareToInfo [0].bstrAddressAbsolute) < 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN:
                    {
                        comparisonResult = (currentContextInfo [0].bstrAddressAbsolute.CompareTo(compareToInfo [0].bstrAddressAbsolute) > 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL:
                    {
                        comparisonResult = (currentContextInfo [0].bstrAddressAbsolute.CompareTo(compareToInfo [0].bstrAddressAbsolute) <= 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL:
                    {
                        comparisonResult = (currentContextInfo [0].bstrAddressAbsolute.CompareTo(compareToInfo [0].bstrAddressAbsolute) >= 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_PROCESS:
                    {
                        comparisonResult = true;

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION:
                    {
                        comparisonResult = (currentContextInfo [0].bstrFunction.CompareTo(compareToInfo [0].bstrFunction) == 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_MODULE:
                    {
                        comparisonResult = (currentContextInfo [0].bstrModuleUrl.CompareTo(compareToInfo [0].bstrModuleUrl) == 0);

                        break;
                    }

                    case enum_CONTEXT_COMPARE.CONTEXT_SAME_SCOPE:
                    // Fallthrough.
                    default:
                    {
                        throw new NotImplementedException();
                    }
                    }

                    if (comparisonResult)
                    {
                        foundIndex = i;

                        return(Constants.S_OK);
                    }
                }
            }
            catch (NotImplementedException e)
            {
                LoggingUtils.HandleException(e);

                foundIndex = uint.MaxValue;

                return(Constants.E_NOTIMPL);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                foundIndex = uint.MaxValue;

                return(Constants.E_COMPARE_CANNOT_COMPARE);
            }

            foundIndex = uint.MaxValue;

            return(Constants.S_FALSE);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private MiVariable [] GetChildVariables(MiVariable parentVariable, int depth)
        {
            LoggingUtils.PrintFunction();

            List <MiVariable> childVariables = new List <MiVariable> ();

            if ((depth > 0) && (parentVariable.HasChildren))
            {
                string command = string.Format("-var-list-children --all-values \"{0}\"", parentVariable.Name);

                MiResultRecord resultRecord = m_debugger.GdbClient.SendSyncCommand(command);

                MiResultRecord.RequireOk(resultRecord, command);

                if (resultRecord.HasField("children"))
                {
                    List <MiResultValue> childrenList = resultRecord ["children"] [0] ["child"];

                    for (int i = 0; i < childrenList.Count; ++i)
                    {
                        MiResultValueTuple childTuple = childrenList [i] as MiResultValueTuple;

                        string variableName = childTuple ["name"] [0].GetString();

                        MiVariable childVariable = null;

                        bool isPseudoChild = false;

                        if (childTuple.HasField("exp"))
                        {
                            string variableExpression = childTuple ["exp"] [0].GetString();

                            if (!string.IsNullOrEmpty(variableExpression))
                            {
                                childVariable = new MiVariable(variableName, variableExpression);

                                childVariable.Populate(childTuple.Values);

                                isPseudoChild = childVariable.IsPseudoChild;
                            }
                        }

                        if (childVariable == null)
                        {
                            childVariable = new MiVariable(variableName, childTuple.Values);
                        }

                        if (isPseudoChild)
                        {
                            depth += 1; // need an additional level of children.

                            MiVariable [] evaluatedChildren = GetChildVariables(childVariable, depth - 1);

                            foreach (MiVariable child in evaluatedChildren)
                            {
                                childVariable.AddChild(child);
                            }
                        }

                        childVariables.Add(childVariable);
                    }
                }
            }

            return(childVariables.ToArray());
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void RefreshBreakpoint(object breakpoint)
        {
            //
            // Validate breakpoint input type. This function can be used for 'bound' and 'error' objects, so we need to handle this appropriately.
            //

            LoggingUtils.PrintFunction();

            CLangDebuggeeBreakpointBound boundBreakpoint = null;

            CLangDebuggeeBreakpointError errorBreakpoint = null;

            MiBreakpoint gdbBreakpoint;

            DebuggeeBreakpointResolution resolution;

            if (breakpoint == null)
            {
                throw new ArgumentNullException(nameof(breakpoint));
            }
            else if (breakpoint is CLangDebuggeeBreakpointBound)
            {
                boundBreakpoint = breakpoint as CLangDebuggeeBreakpointBound;

                gdbBreakpoint = boundBreakpoint.GdbBreakpoint;

                IDebugBreakpointResolution2 boundBreakpointResolution;

                int handle = boundBreakpoint.GetBreakpointResolution(out boundBreakpointResolution);

                if (handle == Constants.E_BP_DELETED)
                {
                    return;
                }

                LoggingUtils.RequireOk(handle);

                resolution = (DebuggeeBreakpointResolution)boundBreakpointResolution;
            }
            else if (breakpoint is CLangDebuggeeBreakpointError)
            {
                errorBreakpoint = breakpoint as CLangDebuggeeBreakpointError;

                gdbBreakpoint = errorBreakpoint.GdbBreakpoint;

                IDebugErrorBreakpointResolution2 errorBreakpointResolution;

                int handle = errorBreakpoint.GetBreakpointResolution(out errorBreakpointResolution);

                if (handle == Constants.E_BP_DELETED)
                {
                    return;
                }

                resolution = (DebuggeeBreakpointResolution)errorBreakpointResolution;

                lock (m_errorBreakpoints)
                {
                    m_errorBreakpoints.Remove(errorBreakpoint);
                }
            }
            else
            {
                throw new ArgumentException("breakpoint");
            }

            //
            // Query breakpoint info/status directly from GDB/MI.
            //

            string command = string.Format("-break-info {0}", gdbBreakpoint.ID);

            m_debugger.GdbClient.SendCommand(command, (MiResultRecord resultRecord) =>
            {
                if (resultRecord == null)
                {
                    throw new InvalidOperationException();
                }
                else if (resultRecord.IsError())
                {
                    //
                    // GDB/MI breakpoint info request failed.
                    //

                    gdbBreakpoint.Address = MiBreakpoint.Pending;

                    (resolution as DebuggeeBreakpointResolution).CodeContext.Address = new DebuggeeAddress(gdbBreakpoint.Address);

                    errorBreakpoint = new CLangDebuggeeBreakpointError(m_debugger, m_breakpointManager, this, (resolution as DebuggeeBreakpointResolution).CodeContext, gdbBreakpoint, resultRecord.Records [1].Stream);

                    lock (m_errorBreakpoints)
                    {
                        m_errorBreakpoints.Add(errorBreakpoint);
                    }

                    m_debugger.Engine.Broadcast(new DebugEngineEvent.BreakpointError(errorBreakpoint), m_debugger.NativeProgram.DebugProgram, m_debugger.NativeProgram.GetThread(m_debugger.NativeProgram.CurrentThreadId));
                }
                else
                {
                    //
                    // We've probably got sane breakpoint information back. Update current breakpoint values and re-process.
                    //

                    MiResultValue breakpointData = resultRecord ["BreakpointTable"] [0] ["body"] [0] ["bkpt"] [0];

                    MiBreakpoint currentGdbBreakpoint = new MiBreakpoint(breakpointData.Values);

                    DebuggeeCodeContext codeContext = (resolution as DebuggeeBreakpointResolution).CodeContext;

                    DebuggeeDocumentContext documentContext = codeContext.DocumentContext;

                    LoggingUtils.RequireOk(CreateBoundBreakpoint(currentGdbBreakpoint, documentContext, codeContext));
                }
            });
        }
Пример #17
0
        public async Task <Subscription> CreateResourceGroupAsync(Guid subscriptionId)
        {
            Subscription subscription = await _context.Subscriptions.FindAsync(subscriptionId);

            ValidateSubscriptionAndInputState(subscription);

            try
            {
                Offer offer = await FindOfferById(subscription.OfferId);

                Plan plan = await FindPlanById(subscription.PlanId);

                string isvSubscriptionId = offer.HostSubscription.ToString();

                var parameters = await EvaluateParameters(offer, plan, subscription);

                subscription.EntryPointUrl = parameters.ContainsKey("entryPointUrl") ? parameters["entryPointUrl"].ToString() : "";

                if (plan.SubscribeArmTemplateId == null)
                {
                    // Don't need to deploy anything, transit to WebhookPending state
                    return(await TransitToNextState(subscription, ProvisioningState.WebhookPending));
                }

                string azureLocation     = null;
                string resourceGroupName = $"{offer.OfferName}-{subscription.SubscriptionId}";

                if (parameters.ContainsKey("resourceGroupLocation"))
                {
                    azureLocation = parameters["resourceGroupLocation"].ToString();
                }
                else
                {
                    throw new LunaBadRequestUserException("The ResourceGroupLocation parameter is not specified.", UserErrorCode.ParameterNotProvided);
                }

                _logger.LogInformation(
                    LoggingUtils.ComposeHttpClientLogMessage(
                        _provisioningClient.GetType().Name,
                        nameof(_provisioningClient.ResourceGroupExistsAsync),
                        subscriptionId));

                bool resourceGroupExists = await _provisioningClient.ResourceGroupExistsAsync(
                    Guid.NewGuid(),
                    Guid.NewGuid(),
                    isvSubscriptionId,
                    resourceGroupName,
                    default);

                if (!resourceGroupExists)
                {
                    _logger.LogInformation(
                        LoggingUtils.ComposeHttpClientLogMessage(
                            _provisioningClient.GetType().Name,
                            nameof(_provisioningClient.CreateOrUpdateResourceGroupAsync),
                            subscriptionId));

                    var result = await _provisioningClient.CreateOrUpdateResourceGroupAsync(
                        Guid.NewGuid(),
                        Guid.NewGuid(),
                        isvSubscriptionId,
                        resourceGroupName,
                        azureLocation,
                        default
                        );

                    _logger.LogInformation($"Deploying resource group {resourceGroupName} in location {azureLocation}.");
                }
                else
                {
                    throw new LunaConflictUserException($"Resource group with name {resourceGroupName} already exist.");
                }

                subscription.ResourceGroup = resourceGroupName;

                return(await TransitToNextState(subscription, ProvisioningState.DeployResourceGroupRunning));
            }
            catch (Exception e)
            {
                return(await HandleExceptions(subscription, e));
            }
        }
Пример #18
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum)
        {
            //
            // Enumerates the code contexts for a given position in a source file.
            //

            LoggingUtils.PrintFunction();

            ppEnum = null;

            try
            {
                if (AttachedEngine == null)
                {
                    throw new InvalidOperationException();
                }

                List <IDebugCodeContext2> codeContexts = new List <IDebugCodeContext2> ();

                uint count;

                {
                    LoggingUtils.RequireOk(AttachedEngine.NativeDebugger.NativeProgram.EnumCodeContexts(pDocPos, out ppEnum));

                    LoggingUtils.RequireOk(ppEnum.GetCount(out count));

                    IDebugCodeContext2 [] codeContextArray = new IDebugCodeContext2 [count];

                    LoggingUtils.RequireOk(ppEnum.Next(count, codeContextArray, ref count));

                    codeContexts.AddRange(codeContextArray);
                }

#if false
                {
                    LoggingUtils.RequireOk(AttachedEngine.JavaDebugger.JavaProgram.EnumCodeContexts(pDocPos, out ppEnum));

                    LoggingUtils.RequireOk(ppEnum.GetCount(out count));

                    IDebugCodeContext2 [] codeContextArray = new IDebugCodeContext2 [count];

                    LoggingUtils.RequireOk(ppEnum.Next(count, codeContextArray, ref count));

                    codeContexts.AddRange(codeContextArray);
                }
#endif

                ppEnum = new DebuggeeCodeContext.Enumerator(codeContexts);

                if (ppEnum == null)
                {
                    throw new InvalidOperationException();
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #19
0
        public async Task <Subscription> ExecuteWebhookAsync(Guid subscriptionId)
        {
            Subscription subscription = await _context.Subscriptions.FindAsync(subscriptionId);

            ValidateSubscriptionAndInputState(subscription);

            try
            {
                Offer offer = await FindOfferById(subscription.OfferId);

                Plan plan = await FindPlanById(subscription.PlanId);

                string urlString = await GetWebhookUrl(plan, subscription.ProvisioningType);

                // Only run the webhook if it is specified.
                if (urlString != null)
                {
                    Context context = await SetContext(offer.OfferName, subscription.Owner, subscriptionId, plan.PlanName, subscription.ProvisioningType);

                    UriBuilder webhookUri = new UriBuilder(urlString);
                    var        query      = HttpUtility.ParseQueryString(webhookUri.Query);

                    foreach (var key in query.AllKeys)
                    {
                        if (query[key].StartsWith("{", StringComparison.InvariantCultureIgnoreCase) && query[key].EndsWith("}", StringComparison.InvariantCultureIgnoreCase))
                        {
                            string parameterName = query[key].Substring(1, query[key].Length - 2);
                            if (context.Parameters.ContainsKey(parameterName))
                            {
                                query[key] = context.Parameters[parameterName].ToString();
                            }
                            else
                            {
                                //re-evaluate the parameter and reset the context
                                await EvaluateParameters(offer, plan, subscription);

                                context = await SetContext(offer.OfferName, subscription.Owner, subscriptionId, plan.PlanName, subscription.ProvisioningType);

                                if (context.Parameters.ContainsKey(parameterName))
                                {
                                    query[key] = context.Parameters[parameterName].ToString();
                                }
                                else
                                {
                                    // There's a bug if this happens.
                                    throw new LunaServerException($"Webhook parameter {parameterName} doesn't exist.");
                                }
                            }
                        }
                    }

                    webhookUri.Query = query.ToString();

                    _logger.LogInformation(
                        LoggingUtils.ComposeHttpClientLogMessage(
                            _provisioningClient.GetType().Name,
                            nameof(_provisioningClient.ExecuteWebhook),
                            subscriptionId));

                    await _provisioningClient.ExecuteWebhook(webhookUri.Uri);

                    _logger.LogInformation($"Running webhook {webhookUri.Uri} for subscription {subscriptionId}.");
                }

                return(await TransitToNextState(subscription, ProvisioningState.NotificationPending));
            }
            catch (Exception e)
            {
                return(await HandleExceptions(subscription, e));
            }
        }
Пример #20
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int EnumModules(out IEnumDebugModules2 ppEnum)
        {
            //
            // Enumerates the modules that this program has loaded and is executing.
            //

            LoggingUtils.PrintFunction();

            ppEnum = null;

            try
            {
                if (AttachedEngine == null)
                {
                    throw new InvalidOperationException();
                }

                List <IDebugModule2> modules = new List <IDebugModule2> ();

                uint count;

                {
                    LoggingUtils.RequireOk(AttachedEngine.NativeDebugger.NativeProgram.EnumModules(out ppEnum));

                    LoggingUtils.RequireOk(ppEnum.GetCount(out count));

                    IDebugModule2 [] moduleArray = new IDebugModule2 [count];

                    LoggingUtils.RequireOk(ppEnum.Next(count, moduleArray, ref count));

                    modules.AddRange(moduleArray);
                }

                {
                    LoggingUtils.RequireOk(AttachedEngine.JavaDebugger.JavaProgram.EnumModules(out ppEnum));

                    LoggingUtils.RequireOk(ppEnum.GetCount(out count));

                    IDebugModule2 [] moduleArray = new IDebugModule2 [count];

                    LoggingUtils.RequireOk(ppEnum.Next(count, moduleArray, ref count));

                    modules.AddRange(moduleArray);
                }

                ppEnum = new DebuggeeModule.Enumerator(modules);

                if (ppEnum == null)
                {
                    throw new InvalidOperationException();
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #21
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int RefreshProcesses()
        {
            //
            // Check which processes are currently running on the target device (port).
            //

            LoggingUtils.PrintFunction();

            try
            {
                m_portDevice.RefreshProcesses();

                m_portProcesses.Clear();

                //
                // Register a new process with this port if it was spawned by 'zygote'.
                //

                uint [] zygotePids = m_portDevice.GetPidsFromName("zygote");

                if (zygotePids.Length > 0)
                {
                    uint [] activeZygoteSpawnedPids = m_portDevice.GetChildPidsFromPpid(zygotePids [0]);

                    for (int i = 0; i < activeZygoteSpawnedPids.Length; ++i)
                    {
                        uint pid = activeZygoteSpawnedPids [i];

                        AndroidProcess nativeProcess = m_portDevice.GetProcessFromPid(pid);

                        m_portProcesses.Add(pid, new DebuggeeProcess(this, nativeProcess));
                    }
                }

                //
                // Register a new process with this port if it was spawned by 'zygote64' (it's a 64-bit process).
                //

                uint [] zygote64Pids = m_portDevice.GetPidsFromName("zygote64");

                if (zygote64Pids.Length > 0)
                {
                    uint [] activeZygote64SpawnedPids = m_portDevice.GetChildPidsFromPpid(zygote64Pids [0]);

                    for (int i = 0; i < activeZygote64SpawnedPids.Length; ++i)
                    {
                        uint pid = activeZygote64SpawnedPids [i];

                        AndroidProcess nativeProcess = m_portDevice.GetProcessFromPid(pid);

                        m_portProcesses.Add(pid, new DebuggeeProcess(this, nativeProcess));
                    }
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #22
0
        public int Attach_V7(IDebugProgram2 pMDMProgram, IDebugEventCallback2 pCallback, uint dwReason)
        {
            LoggingUtils.PrintFunction();

            return(Constants.E_NOTIMPL);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int EnumCodePaths(string pszHint, IDebugCodeContext2 pStart, IDebugStackFrame2 pFrame, int fSource, out IEnumCodePaths2 ppEnum, out IDebugCodeContext2 ppSafety)
        {
            //
            // Enumerates the code paths of this program.
            //

            LoggingUtils.PrintFunction();

#if false
            try
            {
                //
                // Get the entire call-stack for the current thread, and enumerate.
                //

                CLangDebuggeeStackFrame stackFrame = pFrame as CLangDebuggeeStackFrame;

                IDebugThread2 thread;

                LoggingUtils.RequireOk(stackFrame.GetThread(out thread));

                CLangDebuggeeThread stackFrameThread = thread as CLangDebuggeeThread;

                List <DebuggeeStackFrame> threadCallStack = stackFrameThread.StackTrace(uint.MaxValue);

                List <CODE_PATH> threadCodePaths = new List <CODE_PATH> ();

                for (int i = 0; i < threadCallStack.Count; ++i)
                {
                    string frameName;

                    IDebugCodeContext2 codeContext;

                    DebuggeeStackFrame frame = threadCallStack [i] as DebuggeeStackFrame;

                    LoggingUtils.RequireOk(frame.GetName(out frameName));

                    LoggingUtils.RequireOk(frame.GetCodeContext(out codeContext));

                    if (codeContext != null)
                    {
                        CODE_PATH codePath = new CODE_PATH();

                        codePath.bstrName = frameName;

                        codePath.pCode = codeContext;

                        threadCodePaths.Add(codePath);
                    }
                }

                ppEnum = new DebuggeeProgram.EnumeratorCodePaths(threadCodePaths);

                ppSafety = null;

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);
#endif
            {
                ppEnum = null;

                ppSafety = null;

                return(Constants.E_FAIL);
            }
        }
Пример #24
0
        public int DetachDebugger_V7()
        {
            LoggingUtils.PrintFunction();

            return(Constants.E_NOTIMPL);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public void SetRunning(bool isRunning)
        {
            LoggingUtils.PrintFunction();

            IsRunning = isRunning;
        }
Пример #26
0
        /// <summary>
        /// Uploads the given armTemplate as a JSON file in blob storage and records the URI to the
        /// created resrouce in the db.
        /// </summary>
        /// <param name="offerName">The name of the offer.</param>
        /// <param name="templateName">The name of the ARM template.</param>
        /// <param name="armTemplateJSON">The ARM Template's raw JSON data.</param>
        /// <returns>The created armTemplate db record.</returns>
        public async Task <ArmTemplate> CreateAsync(string offerName, string templateName, object armTemplateJSON)
        {
            if (armTemplateJSON is null)
            {
                throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(typeof(ArmTemplate).Name),
                                                      UserErrorCode.PayloadNotProvided);
            }

            // Check that the offer does not already have an armTemplate with the same templateName
            if (await ExistsAsync(offerName, templateName))
            {
                throw new LunaConflictUserException(LoggingUtils.ComposeAlreadyExistsErrorMessage(typeof(ArmTemplate).Name,
                                                                                                  templateName,
                                                                                                  offerName: offerName));
            }

            // Get the offer associated with the offerName provided
            var offer = await _offerService.GetAsync(offerName);

            // Get the container name associated with the offer
            var containerName = offer.ContainerName.ToString();

            // Upload the armTemplateJSON as a file in blob storage and get the URL to the created resource
            var url = await uploadToBlobStorageAsync(containerName, GetArmTemplateFileName(templateName), armTemplateJSON.ToString());

            _logger.LogInformation($"Arm template {templateName} in offer {offerName} is uploaded to {url}.");

            // Create the armTemplate to store in db
            ArmTemplate armTemplate = new ArmTemplate {
                OfferId          = offer.Id,
                TemplateName     = templateName,
                TemplateFilePath = url
            };

            // Add armTemplate to db
            _context.ArmTemplates.Add(armTemplate);
            await _context._SaveChangesAsync();

            _logger.LogInformation(LoggingUtils.ComposeResourceCreatedMessage(typeof(ArmTemplate).Name, templateName, offerName: offerName));

            if (!await _armTemplateParameterService.ExistsAsync(offerName, "resourceGroupLocation"))
            {
                // Add parameter for resourceGroupLocation
                ArmTemplateParameter armParameter = new ArmTemplateParameter
                {
                    OfferId = offer.Id,
                    Name    = "resourceGroupLocation",
                    Type    = "string",
                    // TODO: do we need to indicate an incomplete parameter?
                    Value = string.Empty
                };

                await _armTemplateParameterService.CreateAsync(offerName, armTemplate.Id, armParameter);
            }

            if (!await _armTemplateParameterService.ExistsAsync(offerName, "entryPointUrl"))
            {
                // Add parameter for entryPointLink
                ArmTemplateParameter armParameter = new ArmTemplateParameter
                {
                    OfferId = offer.Id,
                    Name    = "entryPointUrl",
                    Type    = "string",
                    // TODO: do we need to indicate an incomplete parameter?
                    Value = string.Empty
                };

                await _armTemplateParameterService.CreateAsync(offerName, armTemplate.Id, armParameter);
            }

            // Add arm template parameters
            await CreateArmTemplateParameters(offer, armTemplateJSON, armTemplate.Id);

            return(armTemplate);
        }
Пример #27
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int GetThreadProperties(enum_THREADPROPERTY_FIELDS requestedFields, THREADPROPERTIES [] propertiesArray)
        {
            //
            // Gets properties that describe a thread.
            //

            LoggingUtils.PrintFunction();

            try
            {
                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0)
                {
                    propertiesArray [0].dwThreadId = m_threadId;

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
                }

                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0)
                {
                    propertiesArray [0].dwSuspendCount = m_threadSuspendCount;

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
                }

                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0)
                {
                    if (m_threadRunning)
                    {
                        propertiesArray [0].dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
                    }
                    else
                    {
                        propertiesArray [0].dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_STOPPED;
                    }

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
                }

                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0)
                {
                    propertiesArray [0].bstrPriority = "<unknown priority>";

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
                }

                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0)
                {
                    propertiesArray [0].bstrName = m_threadName;

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
                }

                if ((requestedFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0)
                {
                    //
                    // The thread location (usually the topmost stack frame), typically expressed as the name of the method where execution is currently halted.
                    //

                    propertiesArray [0].bstrLocation = "[External Code]";

                    StackTrace(1); // single level depth

                    if (m_threadStackFrames.Count > 0)
                    {
                        DebuggeeStackFrame stackFrame = m_threadStackFrames [0];

                        FRAMEINFO frameInfo = new FRAMEINFO();

                        LoggingUtils.RequireOk(stackFrame.SetFrameInfo(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME, 0, ref frameInfo));

                        if (!string.IsNullOrEmpty(frameInfo.m_bstrFuncName))
                        {
                            propertiesArray [0].bstrLocation = frameInfo.m_bstrFuncName;
                        }
                    }

                    propertiesArray [0].dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
                }

                return(Constants.S_OK);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
Пример #28
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        #region IDebugErrorBreakpointResolution2 Members

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int GetResolutionInfo(enum_BPERESI_FIELDS requestedFields, BP_ERROR_RESOLUTION_INFO [] resolutionInfo)
        {
            //
            // Gets the breakpoint resolution information.
            //

            LoggingUtils.PrintFunction();

            try
            {
                resolutionInfo [0] = new BP_ERROR_RESOLUTION_INFO();

                if ((requestedFields & enum_BPERESI_FIELDS.BPERESI_BPRESLOCATION) != 0)
                {
                    enum_BP_TYPE bpType;

                    GetBreakpointType(out bpType);

                    if (bpType == enum_BP_TYPE.BPT_CODE)
                    {
                        resolutionInfo [0].bpResLocation.bpType = (uint)bpType;

                        resolutionInfo [0].bpResLocation.unionmember1 = Marshal.GetComInterfaceForObject(m_codeContext, typeof(IDebugCodeContext2));
                    }
                    else if (bpType == enum_BP_TYPE.BPT_DATA)
                    {
                        resolutionInfo [0].bpResLocation.bpType = (uint)bpType;

                        throw new NotImplementedException();
                    }

                    resolutionInfo [0].dwFields |= enum_BPERESI_FIELDS.BPERESI_BPRESLOCATION;
                }

                if ((requestedFields & enum_BPERESI_FIELDS.BPERESI_PROGRAM) != 0)
                {
                    LoggingUtils.RequireOk(m_codeContext.GetProgram(out resolutionInfo [0].pProgram));

                    resolutionInfo [0].dwFields |= enum_BPERESI_FIELDS.BPERESI_PROGRAM;
                }

                if ((requestedFields & enum_BPERESI_FIELDS.BPERESI_THREAD) != 0)
                {
                }

                if ((requestedFields & enum_BPERESI_FIELDS.BPERESI_MESSAGE) != 0)
                {
                    resolutionInfo [0].bstrMessage = m_resolutionMessage;

                    resolutionInfo [0].dwFields |= enum_BPERESI_FIELDS.BPERESI_MESSAGE;
                }

                if ((requestedFields & enum_BPERESI_FIELDS.BPERESI_TYPE) != 0)
                {
                    resolutionInfo [0].dwType = enum_BP_ERROR_TYPE.BPET_GENERAL_WARNING;

                    resolutionInfo [0].dwFields |= enum_BPERESI_FIELDS.BPERESI_TYPE;
                }

                return(Constants.S_OK);
            }
            catch (NotImplementedException e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_NOTIMPL);
            }
            catch (Exception e)
            {
                LoggingUtils.HandleException(e);

                return(Constants.E_FAIL);
            }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
        {
            LoggingUtils.PrintFunction();

            return(VSConstants.S_OK);
        }
Пример #30
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public bool IsRegistered(ref Guid riidEvent)
        {
            LoggingUtils.PrintFunction();

            return(m_debuggerCallback.ContainsKey(riidEvent));
        }