Esempio n. 1
0
 public Task <NetworkCredential> ResetWindowsUserAsync(
     VmInstanceReference instanceRef,
     string username,
     CancellationToken token)
 {
     return(ResetWindowsUserAsync(instanceRef, username, token, DefaultPasswordResetTimeout));
 }
Esempio n. 2
0
        private async Task <IRemoteDesktopSession> Connect(
            RdpTunnel tunnel,
            VmInstanceReference vmInstanceReference)
        {
            using (var gceAdapter = new ComputeEngineAdapter(this.serviceProvider.GetService <IAuthorizationAdapter>()))
            {
                var credentials = await gceAdapter.ResetWindowsUserAsync(
                    vmInstanceReference,
                    CreateRandomUsername(),
                    CancellationToken.None);

                var rdpService = new RemoteDesktopService(this.serviceProvider);
                return(rdpService.Connect(
                           vmInstanceReference,
                           "localhost",
                           (ushort)tunnel.LocalPort,
                           new VmInstanceConnectionSettings()
                {
                    Username = credentials.UserName,
                    Password = credentials.SecurePassword,
                    AuthenticationLevel = RdpAuthenticationLevel.NoServerAuthentication,
                    BitmapPersistence = RdpBitmapPersistence.Disabled,
                    DesktopSize = RdpDesktopSize.ClientSize
                }));
            }
        }
        public async Task WhenInstanceDoesntExist_ThenPasswordResetExceptionIsThrown(
            [WindowsInstance] InstanceRequest testInstance)
        {
            await testInstance.AwaitReady();

            var username = "******" + Guid.NewGuid().ToString();

            // Use correct project, but wrong VM.
            var instanceRef = new VmInstanceReference(
                testInstance.InstanceReference.ProjectId,
                testInstance.InstanceReference.Zone,
                testInstance.InstanceReference.InstanceName + "-x");

            try
            {
                await this.instancesResource.ResetWindowsUserAsync(
                    instanceRef,
                    username,
                    CancellationToken.None);

                Assert.Fail();
            }
            catch (PasswordResetException e)
            {
                Assert.IsNotEmpty(e.Message);
            }
        }
        public async Task <NetworkCredential> GenerateCredentialsAsync(
            IWin32Window owner,
            VmInstanceReference instanceRef,
            string suggestedUsername = null)
        {
            // Prompt for username to use.
            var username = new GenerateCredentialsDialog().PromptForUsername(
                owner,
                suggestedUsername ?? this.authService.Authorization.SuggestWindowsUsername());

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

            var credentials = await this.jobService.RunInBackground(
                new JobDescription("Generating Windows logon credentials..."),
                token => this.computeEngineAdapter.ResetWindowsUserAsync(
                    instanceRef,
                    username,
                    token));

            new ShowCredentialsDialog().ShowDialog(
                owner,
                credentials.UserName,
                credentials.Password);

            return(credentials);
        }
Esempio n. 5
0
        private Task AwaitReady(ComputeEngine engine, VmInstanceReference instanceRef)
        {
            return(Task.Run(async() =>
            {
                for (int i = 0; i < 60; i++)
                {
                    try
                    {
                        var instance = await engine.Service.Instances.Get(
                            instanceRef.ProjectId, instanceRef.Zone, instanceRef.InstanceName)
                                       .ExecuteAsync();

                        if (await IsReadyAsync(engine, instanceRef, instance))
                        {
                            return;
                        }
                    }
                    catch (Exception)
                    { }

                    await Task.Delay(5 * 1000);
                }

                throw new TimeoutException($"Timeout waiting for {instanceRef} to become ready");
            }));
        }
Esempio n. 6
0
        public static async Task <NetworkCredential> ResetWindowsUserAsync(
            this InstancesResource resource,
            VmInstanceReference instanceRef,
            string username,
            CancellationToken token,
            TimeSpan timeout)
        {
            using (var timeoutCts = new CancellationTokenSource())
            {
                timeoutCts.CancelAfter(timeout);

                using (var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, token))
                {
                    try
                    {
                        return(await ResetWindowsUserAsync(
                                   resource,
                                   instanceRef,
                                   username,
                                   combinedCts.Token));
                    }
                    catch (Exception e) when(e.IsCancellation() && timeoutCts.IsCancellationRequested)
                    {
                        // This task was cancelled because of a timeout, not because
                        // the enclosing job was cancelled.
                        throw new PasswordResetException(
                                  "Timeout waiting for Compute Engine agent to reset password. " +
                                  "Verify that the agent is running.");
                    }
                }
            }
        }
 public SerialPortStream GetSerialPortOutput(VmInstanceReference instanceRef)
 {
     using (TraceSources.IapDesktop.TraceMethod().WithParameters(instanceRef))
     {
         return(this.service.Instances.GetSerialPortOutputStream(instanceRef, 1));
     }
 }
Esempio n. 8
0
        public void WhenProbeFails_ThenOpenTunnelsDoesNotIncludeTunnel()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <Tunnel>(null, null, null);

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromException(new ApplicationException()));

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new VmInstanceReference("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(destination))
            .Returns(Task.FromResult(mockTunnel.Object));

            AssertEx.ThrowsAggregateException <ApplicationException>(() =>
            {
                broker.ConnectAsync(destination, TimeSpan.FromMinutes(1)).Wait();
            });

            Assert.AreEqual(0, broker.OpenTunnels.Count());
        }
Esempio n. 9
0
        public SerialLogWindow(VmInstanceReference vmInstance)
        {
            InitializeComponent();

            this.TabText  = $"Log ({vmInstance.InstanceName})";
            this.Instance = vmInstance;
        }
Esempio n. 10
0
 /// <summary>
 /// Read serial port output as a continuous stream.
 /// </summary>
 public static SerialPortStream GetSerialPortOutputStream(
     this InstancesResource resource,
     VmInstanceReference instanceRef,
     ushort port)
 {
     return(new SerialPortStream(resource, instanceRef, port));
 }
Esempio n. 11
0
        public async Task WhenConnectSuccessful_OpenEventIsFired()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <Tunnel>(null, null, null);

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(true));

            var broker        = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);
            var vmInstanceRef = new VmInstanceReference("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(destination))
            .Returns(Task.FromResult(mockTunnel.Object));

            var tunnel = await broker.ConnectAsync(destination, TimeSpan.FromMinutes(1));

            mockEventService.Verify(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()), Times.Once);
        }
Esempio n. 12
0
        //---------------------------------------------------------------------
        // Ctor
        //---------------------------------------------------------------------

        private InstanceHistoryBuilder(
            ulong instanceId,
            VmInstanceReference reference,
            GlobalResourceReference image,
            InstanceState state,
            DateTime?lastSeen,
            Tenancy tenancy)
        {
            if (instanceId == 0)
            {
                throw new ArgumentException("Instance ID cannot be 0");
            }

            this.InstanceId    = instanceId;
            this.reference     = reference;
            this.image         = image;
            this.lastStoppedOn = lastSeen;

            if (state == InstanceState.Running)
            {
                Debug.Assert(tenancy != Tenancy.Unknown);
                Debug.Assert(lastSeen != null);

                // Add a synthetic placement.
                AddPlacement(new InstancePlacement(tenancy, null, lastSeen.Value, lastSeen.Value));
            }
        }
 public async Task <Instance> QueryInstanceAsync(VmInstanceReference instanceRef)
 {
     using (TraceSources.IapDesktop.TraceMethod().WithParameters(instanceRef))
     {
         return(await QueryInstanceAsync(instanceRef.ProjectId, instanceRef.Zone, instanceRef.InstanceName));
     }
 }
 public IapTunnelingEndpoint(ICredential credential, VmInstanceReference vmInstance, ushort port, string nic)
 {
     this.credential = credential;
     this.VmInstance = vmInstance;
     this.Port       = port;
     this.Interface  = nic;
 }
Esempio n. 15
0
        public async Task WhenConnectingTwice_ExistingTunnelIsReturned()
        {
            var mockTunnelService = new Mock <ITunnelService>();

            var mockEventService = new Mock <IEventService>();

            mockEventService.Setup(s => s.FireAsync(It.IsAny <TunnelOpenedEvent>()))
            .Returns(Task.FromResult(true));

            var mockTunnel = new Mock <Tunnel>(null, null, null);

            mockTunnel.Setup(t => t.Probe(It.IsAny <TimeSpan>()))
            .Returns(Task.FromResult(true));
            var broker = new TunnelBrokerService(mockTunnelService.Object, mockEventService.Object);

            var vmInstanceRef = new VmInstanceReference("project", "zone", "instance");
            var destination   = new TunnelDestination(vmInstanceRef, 3389);

            mockTunnelService.Setup(s => s.CreateTunnelAsync(destination))
            .Returns(Task.FromResult(mockTunnel.Object));

            var tunnel1 = await broker.ConnectAsync(destination, TimeSpan.FromMinutes(1));

            var tunnel2 = await broker.ConnectAsync(destination, TimeSpan.FromMinutes(1));

            Assert.IsNotNull(tunnel1);
            Assert.IsNotNull(tunnel2);
            Assert.AreSame(tunnel1, tunnel2);
            Assert.AreEqual(1, broker.OpenTunnels.Count());
        }
 protected override INetworkStream ConnectToEchoServer(VmInstanceReference vmRef)
 {
     return(new FragmentingStream(new SshRelayStream(
                                      new IapTunnelingEndpoint(
                                          Defaults.GetCredential(),
                                          vmRef,
                                          7,
                                          IapTunnelingEndpoint.DefaultNetworkInterface))));
 }
Esempio n. 17
0
 public SerialPortStream(
     InstancesResource instancesResource,
     VmInstanceReference instanceRef,
     ushort port)
 {
     this.instancesResource = instancesResource;
     this.port     = port;
     this.instance = instanceRef;
 }
 public VmInstanceNode TryFindNode(VmInstanceReference reference)
 {
     return(this.rootNode.Nodes
            .OfType <ProjectNode>()
            .Where(p => p.ProjectId == reference.ProjectId)
            .SelectMany(p => p.Nodes.Cast <ZoneNode>())
            .Where(z => z.ZoneId == reference.Zone)
            .SelectMany(z => z.Nodes.Cast <VmInstanceNode>())
            .FirstOrDefault(vm => vm.InstanceName == reference.InstanceName));;
 }
Esempio n. 19
0
        public void TestNotEquals()
        {
            var ref1 = new VmInstanceReference("proj", "zone", "inst");
            var ref2 = new VmInstanceReference("proj", "zone", "other");

            Assert.IsFalse(ref1.Equals(ref2));
            Assert.IsFalse(ref1.Equals((object)ref2));
            Assert.IsFalse(ref1 == ref2);
            Assert.IsTrue(ref1 != ref2);
        }
Esempio n. 20
0
        public void WhenReferencesAreOfDifferentType_ThenEqualsReturnsFalse()
        {
            var ref1 = new VmInstanceReference("proj", "zone", "inst");
            var ref2 = new ZonalResourceReference("proj", "zone", "instances", "inst");

            Assert.IsFalse(ref2.Equals(ref1));
            Assert.IsFalse(ref2.Equals((object)ref1));
            Assert.IsFalse(ref1.Equals(ref2));
            Assert.IsFalse(ref1.Equals((object)ref2));
        }
Esempio n. 21
0
        public void WhenReferencesAreNotEquivalent_ThenEqualsReturnsFalse()
        {
            var ref1 = new VmInstanceReference("proj", "zone", "inst");
            var ref2 = new VmInstanceReference("proj", "zone", "other");

            Assert.IsFalse(ref1.Equals(ref2));
            Assert.IsFalse(ref1.Equals((object)ref2));
            Assert.IsFalse(ref1 == ref2);
            Assert.IsTrue(ref1 != ref2);
        }
 public async Task <NetworkCredential> ResetWindowsUserAsync(
     VmInstanceReference instanceRef,
     string username,
     CancellationToken token)
 {
     using (TraceSources.IapDesktop.TraceMethod().WithParameters(instanceRef))
     {
         return(await this.service.Instances.ResetWindowsUserAsync(instanceRef, username, token));
     }
 }
Esempio n. 23
0
        public void TestEqualsNull()
        {
            var ref1 = new VmInstanceReference("proj", "zone", "inst");

            Assert.IsFalse(ref1.Equals(null));
            Assert.IsFalse(ref1.Equals((object)null));
            Assert.IsFalse(ref1 == null);
            Assert.IsFalse(null == ref1);
            Assert.IsTrue(ref1 != null);
            Assert.IsTrue(null != ref1);
        }
Esempio n. 24
0
        public void OnStop(DateTime date, VmInstanceReference reference)
        {
            Debug.Assert(date <= this.lastEventDate);
            this.lastEventDate = date;

            this.lastStoppedOn = date;

            if (this.reference == null)
            {
                this.reference = reference;
            }
        }
Esempio n. 25
0
        public void OnStart(DateTime date, VmInstanceReference reference)
        {
            Debug.Assert(date <= this.lastEventDate);
            this.lastEventDate = date;

            if (this.reference == null)
            {
                this.reference = reference;
            }

            // Register Fleet placement - this might be merged with an existing
            // SoleTenant placement if there has been one registerd before.
            AddPlacement(Tenancy.Fleet, null, date);
        }
Esempio n. 26
0
 internal InstanceHistory(
     [JsonProperty("id")] ulong instanceId,
     [JsonProperty("vm")] VmInstanceReference reference,
     [JsonProperty("state")] InstanceHistoryState state,
     [JsonProperty("image")] GlobalResourceReference image,
     [JsonProperty("placements")] IEnumerable <InstancePlacement> placements
     )
 {
     this.InstanceId = instanceId;
     this.Reference  = reference;
     this.State      = state;
     this.Image      = image;
     this.Placements = placements;
 }
Esempio n. 27
0
        public void ShowSerialLog(VmInstanceReference vmInstance)
        {
            var window = TryGetExistingWindow(vmInstance);

            if (window == null)
            {
                var gceAdapter = this.serviceProvider.GetService <IComputeEngineAdapter>();

                window = new SerialLogWindow(vmInstance);
                window.TailSerialPortStream(gceAdapter.GetSerialPortOutput(vmInstance));
            }

            window.ShowOrActivate(this.dockPanel, DockState.DockBottomAutoHide);
        }
Esempio n. 28
0
 public IEnumerable GetData(IParameterInfo parameter)
 {
     if (parameter.ParameterType == typeof(InstanceRequest))
     {
         var vmRef = new VmInstanceReference(
             this.ProjectId,
             this.Zone,
             this.UniqueId);
         yield return(new InstanceRequest(vmRef, () => GetInstanceAsync(vmRef)));
     }
     else
     {
         throw new ArgumentException($"Parameter must be of type {typeof(VmInstanceReference).Name}");
     }
 }
Esempio n. 29
0
        public static RdpTunnel Create(VmInstanceReference vmRef)
        {
            var listener = SshRelayListener.CreateLocalListener(
                new IapTunnelingEndpoint(
                    Defaults.GetCredential(),
                    vmRef,
                    3389,
                    IapTunnelingEndpoint.DefaultNetworkInterface));

            var tokenSource = new CancellationTokenSource();

            listener.ListenAsync(tokenSource.Token);

            return(new RdpTunnel(listener, tokenSource));
        }
        public bool TryActivate(VmInstanceReference vmInstance)
        {
            // Check if there is an existing session/pane.
            var rdpPane = TryGetExistingPane(vmInstance);

            if (rdpPane != null)
            {
                // Pane found, activate.
                rdpPane.Show(this.dockPanel, DockState.Document);
                return(true);
            }
            else
            {
                return(false);
            }
        }