Esempio n. 1
0
 public Task<TaskAgent> AddAgentAsync(Int32 agentPoolId, TaskAgent agent)
 {
     CheckConnection();
     return _taskAgentClient.AddAgentAsync(agentPoolId, agent);
 }
Esempio n. 2
0
        public async Task UnconfigureAsync(CommandSettings command)
        {
            ArgUtil.Equal(RunMode.Normal, HostContext.RunMode, nameof(HostContext.RunMode));
            string currentAction = string.Empty;

            try
            {
                //stop, uninstall service and remove service config file
                if (_store.IsServiceConfigured())
                {
                    currentAction = StringUtil.Loc("UninstallingService");
                    _term.WriteLine(currentAction);
#if OS_WINDOWS
                    var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>();
                    serviceControlManager.UnconfigureService();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
#elif OS_LINUX
                    // unconfig system D service first
                    throw new Exception(StringUtil.Loc("UnconfigureServiceDService"));
#elif OS_OSX
                    // unconfig osx service first
                    throw new Exception(StringUtil.Loc("UnconfigureOSXService"));
#endif
                }
                else
                {
#if OS_WINDOWS
                    //running as process, unconfigure autologon if it was configured
                    if (_store.IsAutoLogonConfigured())
                    {
                        currentAction = StringUtil.Loc("UnconfigAutologon");
                        _term.WriteLine(currentAction);
                        var autoLogonConfigManager = HostContext.GetService <IAutoLogonManager>();
                        autoLogonConfigManager.Unconfigure();
                        _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                    }
                    else
                    {
                        Trace.Info("AutoLogon was not configured on the agent.");
                    }
#endif
                }

                //delete agent from the server
                currentAction = StringUtil.Loc("UnregisteringAgent");
                _term.WriteLine(currentAction);
                bool isConfigured   = _store.IsConfigured();
                bool hasCredentials = _store.HasCredentials();
                if (isConfigured && hasCredentials)
                {
                    AgentSettings settings          = _store.GetSettings();
                    var           credentialManager = HostContext.GetService <ICredentialManager>();

                    // Get the credentials
                    var            credProvider = GetCredentialProvider(command, settings.ServerUrl);
                    VssCredentials creds        = credProvider.GetVssCredentials(HostContext);
                    Trace.Info("cred retrieved");

                    bool isDeploymentGroup = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0);

                    Trace.Info("Agent configured for deploymentGroup : {0}", isDeploymentGroup.ToString());

                    string agentType = isDeploymentGroup
                   ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration
                   : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration;

                    var extensionManager = HostContext.GetService <IExtensionManager>();
                    IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType);
                    ArgUtil.NotNull(agentProvider, agentType);

                    await agentProvider.TestConnectionAsync(settings, creds);

                    TaskAgent agent = await agentProvider.GetAgentAsync(settings);

                    if (agent == null)
                    {
                        _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                    }
                    else
                    {
                        await agentProvider.DeleteAgentAsync(settings);

                        _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                    }
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("MissingConfig"));
                }

                //delete credential config files
                currentAction = StringUtil.Loc("DeletingCredentials");
                _term.WriteLine(currentAction);
                if (hasCredentials)
                {
                    _store.DeleteCredential();
                    var keyManager = HostContext.GetService <IRSAKeyManager>();
                    keyManager.DeleteKey();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }

                //delete settings config file
                currentAction = StringUtil.Loc("DeletingSettings");
                _term.WriteLine(currentAction);
                if (isConfigured)
                {
                    // delete proxy setting
                    (HostContext.GetService <IVstsAgentWebProxy>() as VstsAgentWebProxy).DeleteProxySetting();

                    // delete agent cert setting
                    (HostContext.GetService <IAgentCertificateManager>() as AgentCertificateManager).DeleteCertificateSetting();

                    _store.DeleteSettings();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }
            }
            catch (Exception)
            {
                _term.WriteLine(StringUtil.Loc("Failed") + currentAction);
                throw;
            }
        }
Esempio n. 3
0
        //Shows the agent field in case an agent type is specified either with [AgentType] attribute or through the use of the generic versions of Action or Condition Task
        void ShowAgentField()
        {
            if (task.agentType == null)
            {
                return;
            }

            TaskAgent taskAgent = overrideAgentProp.value;

            if (Application.isPlaying && task.agentIsOverride && taskAgent.value == null)
            {
                GUI.color = Colors.lightRed;
                GUILayout.Label("<b>!Missing Agent Reference!</b>");
                GUI.color = Color.white;
                return;
            }


            var isMissingType = task.agent == null;
            var infoString    = isMissingType? "<color=#ff5f5f>" + task.agentType.FriendlyName() + "</color>": task.agentType.FriendlyName();

            GUI.color           = new Color(1f, 1f, 1f, task.agentIsOverride? 1f : 0.5f);
            GUI.backgroundColor = GUI.color;
            GUILayout.BeginVertical(task.agentIsOverride? "box" : "button");
            GUILayout.BeginHorizontal();


            if (task.agentIsOverride)
            {
                if (taskAgent.useBlackboard)
                {
                    GUI.color = new Color(0.9f, 0.9f, 1f, 1f);
                    var varNames = new List <string>();

                    //Local
                    if (taskAgent.bb != null)
                    {
                        varNames.AddRange(taskAgent.bb.GetVariableNames(typeof(GameObject)));
                        varNames.AddRange(taskAgent.bb.GetVariableNames(typeof(Component)));
                        if (task.agentType.IsInterface)
                        {
                            varNames.AddRange(taskAgent.bb.GetVariableNames(task.agentType));
                        }
                    }

                    //Globals
                    foreach (var globalBB in GlobalBlackboard.allGlobals)
                    {
                        varNames.Add(globalBB.name + "/");

                        var globalVars = new List <string>();
                        globalVars.AddRange(globalBB.GetVariableNames(typeof(GameObject)));
                        globalVars.AddRange(globalBB.GetVariableNames(typeof(Component)));
                        if (task.agentType.IsInterface)
                        {
                            globalVars.AddRange(globalBB.GetVariableNames(task.agentType));
                        }

                        for (var i = 0; i < globalVars.Count; i++)
                        {
                            globalVars[i] = globalBB.name + "/" + globalVars[i];
                        }

                        varNames.AddRange(globalVars);
                    }

                    //No Dynamic for AgentField for convenience and user error safety
                    varNames.Add("(DynamicVar)");


                    if (varNames.Contains(taskAgent.name) || string.IsNullOrEmpty(taskAgent.name))
                    {
                        taskAgent.name = EditorUtils.StringPopup(taskAgent.name, varNames, false, true);
                        if (taskAgent.name == "(DynamicVar)")
                        {
                            taskAgent.name = "_";
                        }
                    }
                    else
                    {
                        taskAgent.name = EditorGUILayout.TextField(taskAgent.name);
                    }
                }
                else
                {
                    taskAgent.value = EditorGUILayout.ObjectField(taskAgent.value, task.agentType, true) as Component;
                }
            }
            else
            {
                GUILayout.BeginHorizontal();
                var icon    = UserTypePrefs.GetTypeIcon(task.agentType);
                var label   = string.Format("Use Self ({0})", infoString);
                var content = new GUIContent(label, icon);
                GUILayout.Label(content, GUILayout.Height(16));
                GUILayout.EndHorizontal();
            }


            GUI.color = Color.white;

            if (task.agentIsOverride)
            {
                if (isMissingType)
                {
                    GUILayout.Label("(" + infoString + ")", GUILayout.Height(15));
                }
                taskAgent.useBlackboard = EditorGUILayout.Toggle(taskAgent.useBlackboard, EditorStyles.radioButton, GUILayout.Width(18));
            }

            GUI.color           = Color.white;
            GUI.backgroundColor = Color.white;

            if (!Application.isPlaying)
            {
                task.agentIsOverride = EditorGUILayout.Toggle(task.agentIsOverride, GUILayout.Width(18));
            }

            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
        }
        public async Task ConfigureAsync(CommandSettings command)
        {
            Trace.Info(nameof(ConfigureAsync));
            if (IsConfigured())
            {
                throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError"));
            }

            // TEE EULA
            bool acceptTeeEula = false;
            switch (Constants.Agent.Platform)
            {
                case Constants.OSPlatform.OSX:
                case Constants.OSPlatform.Linux:
                    // Write the section header.
                    WriteSection(StringUtil.Loc("EulasSectionHeader"));

                    // Verify the EULA exists on disk in the expected location.
                    string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
                    ArgUtil.File(eulaFile, nameof(eulaFile));

                    // Write elaborate verbiage about the TEE EULA.
                    _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile));
                    _term.WriteLine();

                    // Prompt to acccept the TEE EULA.
                    acceptTeeEula = command.GetAcceptTeeEula();
                    break;
                case Constants.OSPlatform.Windows:
                    break;
                default:
                    throw new NotSupportedException();
            }

            // TODO: Check if its running with elevated permission and stop early if its not

            // Loop getting url and creds until you can connect
            string serverUrl = null;
            ICredentialProvider credProvider = null;
            WriteSection(StringUtil.Loc("ConnectSectionHeader"));
            while (true)
            {
                // Get the URL
                serverUrl = command.GetUrl();

                // Get the credentials
                credProvider = GetCredentialProvider(command, serverUrl);
                VssCredentials creds = credProvider.GetVssCredentials(HostContext);
                Trace.Info("cred retrieved");
                try
                {
                    // Validate can connect.
                    await TestConnectAsync(serverUrl, creds);
                    Trace.Info("Connect complete.");
                    break;
                }
                catch (Exception e) when (!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError(StringUtil.Loc("FailedToConnect"));
                    // TODO: If the connection fails, shouldn't the URL/creds be cleared from the command line parser? Otherwise retry may be immediately attempted using the same values without prompting the user for new values. The same general problem applies to every retry loop during configure.
                }
            }

            // We want to use the native CSP of the platform for storage, so we use the RSACSP directly
            RSAParameters publicKey;
            var keyManager = HostContext.GetService<IRSAKeyManager>();
            using (var rsa = keyManager.CreateKey())
            {
                publicKey = rsa.ExportParameters(false);
            }

            // Loop getting agent name and pool
            string poolName = null;
            int poolId = 0;
            string agentName = null;
            WriteSection(StringUtil.Loc("RegisterAgentSectionHeader"));
            while (true)
            {
                poolName = command.GetPool();
                try
                {
                    poolId = await GetPoolId(poolName);
                }
                catch (Exception e) when (!command.Unattended)
                {
                    _term.WriteError(e);
                }

                if (poolId > 0)
                {
                    break;
                }

                _term.WriteError(StringUtil.Loc("FailedToFindPool"));
            }

            TaskAgent agent;
            while (true)
            {
                agentName = command.GetAgent();

                // Get the system capabilities.
                // TODO: Hook up to ctrl+c cancellation token.
                // TODO: LOC
                _term.WriteLine("Scanning for tool capabilities.");
                Dictionary<string, string> systemCapabilities = await HostContext.GetService<ICapabilitiesManager>().GetCapabilitiesAsync(
                    new AgentSettings { AgentName = agentName }, CancellationToken.None);

                // TODO: LOC
                _term.WriteLine("Connecting to the server.");
                agent = await GetAgent(agentName, poolId);
                if (agent != null)
                {
                    if (command.GetReplace())
                    {
                        agent.Authorization = new TaskAgentAuthorization
                        {
                            PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus),
                        };

                        // update - update instead of delete so we don't lose user capabilities etc...
                        agent.Version = Constants.Agent.Version;

                        foreach (KeyValuePair<string, string> capability in systemCapabilities)
                        {
                            agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                        }

                        try
                        {
                            agent = await _agentServer.UpdateAgentAsync(poolId, agent);
                            _term.WriteLine(StringUtil.Loc("AgentReplaced"));
                            break;
                        }
                        catch (Exception e) when (!command.Unattended)
                        {
                            _term.WriteError(e);
                            _term.WriteError(StringUtil.Loc("FailedToReplaceAgent"));
                        }
                    }
                    else
                    {
                        // TODO: ?
                    }
                }
                else
                {
                    agent = new TaskAgent(agentName)
                    {
                        Authorization = new TaskAgentAuthorization
                        {
                            PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus),
                        },
                        MaxParallelism = 1,
                        Version = Constants.Agent.Version
                    };

                    foreach (KeyValuePair<string, string> capability in systemCapabilities)
                    {
                        agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                    }

                    try
                    {
                        agent = await _agentServer.AddAgentAsync(poolId, agent);
                        _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully"));
                        break;
                    }
                    catch (Exception e) when (!command.Unattended)
                    {
                        _term.WriteError(e);
                        _term.WriteError(StringUtil.Loc("AddAgentFailed"));
                    }
                }
            }

            // See if the server supports our OAuth key exchange for credentials
            if (agent.Authorization != null &&
                agent.Authorization.ClientId != Guid.Empty &&
                agent.Authorization.AuthorizationUrl != null)
            {
                var credentialData = new CredentialData
                {
                    Scheme = Constants.Configuration.OAuth,
                    Data =
                    {
                        { "clientId", agent.Authorization.ClientId.ToString("D") },
                        { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri },
                    },
                };

                // Save the negotiated OAuth credential data
                _store.SaveCredential(credentialData);
            }
            else
            {
                // Save the provided admin credential data for compat with existing agent
                _store.SaveCredential(credProvider.CredentialData);
            }

            // We will Combine() what's stored with root.  Defaults to string a relative path
            string workFolder = command.GetWork();
            string notificationPipeName = command.GetNotificationPipeName();

            // Get Agent settings
            var settings = new AgentSettings
            {
                AcceptTeeEula = acceptTeeEula,
                AgentId = agent.Id,
                AgentName = agentName,
                NotificationPipeName = notificationPipeName,
                PoolId = poolId,
                PoolName = poolName,
                ServerUrl = serverUrl,
                WorkFolder = workFolder,
            };

            _store.SaveSettings(settings);
            _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow));

            bool runAsService = false;

            if (Constants.Agent.Platform == Constants.OSPlatform.Windows)
            {
                runAsService = command.GetRunAsService();
            }

            var serviceControlManager = HostContext.GetService<IServiceControlManager>();
            serviceControlManager.GenerateScripts(settings);

            bool successfullyConfigured = false;
            if (runAsService)
            {
                Trace.Info("Configuring to run the agent as service");
                successfullyConfigured = serviceControlManager.ConfigureService(settings, command);
            }

            if (runAsService && successfullyConfigured)
            {
                Trace.Info("Configuration was successful, trying to start the service");
                serviceControlManager.StartService();
            }
        }
Esempio n. 5
0
        public override async Task <TaskAgent> AddAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
        {
            ArgUtil.NotNull(agentSettings, nameof(agentSettings));
            ArgUtil.NotNull(agent, nameof(agent));
            ArgUtil.NotNull(command, nameof(command));
            var virtualMachine = new VirtualMachineResource()
            {
                Name = agent.Name, Agent = agent
            };
            var tags = GetVirtualMachineResourceTags(command);

            virtualMachine.Tags = tags;

            virtualMachine = await _environmentsServer.AddEnvironmentVMAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId, virtualMachine);

            Trace.Info("Environment virtual machine resource with name: '{0}', id: '{1}' has been added successfully.", virtualMachine.Name, virtualMachine.Id);

            var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId);

            Trace.Info("environment pool id: '{0}'", pool.Id);
            agentSettings.PoolId    = pool.Id;
            agentSettings.AgentName = virtualMachine.Name;
            agentSettings.EnvironmentVMResourceId = virtualMachine.Id;

            return(virtualMachine.Agent);
        }
Esempio n. 6
0
 public Task <TaskAgent> UpdateAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
 {
     ArgUtil.NotNull(agentSettings, nameof(agentSettings));
     return(_agentServer.UpdateAgentAsync(agentSettings.PoolId, agent));
 }
Esempio n. 7
0
        public ConfigurationManagerL0()
        {
            _agentServer        = new Mock <IAgentServer>();
            _locationServer     = new Mock <ILocationServer>();
            _credMgr            = new Mock <ICredentialManager>();
            _promptManager      = new Mock <IPromptManager>();
            _store              = new Mock <IConfigurationStore>();
            _extnMgr            = new Mock <IExtensionManager>();
            _rsaKeyManager      = new Mock <IRSAKeyManager>();
            _machineGroupServer = new Mock <IDeploymentGroupServer>();
            _environmentsServer = new Mock <IEnvironmentsServer>();
            _vstsAgentWebProxy  = new Mock <IVstsAgentWebProxy>();
            _cert = new Mock <IAgentCertificateManager>();

#if OS_WINDOWS
            _serviceControlManager = new Mock <IWindowsServiceControlManager>();
#endif

#if !OS_WINDOWS
            _serviceControlManager = new Mock <ILinuxServiceControlManager>();
#endif

            _capabilitiesManager = new CapabilitiesManager();

            var expectedAgent = new TaskAgent(_expectedAgentName)
            {
                Id = 1
            };
            var expectedDeploymentMachine = new DeploymentMachine()
            {
                Agent = expectedAgent, Id = _expectedDeploymentMachineId
            };
            expectedAgent.Authorization = new TaskAgentAuthorization
            {
                ClientId         = Guid.NewGuid(),
                AuthorizationUrl = new Uri("http://localhost:8080/tfs"),
            };

            var connectionData = new ConnectionData()
            {
                InstanceId     = Guid.NewGuid(),
                DeploymentType = DeploymentFlags.Hosted,
                DeploymentId   = Guid.NewGuid()
            };
            _agentServer.Setup(x => x.ConnectAsync(It.IsAny <Uri>(), It.IsAny <VssCredentials>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.GetConnectionDataAsync()).Returns(Task.FromResult <ConnectionData>(connectionData));
            _machineGroupServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _machineGroupServer.Setup(x => x.UpdateDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <List <DeploymentMachine> >()));
            _machineGroupServer.Setup(x => x.AddDeploymentTargetAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
            _machineGroupServer.Setup(x => x.ReplaceDeploymentTargetAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <DeploymentMachine>())).Returns(Task.FromResult(expectedDeploymentMachine));
            _machineGroupServer.Setup(x => x.GetDeploymentTargetsAsync(It.IsAny <Guid>(), It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(new List <DeploymentMachine>()
            {
            }));
            _machineGroupServer.Setup(x => x.DeleteDeploymentTargetAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult <object>(null));

            _store.Setup(x => x.IsConfigured()).Returns(false);
            _store.Setup(x => x.HasCredentials()).Returns(false);
            _store.Setup(x => x.GetSettings()).Returns(() => _configMgrAgentSettings);

            _store.Setup(x => x.SaveSettings(It.IsAny <AgentSettings>()))
            .Callback((AgentSettings settings) =>
            {
                _configMgrAgentSettings = settings;
            });

            _credMgr.Setup(x => x.GetCredentialProvider(It.IsAny <string>())).Returns(new TestAgentCredential());

#if !OS_WINDOWS
            _serviceControlManager.Setup(x => x.GenerateScripts(It.IsAny <AgentSettings>()));
#endif

            var expectedPools = new List <TaskAgentPool>()
            {
                new TaskAgentPool(_expectedPoolName)
                {
                    Id = _expectedPoolId
                }
            };
            _agentServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny <string>(), It.IsAny <TaskAgentPoolType>())).Returns(Task.FromResult(expectedPools));

            var expectedAgents = new List <TaskAgent>();
            _agentServer.Setup(x => x.GetAgentsAsync(It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(expectedAgents));

            _agentServer.Setup(x => x.AddAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));
            _agentServer.Setup(x => x.UpdateAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));

            rsa = new RSACryptoServiceProvider(2048);

            _rsaKeyManager.Setup(x => x.CreateKey()).Returns(rsa);
        }
Esempio n. 8
0
        public virtual async Task <TaskAgent> UpdateAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
        {
            ArgUtil.NotNull(agentSettings, nameof(agentSettings));
            ArgUtil.NotNull(command, nameof(command));
            var deploymentMachine = (await this.GetDeploymentTargetsAsync(agentSettings)).FirstOrDefault();

            deploymentMachine.Agent = agent;
            deploymentMachine       = await _deploymentGroupServer.ReplaceDeploymentTargetAsync(new Guid(agentSettings.ProjectId), agentSettings.DeploymentGroupId, deploymentMachine.Id, deploymentMachine);

            await GetAndAddTags(deploymentMachine, agentSettings, command);

            return(deploymentMachine.Agent);
        }
Esempio n. 9
0
    IEnumerator AutoSpinCards()
    {
        int yesterdayTicket = Save.data.allData.award_ranking.ysterday_tickets;

        yield return(new WaitForSeconds(1));

        if (yesterdayTicket >= Save.data.allData.award_ranking.ticktes_flag)
        {
            Vector3 flyEndPos      = fly_targetRect.position;
            Vector3 startPos       = yesterday_ticket_numText.transform.position;
            int     cardCount      = all_fly_cards.Count;
            int     startCardIndex = 0;
            int     endCardIndex   = 0;
            float   flyInterval    = 0.3f;
            float   flyTimer       = 0;
            float   nextFlyTime    = 0;
            while (endCardIndex < cardCount)
            {
                flyTimer += Time.deltaTime;
                yesterday_ticket_numText.text = ((int)(yesterdayTicket * Mathf.Clamp(((1.8f - flyTimer) / 1.8f), 0, 1))).GetTokenShowString();
                if (flyTimer >= nextFlyTime)
                {
                    startCardIndex++;
                    if (startCardIndex > cardCount)
                    {
                        startCardIndex = cardCount;
                    }
                    nextFlyTime += flyInterval;
                }
                for (int i = endCardIndex; i < startCardIndex; i++)
                {
                    all_fly_cards[i].Rotate(new Vector3(0, 0, Time.deltaTime * 100));
                    float progress = Mathf.Clamp(flyTimer - flyInterval * i, 0, 1);
                    all_fly_cards[i].transform.position = Vector3.Lerp(startPos, flyEndPos, progress);
                    if (progress == 1)
                    {
                        all_fly_cards[i].gameObject.SetActive(false);
                        Audio.PlayOneShot(AudioPlayArea.FlyOver);
                        endCardIndex++;
                    }
                }
                yield return(null);
            }
        }
        float timer        = 0;
        float spinTime     = 2;
        bool  hasBack      = false;
        float forwardSpeed = 0;
        float backSpeed    = 0.015f;
        float backTimer    = 0;

        float maxSpeed = 6000;

        all_card_rootRect.localPosition = new Vector3(0, all_card_rootRect.localPosition.y);
        while (true)
        {
            yield return(null);

            timer += Time.deltaTime;
            if (timer < spinTime)
            {
                forwardSpeed += 50;
                if (forwardSpeed > maxSpeed)
                {
                    forwardSpeed = maxSpeed;
                }
                all_card_rootRect.localPosition += new Vector3(-Time.deltaTime * forwardSpeed, 0);
                if (all_card_rootRect.localPosition.x <= endPosOffset.x)
                {
                    all_card_rootRect.localPosition -= 2 * endPosOffset;
                }
            }
            else
            {
                if (!hasBack)
                {
                    backSpeed -= 0.0005f;
                    backTimer += backSpeed;
                    all_card_rootRect.localPosition = new Vector3(endPosOffset.x * (1 + backTimer), endPos.y);
                    if (backSpeed <= 0)
                    {
                        hasBack = true;
                    }
                }
                else
                {
                    backSpeed -= 0.002f;
                    backTimer += backSpeed;
                    all_card_rootRect.localPosition = new Vector3(endPosOffset.x * (1 + backTimer), endPos.y);
                    if (backTimer <= 0)
                    {
                        all_card_rootRect.localPosition = endPos;
                        break;
                    }
                }
            }
        }
        tipText.text = "More tickets you have, more chance to win!";
        get_button_contentText.text = "TRY YOUR LUCK";
        List <AllData_BettingWinnerData_Winner> bettingWinners = Save.data.allData.award_ranking.ranking;
        string selfId = Save.data.allData.user_panel.user_id;
        AllData_BettingWinnerData_Winner willShow = bettingWinners[0];

        foreach (var winner in bettingWinners)
        {
            if (winner.user_id.Equals(selfId))
            {
                willShow     = winner;
                tipText.text = "Congratulations on winning the prize!!";
                get_button_contentText.text = "TAKE YOUR MONEY!";
                TaskAgent.TriggerTaskEvent(PlayerTaskTarget.WinnerOnce, 1);
                break;
            }
        }
        single_card_item.Init(willShow.user_title, willShow.user_id, willShow.user_num);
        yield return(new WaitForSeconds(1));

        getButton.gameObject.SetActive(true);
    }
        public ConfigurationManagerL0()
        {
            _agentServer        = new Mock <IAgentServer>();
            _credMgr            = new Mock <ICredentialManager>();
            _promptManager      = new Mock <IPromptManager>();
            _store              = new Mock <IConfigurationStore>();
            _extnMgr            = new Mock <IExtensionManager>();
            _rsaKeyManager      = new Mock <IRSAKeyManager>();
            _machineGroupServer = new Mock <IMachineGroupServer>();
            _netFrameworkUtil   = new Mock <INetFrameworkUtil>();

#if OS_WINDOWS
            _serviceControlManager = new Mock <IWindowsServiceControlManager>();
#endif

#if !OS_WINDOWS
            _serviceControlManager = new Mock <ILinuxServiceControlManager>();
#endif

#if !OS_WINDOWS
            string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
            Directory.CreateDirectory(IOUtil.GetExternalsPath());
            Directory.CreateDirectory(Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory));
            File.WriteAllText(eulaFile, "testeulafile");
#endif

            _capabilitiesManager = new CapabilitiesManager();

            _agentServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _machineGroupServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _machineGroupServer.Setup(
                x =>
                x.UpdateDeploymentMachineGroupAsync(It.IsAny <string>(), It.IsAny <int>(),
                                                    It.IsAny <List <DeploymentMachine> >()));
            _netFrameworkUtil.Setup(x => x.Test(It.IsAny <Version>())).Returns(true);

            _store.Setup(x => x.IsConfigured()).Returns(false);
            _store.Setup(x => x.HasCredentials()).Returns(false);
            _store.Setup(x => x.GetSettings()).Returns(() => _configMgrAgentSettings);

            _store.Setup(x => x.SaveSettings(It.IsAny <AgentSettings>()))
            .Callback((AgentSettings settings) =>
            {
                _configMgrAgentSettings = settings;
            });

            _credMgr.Setup(x => x.GetCredentialProvider(It.IsAny <string>())).Returns(new TestAgentCredential());

#if !OS_WINDOWS
            _serviceControlManager.Setup(x => x.GenerateScripts(It.IsAny <AgentSettings>()));
#endif

            var expectedPools = new List <TaskAgentPool>()
            {
                new TaskAgentPool(_expectedPoolName)
                {
                    Id = _expectedPoolId
                }
            };
            _agentServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny <string>())).Returns(Task.FromResult(expectedPools));

            var expectedAgents = new List <TaskAgent>();
            _agentServer.Setup(x => x.GetAgentsAsync(It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(expectedAgents));

            var expectedAgent = new TaskAgent(_expectedAgentName)
            {
                Id = 1
            };
            _agentServer.Setup(x => x.AddAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));
            _agentServer.Setup(x => x.UpdateAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));

            rsa         = RSA.Create();
            rsa.KeySize = 2048;

            _rsaKeyManager.Setup(x => x.CreateKey()).Returns(rsa);
        }
Esempio n. 11
0
        public async Task UnconfigureAsync(CommandSettings command)
        {
            string currentAction = StringUtil.Loc("UninstallingService");

            try
            {
                //stop, uninstall service and remove service config file
                _term.WriteLine(currentAction);
                if (_store.IsServiceConfigured())
                {
#if OS_WINDOWS
                    if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        Trace.Error("Needs Administrator privileges for unconfigure windows service agent.");
                        throw new SecurityException(StringUtil.Loc("NeedAdminForUnconfigWinServiceAgent"));
                    }

                    var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>();
                    serviceControlManager.UnconfigureService();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
#elif OS_LINUX
                    // unconfig system D service first
                    throw new Exception(StringUtil.Loc("UnconfigureServiceDService"));
#elif OS_OSX
                    // unconfig osx service first
                    throw new Exception(StringUtil.Loc("UnconfigureOSXService"));
#endif
                }

                //delete agent from the server
                currentAction = StringUtil.Loc("UnregisteringAgent");
                _term.WriteLine(currentAction);
                bool isConfigured   = _store.IsConfigured();
                bool hasCredentials = _store.HasCredentials();
                if (isConfigured && hasCredentials)
                {
                    AgentSettings settings          = _store.GetSettings();
                    var           credentialManager = HostContext.GetService <ICredentialManager>();

                    // Get the credentials
                    var            credProvider = GetCredentialProvider(command, settings.ServerUrl);
                    VssCredentials creds        = credProvider.GetVssCredentials(HostContext);
                    Trace.Info("cred retrieved");

                    bool isDeploymentGroup = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0);

                    Trace.Info("Agent configured for deploymentGroup : {0}", isDeploymentGroup.ToString());

                    string agentType = isDeploymentGroup
                   ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration
                   : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration;

                    var extensionManager = HostContext.GetService <IExtensionManager>();
                    IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType);
                    ArgUtil.NotNull(agentProvider, agentType);

                    await agentProvider.TestConnectionAsync(settings, creds);

                    TaskAgent agent = await agentProvider.GetAgentAsync(settings);

                    if (agent == null)
                    {
                        _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                    }
                    else
                    {
                        await agentProvider.DeleteAgentAsync(settings);

                        _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                    }
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("MissingConfig"));
                }

                //delete credential config files
                currentAction = StringUtil.Loc("DeletingCredentials");
                _term.WriteLine(currentAction);
                if (hasCredentials)
                {
                    _store.DeleteCredential();
                    var keyManager = HostContext.GetService <IRSAKeyManager>();
                    keyManager.DeleteKey();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }

                //delete settings config file
                currentAction = StringUtil.Loc("DeletingSettings");
                _term.WriteLine(currentAction);
                if (isConfigured)
                {
                    _store.DeleteSettings();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }
            }
            catch (Exception)
            {
                _term.WriteLine(StringUtil.Loc("Failed") + currentAction);
                throw;
            }
        }
        public void CanEnsureConfigure()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                trace.Info("Preparing command line arguments");
                var command = new CommandSettings(
                    tc,
                    new[]
                    {
                        "configure",
                        "--url", _expectedServerUrl, 
                        "--agent", _expectedAgentName, 
                        "--pool", _expectedPoolName,  
                        "--work", _expectedWorkFolder,
                        "--auth", _expectedAuthType,
                        "--token", _expectedToken
                    });
                trace.Info("Constructed.");
                
                var expectedPools = new List<TaskAgentPool>() { new TaskAgentPool(_expectedPoolName) { Id = 1 } };
                _agentServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny<string>())).Returns(Task.FromResult(expectedPools));
                
                var expectedAgents = new List<TaskAgent>();
                _agentServer.Setup(x => x.GetAgentsAsync(It.IsAny<int>(), It.IsAny<string>())).Returns(Task.FromResult(expectedAgents));
                
                var expectedAgent = new TaskAgent(_expectedAgentName) { Id = 1 };
                _agentServer.Setup(x => x.AddAgentAsync(It.IsAny<int>(), It.IsAny<TaskAgent>())).Returns(Task.FromResult(expectedAgent));
                _agentServer.Setup(x => x.UpdateAgentAsync(It.IsAny<int>(), It.IsAny<TaskAgent>())).Returns(Task.FromResult(expectedAgent));
                
                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);
                
                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.True(s.ServerUrl.Equals(_expectedServerUrl));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolName.Equals(_expectedPoolName));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
            }
        }
Esempio n. 13
0
 public Task<TaskAgent> UpdateAgentAsync(int agentPoolId, TaskAgent agent)
 {
     CheckConnection();
     return _taskAgentClient.ReplaceAgentAsync(agentPoolId, agent);
 }
Esempio n. 14
0
 public Task <TaskAgent> AddAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
 {
     return(_agentServer.AddAgentAsync(agentSettings.PoolId, agent));
 }
        public ConfigurationManagerL0()
        {
            _runnerServer   = new Mock <IRunnerServer>();
            _locationServer = new Mock <ILocationServer>();
            _credMgr        = new Mock <ICredentialManager>();
            _promptManager  = new Mock <IPromptManager>();
            _store          = new Mock <IConfigurationStore>();
            _extnMgr        = new Mock <IExtensionManager>();
            _rsaKeyManager  = new Mock <IRSAKeyManager>();

#if OS_WINDOWS
            _serviceControlManager = new Mock <IWindowsServiceControlManager>();
#endif

#if !OS_WINDOWS
            _serviceControlManager = new Mock <ILinuxServiceControlManager>();
#endif

            var expectedAgent = new TaskAgent(_expectedAgentName)
            {
                Id = 1
            };
            expectedAgent.Authorization = new TaskAgentAuthorization
            {
                ClientId         = Guid.NewGuid(),
                AuthorizationUrl = new Uri("http://localhost:8080/pipelines"),
            };

            var connectionData = new ConnectionData()
            {
                InstanceId     = Guid.NewGuid(),
                DeploymentType = DeploymentFlags.Hosted,
                DeploymentId   = Guid.NewGuid()
            };
            _runnerServer.Setup(x => x.ConnectAsync(It.IsAny <Uri>(), It.IsAny <VssCredentials>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.ConnectAsync(It.IsAny <VssConnection>())).Returns(Task.FromResult <object>(null));
            _locationServer.Setup(x => x.GetConnectionDataAsync()).Returns(Task.FromResult <ConnectionData>(connectionData));

            _store.Setup(x => x.IsConfigured()).Returns(false);
            _store.Setup(x => x.HasCredentials()).Returns(false);
            _store.Setup(x => x.GetSettings()).Returns(() => _configMgrAgentSettings);

            _store.Setup(x => x.SaveSettings(It.IsAny <RunnerSettings>()))
            .Callback((RunnerSettings settings) =>
            {
                _configMgrAgentSettings = settings;
            });

            _credMgr.Setup(x => x.GetCredentialProvider(It.IsAny <string>())).Returns(new TestRunnerCredential());

#if !OS_WINDOWS
            _serviceControlManager.Setup(x => x.GenerateScripts(It.IsAny <RunnerSettings>()));
#endif

            var expectedPools = new List <TaskAgentPool>()
            {
                new TaskAgentPool(_expectedPoolName)
                {
                    Id = _expectedPoolId
                }
            };
            _runnerServer.Setup(x => x.GetAgentPoolsAsync(It.IsAny <string>(), It.IsAny <TaskAgentPoolType>())).Returns(Task.FromResult(expectedPools));

            var expectedAgents = new List <TaskAgent>();
            _runnerServer.Setup(x => x.GetAgentsAsync(It.IsAny <int>(), It.IsAny <string>())).Returns(Task.FromResult(expectedAgents));

            _runnerServer.Setup(x => x.AddAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));
            _runnerServer.Setup(x => x.ReplaceAgentAsync(It.IsAny <int>(), It.IsAny <TaskAgent>())).Returns(Task.FromResult(expectedAgent));

            rsa = new RSACryptoServiceProvider(2048);

            _rsaKeyManager.Setup(x => x.CreateKey()).Returns(rsa);
        }
Esempio n. 16
0
        public async Task UnconfigureAsync(CommandSettings command)
        {
            string currentAction = string.Empty;

            _term.WriteSection("Runner removal");

            try
            {
                //stop, uninstall service and remove service config file
                if (_store.IsServiceConfigured())
                {
                    currentAction = "Removing service";
                    _term.WriteLine(currentAction);
#if OS_WINDOWS
                    var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>();
                    serviceControlManager.UnconfigureService();

                    _term.WriteLine();
                    _term.WriteSuccessMessage("Runner service removed");
#elif OS_LINUX
                    // unconfig system D service first
                    throw new Exception("Unconfigure service first");
#elif OS_OSX
                    // unconfig osx service first
                    throw new Exception("Unconfigure service first");
#endif
                }

                //delete agent from the server
                currentAction = "Removing runner from the server";
                bool isConfigured   = _store.IsConfigured();
                bool hasCredentials = _store.HasCredentials();
                if (isConfigured && hasCredentials)
                {
                    RunnerSettings settings          = _store.GetSettings();
                    var            credentialManager = HostContext.GetService <ICredentialManager>();

                    // Get the credentials
                    VssCredentials creds = null;
                    if (string.IsNullOrEmpty(settings.GitHubUrl))
                    {
                        var credProvider = GetCredentialProvider(command, settings.ServerUrl);
                        creds = credProvider.GetVssCredentials(HostContext);
                        Trace.Info("legacy vss cred retrieved");
                    }
                    else
                    {
                        var githubToken             = command.GetRunnerDeletionToken();
                        GitHubAuthResult authResult = await GetTenantCredential(settings.GitHubUrl, githubToken, Constants.RunnerEvent.Remove);

                        creds = authResult.ToVssCredentials();
                        Trace.Info("cred retrieved via GitHub auth");
                    }

                    // Determine the service deployment type based on connection data. (Hosted/OnPremises)
                    await _runnerServer.ConnectAsync(new Uri(settings.ServerUrl), creds);

                    var agents = await _runnerServer.GetAgentsAsync(settings.PoolId, settings.AgentName);

                    Trace.Verbose("Returns {0} agents", agents.Count);
                    TaskAgent agent = agents.FirstOrDefault();
                    if (agent == null)
                    {
                        _term.WriteLine("Does not exist. Skipping " + currentAction);
                    }
                    else
                    {
                        await _runnerServer.DeleteAgentAsync(settings.PoolId, settings.AgentId);

                        _term.WriteLine();
                        _term.WriteSuccessMessage("Runner removed successfully");
                    }
                }
                else
                {
                    _term.WriteLine("Cannot connect to server, because config files are missing. Skipping removing runner from the server.");
                }

                //delete credential config files
                currentAction = "Removing .credentials";
                if (hasCredentials)
                {
                    _store.DeleteCredential();
                    var keyManager = HostContext.GetService <IRSAKeyManager>();
                    keyManager.DeleteKey();
                    _term.WriteSuccessMessage("Removed .credentials");
                }
                else
                {
                    _term.WriteLine("Does not exist. Skipping " + currentAction);
                }

                //delete settings config file
                currentAction = "Removing .runner";
                if (isConfigured)
                {
                    _store.DeleteSettings();
                    _term.WriteSuccessMessage("Removed .runner");
                }
                else
                {
                    _term.WriteLine("Does not exist. Skipping " + currentAction);
                }
            }
            catch (Exception)
            {
                _term.WriteError("Failed: " + currentAction);
                throw;
            }

            _term.WriteLine();
        }
Esempio n. 17
0
 public Task <TaskAgent> UpdateAgentAsync(int poolId, TaskAgent agent)
 {
     return(_agentServer.UpdateAgentAsync(poolId, agent));
 }
Esempio n. 18
0
        public virtual async Task <TaskAgent> AddAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
        {
            ArgUtil.NotNull(agentSettings, nameof(agentSettings));
            ArgUtil.NotNull(command, nameof(command));
            var deploymentMachine = new DeploymentMachine()
            {
                Agent = agent
            };
            var azureSubscriptionId = await GetAzureSubscriptionIdAsync();

            if (!String.IsNullOrEmpty(azureSubscriptionId))
            {
                deploymentMachine.Properties.Add("AzureSubscriptionId", azureSubscriptionId);
            }
            deploymentMachine = await _deploymentGroupServer.AddDeploymentTargetAsync(new Guid(agentSettings.ProjectId), agentSettings.DeploymentGroupId, deploymentMachine);

            await GetAndAddTags(deploymentMachine, agentSettings, command);

            return(deploymentMachine.Agent);
        }
Esempio n. 19
0
 public Task <TaskAgent> AddAgentAsync(int poolId, TaskAgent agent)
 {
     return(_agentServer.AddAgentAsync(poolId, agent));
 }
Esempio n. 20
0
        public override async Task <TaskAgent> UpdateAgentAsync(AgentSettings agentSettings, TaskAgent agent, CommandSettings command)
        {
            ArgUtil.NotNull(agentSettings, nameof(agentSettings));
            ArgUtil.NotNull(command, nameof(command));
            var tags = GetVirtualMachineResourceTags(command);

            var vmResource = (await GetEnvironmentVMsAsync(agentSettings)).FirstOrDefault();

            vmResource.Agent = agent;
            vmResource.Tags  = tags;
            Trace.Info("Replacing environment virtual machine resource with id: '{0}'", vmResource.Id);
            vmResource = await _environmentsServer.ReplaceEnvironmentVMAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId, vmResource);

            Trace.Info("environment virtual machine resource with id: '{0}' has been replaced successfully", vmResource.Id);
            var pool = await _environmentsServer.GetEnvironmentPoolAsync(new Guid(agentSettings.ProjectId), agentSettings.EnvironmentId);

            agentSettings.AgentName = vmResource.Name;
            agentSettings.EnvironmentVMResourceId = vmResource.Id;
            agentSettings.PoolId = pool.Id;

            return(vmResource.Agent);
        }
        public async Task ConfigureAsync(CommandSettings command)
        {
            Trace.Info(nameof(ConfigureAsync));
            if (IsConfigured())
            {
                throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError"));
            }

            // TEE EULA
            bool acceptTeeEula = false;

            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.OSX:
            case Constants.OSPlatform.Linux:
                // Write the section header.
                WriteSection(StringUtil.Loc("EulasSectionHeader"));

                // Verify the EULA exists on disk in the expected location.
                string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
                ArgUtil.File(eulaFile, nameof(eulaFile));

                // Write elaborate verbiage about the TEE EULA.
                _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile));
                _term.WriteLine();

                // Prompt to acccept the TEE EULA.
                acceptTeeEula = command.GetAcceptTeeEula();
                break;

            case Constants.OSPlatform.Windows:
                break;

            default:
                throw new NotSupportedException();
            }

            // TODO: Check if its running with elevated permission and stop early if its not

            // Loop getting url and creds until you can connect
            string serverUrl = null;
            ICredentialProvider credProvider = null;

            WriteSection(StringUtil.Loc("ConnectSectionHeader"));
            while (true)
            {
                // Get the URL
                serverUrl = command.GetUrl();

                // Get the credentials
                credProvider = GetCredentialProvider(command, serverUrl);
                VssCredentials creds = credProvider.GetVssCredentials(HostContext);
                Trace.Info("cred retrieved");
                try
                {
                    // Validate can connect.
                    await TestConnectAsync(serverUrl, creds);

                    Trace.Info("Connect complete.");
                    break;
                }
                catch (Exception e) when(!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError(StringUtil.Loc("FailedToConnect"));
                    // TODO: If the connection fails, shouldn't the URL/creds be cleared from the command line parser? Otherwise retry may be immediately attempted using the same values without prompting the user for new values. The same general problem applies to every retry loop during configure.
                }
            }

            _term.WriteLine(StringUtil.Loc("SavingCredential"));
            Trace.Verbose("Saving credential");
            _store.SaveCredential(credProvider.CredentialData);

            // Loop getting agent name and pool
            string poolName  = null;
            int    poolId    = 0;
            string agentName = null;

            WriteSection(StringUtil.Loc("RegisterAgentSectionHeader"));
            while (true)
            {
                poolName = command.GetPool();
                try
                {
                    poolId = await GetPoolId(poolName);
                }
                catch (Exception e) when(!command.Unattended)
                {
                    _term.WriteError(e);
                }

                if (poolId > 0)
                {
                    break;
                }

                _term.WriteError(StringUtil.Loc("FailedToFindPool"));
            }

            TaskAgent agent;

            while (true)
            {
                agentName = command.GetAgent();

                // Get the system capabilities.
                // TODO: Hook up to ctrl+c cancellation token.
                // TODO: LOC
                _term.WriteLine("Scanning for tool capabilities.");
                Dictionary <string, string> systemCapabilities = await HostContext.GetService <ICapabilitiesManager>().GetCapabilitiesAsync(
                    new AgentSettings {
                    AgentName = agentName
                }, CancellationToken.None);

                // TODO: LOC
                _term.WriteLine("Connecting to the server.");
                agent = await GetAgent(agentName, poolId);

                if (agent != null)
                {
                    if (command.GetReplace())
                    {
                        // update - update instead of delete so we don't lose user capabilities etc...
                        agent.Version = Constants.Agent.Version;

                        foreach (KeyValuePair <string, string> capability in systemCapabilities)
                        {
                            agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                        }

                        try
                        {
                            agent = await _agentServer.UpdateAgentAsync(poolId, agent);

                            _term.WriteLine(StringUtil.Loc("AgentReplaced"));
                            break;
                        }
                        catch (Exception e) when(!command.Unattended)
                        {
                            _term.WriteError(e);
                            _term.WriteError(StringUtil.Loc("FailedToReplaceAgent"));
                        }
                    }
                    else
                    {
                        // TODO: ?
                    }
                }
                else
                {
                    agent = new TaskAgent(agentName)
                    {
                        MaxParallelism = 1,
                        Version        = Constants.Agent.Version
                    };

                    foreach (KeyValuePair <string, string> capability in systemCapabilities)
                    {
                        agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty;
                    }

                    try
                    {
                        agent = await _agentServer.AddAgentAsync(poolId, agent);

                        _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully"));
                        break;
                    }
                    catch (Exception e) when(!command.Unattended)
                    {
                        _term.WriteError(e);
                        _term.WriteError(StringUtil.Loc("AddAgentFailed"));
                    }
                }
            }

            // We will Combine() what's stored with root.  Defaults to string a relative path
            string workFolder = command.GetWork();

            // Get Agent settings
            var settings = new AgentSettings
            {
                AcceptTeeEula = acceptTeeEula,
                AgentId       = agent.Id,
                ServerUrl     = serverUrl,
                AgentName     = agentName,
                PoolName      = poolName,
                PoolId        = poolId,
                WorkFolder    = workFolder,
            };

            _store.SaveSettings(settings);
            _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow));

            bool runAsService           = command.GetRunAsService();
            var  serviceControlManager  = HostContext.GetService <IServiceControlManager>();
            bool successfullyConfigured = false;

            if (runAsService)
            {
                Trace.Info("Configuring to run the agent as service");
                successfullyConfigured = serviceControlManager.ConfigureService(settings, command);
            }

            // chown/chmod the _diag and settings files to the current user, if we started with sudo.
            // Also if we started with sudo, the _diag will be owned by root. Change this to current login user
            if (Constants.Agent.Platform == Constants.OSPlatform.Linux ||
                Constants.Agent.Platform == Constants.OSPlatform.OSX)
            {
                string uidValue = Environment.GetEnvironmentVariable("SUDO_UID");
                string gidValue = Environment.GetEnvironmentVariable("SUDO_GID");

                if (!string.IsNullOrEmpty(uidValue) && !string.IsNullOrEmpty(gidValue))
                {
                    var filesToChange = new Dictionary <string, string>
                    {
                        { IOUtil.GetDiagPath(), "775" },
                        { IOUtil.GetConfigFilePath(), "770" },
                        { IOUtil.GetCredFilePath(), "770" },
                    };
                    var unixUtil = HostContext.CreateService <IUnixUtil>();
                    foreach (var file in filesToChange)
                    {
                        await unixUtil.Chown(uidValue, gidValue, file.Key);

                        await unixUtil.Chmod(file.Value, file.Key);
                    }
                }
            }

            if (runAsService && successfullyConfigured)
            {
                Trace.Info("Configuration was successful, trying to start the service");
                serviceControlManager.StartService();
            }
        }
 public Task <TaskAgent> ReplaceAgentAsync(int agentPoolId, TaskAgent agent)
 {
     CheckConnection(RunnerConnectionType.Generic);
     return(_genericTaskAgentClient.ReplaceAgentAsync(agentPoolId, agent));
 }
Esempio n. 23
0
 public Task <TaskAgent> AddAgentAsync(Int32 agentPoolId, TaskAgent agent)
 {
     CheckConnection();
     return(_taskAgentClient.AddAgentAsync(agentPoolId, agent));
 }
Esempio n. 24
0
        public async Task UnconfigureAsync(CommandSettings command)
        {
            string currentAction = string.Empty;

            try
            {
                //stop, uninstall service and remove service config file
                if (_store.IsServiceConfigured())
                {
                    currentAction = StringUtil.Loc("UninstallingService");
                    _term.WriteLine(currentAction);
                    if (PlatformUtil.RunningOnWindows)
                    {
                        var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>();
                        serviceControlManager.UnconfigureService();
                        _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                    }
                    else if (PlatformUtil.RunningOnLinux)
                    {
                        // unconfig systemd service first
                        throw new Exception(StringUtil.Loc("UnconfigureServiceDService"));
                    }
                    else if (PlatformUtil.RunningOnMacOS)
                    {
                        // unconfig macOS service first
                        throw new Exception(StringUtil.Loc("UnconfigureOSXService"));
                    }
                }
                else
                {
                    if (PlatformUtil.RunningOnWindows)
                    {
                        //running as process, unconfigure autologon if it was configured
                        if (_store.IsAutoLogonConfigured())
                        {
                            currentAction = StringUtil.Loc("UnconfigAutologon");
                            _term.WriteLine(currentAction);
                            var autoLogonConfigManager = HostContext.GetService <IAutoLogonManager>();
                            autoLogonConfigManager.Unconfigure();
                            _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                        }
                        else
                        {
                            Trace.Info("AutoLogon was not configured on the agent.");
                        }
                    }
                }

                //delete agent from the server
                currentAction = StringUtil.Loc("UnregisteringAgent");
                _term.WriteLine(currentAction);
                bool isConfigured   = _store.IsConfigured();
                bool hasCredentials = _store.HasCredentials();
                if (isConfigured && hasCredentials)
                {
                    AgentSettings settings          = _store.GetSettings();
                    var           credentialManager = HostContext.GetService <ICredentialManager>();

                    // Get the credentials
                    var            credProvider = GetCredentialProvider(command, settings.ServerUrl);
                    VssCredentials creds        = credProvider.GetVssCredentials(HostContext);
                    Trace.Info("cred retrieved");

                    bool isEnvironmentVMResource = false;
                    bool isDeploymentGroup       = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0);
                    if (!isDeploymentGroup)
                    {
                        isEnvironmentVMResource = settings.EnvironmentId > 0;
                    }

                    Trace.Info("Agent configured for deploymentGroup : {0}", isDeploymentGroup.ToString());

                    string agentType = isDeploymentGroup
                   ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration
                   : isEnvironmentVMResource
                   ? Constants.Agent.AgentConfigurationProvider.EnvironmentVMResourceConfiguration
                   : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration;

                    var extensionManager = HostContext.GetService <IExtensionManager>();
                    IConfigurationProvider agentProvider = (extensionManager.GetExtensions <IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType);
                    ArgUtil.NotNull(agentProvider, agentType);

                    // Determine the service deployment type based on connection data. (Hosted/OnPremises)
                    bool isHostedServer = await IsHostedServer(settings.ServerUrl, creds);

                    await agentProvider.TestConnectionAsync(settings, creds, isHostedServer);

                    TaskAgent agent = await agentProvider.GetAgentAsync(settings);

                    if (agent == null)
                    {
                        _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                    }
                    else
                    {
                        await agentProvider.DeleteAgentAsync(settings);

                        _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                    }
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("MissingConfig"));
                }

                //delete credential config files
                currentAction = StringUtil.Loc("DeletingCredentials");
                _term.WriteLine(currentAction);
                if (hasCredentials)
                {
                    _store.DeleteCredential();
                    var keyManager = HostContext.GetService <IRSAKeyManager>();
                    keyManager.DeleteKey();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }

                //delete settings config file
                currentAction = StringUtil.Loc("DeletingSettings");
                _term.WriteLine(currentAction);
                if (isConfigured)
                {
                    // delete proxy setting
                    (HostContext.GetService <IVstsAgentWebProxy>() as VstsAgentWebProxy).DeleteProxySetting();

                    // delete agent cert setting
                    (HostContext.GetService <IAgentCertificateManager>() as AgentCertificateManager).DeleteCertificateSetting();

                    // delete agent runtime option
                    _store.DeleteAgentRuntimeOptions();

                    _store.DeleteSettings();
                    _term.WriteLine(StringUtil.Loc("Success") + currentAction);
                }
                else
                {
                    _term.WriteLine(StringUtil.Loc("Skipping") + currentAction);
                }
            }
            catch (Exception)
            {
                _term.WriteLine(StringUtil.Loc("Failed") + currentAction);
                throw;
            }
        }
Esempio n. 25
0
 public Task <TaskAgent> UpdateAgentAsync(int agentPoolId, TaskAgent agent)
 {
     CheckConnection();
     return(_taskAgentClient.ReplaceAgentAsync(agentPoolId, agent));
 }
Esempio n. 26
0
 public Task <TaskAgent> AddAgentAsync(Int32 agentPoolId, TaskAgent agent)
 {
     CheckConnection(RunnerConnectionType.Generic);
     return(_genericTaskAgentClient.AddAgentAsync(agentPoolId, agent));
 }
 public Task <TaskAgent> AddAgentAsync(int poolId, TaskAgent agent, CommandSettings command)
 {
     return(_agentServer.AddAgentAsync(poolId, agent));
 }