Start() public method

public Start ( ) : void
return void
 /// <exception cref="NSch.JSchException"></exception>
 public override void Connect()
 {
     try
     {
         Session _session = GetSession();
         if (!_session.IsConnected())
         {
             throw new JSchException("session is down");
         }
         if (io.@in != null)
         {
             thread = new Sharpen.Thread(this);
             thread.SetName("DirectTCPIP thread " + _session.GetHost());
             if (_session.daemon_thread)
             {
                 thread.SetDaemon(_session.daemon_thread);
             }
             thread.Start();
         }
     }
     catch (Exception e)
     {
         io.Close();
         io = null;
         Channel.Del(this);
         if (e is JSchException)
         {
             throw (JSchException)e;
         }
     }
 }
        /// <exception cref="NSch.JSchException"></exception>
        public override void Start()
        {
            Session _session = GetSession();

            try
            {
                SendRequests();
                Request request = new RequestShell();
                request.DoRequest(_session, this);
            }
            catch (Exception e)
            {
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                if (e is Exception)
                {
                    throw new JSchException("ChannelShell", (Exception)e);
                }
                throw new JSchException("ChannelShell");
            }
            if (io.@in != null)
            {
                thread = new Sharpen.Thread(this);
                thread.SetName("Shell for " + _session.host);
                if (_session.daemon_thread)
                {
                    thread.SetDaemon(_session.daemon_thread);
                }
                thread.Start();
            }
        }
Ejemplo n.º 3
0
 internal virtual Sharpen.Thread Start(int n)
 {
     this.n = n;
     Sharpen.Thread t = new Sharpen.Thread(this);
     t.Start();
     return(t);
 }
Ejemplo n.º 4
0
        /// <summary>This is a main function for testing JobControl class.</summary>
        /// <remarks>
        /// This is a main function for testing JobControl class.
        /// It requires 4 jobs:
        /// Job 1: passed as parameter. input:indir  output:outdir_1
        /// Job 2: copy data from indir to outdir_2
        /// Job 3: copy data from outdir_1 and outdir_2 to outdir_3
        /// Job 4: copy data from outdir to outdir_4
        /// The jobs 1 and 2 have no dependency. The job 3 depends on jobs 1 and 2.
        /// The job 4 depends on job 3.
        /// Then it creates a JobControl object and add the 4 jobs to
        /// the JobControl object.
        /// Finally, it creates a thread to run the JobControl object
        /// </remarks>
        /// <exception cref="System.Exception"/>
        private JobControl CreateDependencies(Configuration conf, Job job1)
        {
            IList <ControlledJob> dependingJobs = null;

            cjob1 = new ControlledJob(job1, dependingJobs);
            Job job2 = MapReduceTestUtil.CreateCopyJob(conf, outdir_2, indir);

            cjob2 = new ControlledJob(job2, dependingJobs);
            Job job3 = MapReduceTestUtil.CreateCopyJob(conf, outdir_3, outdir_1, outdir_2);

            dependingJobs = new AList <ControlledJob>();
            dependingJobs.AddItem(cjob1);
            dependingJobs.AddItem(cjob2);
            cjob3 = new ControlledJob(job3, dependingJobs);
            Job job4 = MapReduceTestUtil.CreateCopyJob(conf, outdir_4, outdir_3);

            dependingJobs = new AList <ControlledJob>();
            dependingJobs.AddItem(cjob3);
            cjob4 = new ControlledJob(job4, dependingJobs);
            JobControl theControl = new JobControl("Test");

            theControl.AddJob(cjob1);
            theControl.AddJob(cjob2);
            theControl.AddJob(cjob3);
            theControl.AddJob(cjob4);
            Sharpen.Thread theController = new Sharpen.Thread(theControl);
            theController.Start();
            return(theControl);
        }
Ejemplo n.º 5
0
        /// <exception cref="System.Exception"/>
        public virtual void TestDSShellWithNodeLabelExpression()
        {
            InitializeNodeLabels();
            // Start NMContainerMonitor
            TestDistributedShellWithNodeLabels.NMContainerMonitor mon = new TestDistributedShellWithNodeLabels.NMContainerMonitor
                                                                            (this);
            Sharpen.Thread t = new Sharpen.Thread(mon);
            t.Start();
            // Submit a job which will sleep for 60 sec
            string[] args = new string[] { "--jar", TestDistributedShell.AppmasterJar, "--num_containers"
                                           , "4", "--shell_command", "sleep", "--shell_args", "15", "--master_memory", "512"
                                           , "--master_vcores", "2", "--container_memory", "128", "--container_vcores", "1"
                                           , "--node_label_expression", "x" };
            Log.Info("Initializing DS Client");
            Client client = new Client(new Configuration(distShellTest.yarnCluster.GetConfig(
                                                             )));
            bool initSuccess = client.Init(args);

            NUnit.Framework.Assert.IsTrue(initSuccess);
            Log.Info("Running DS Client");
            bool result = client.Run();

            Log.Info("Client run completed. Result=" + result);
            t.Interrupt();
            // Check maximum number of containers on each NMs
            int[] maxRunningContainersOnNMs = mon.GetMaxRunningContainersReport();
            // Check no container allocated on NM[0]
            NUnit.Framework.Assert.AreEqual(0, maxRunningContainersOnNMs[0]);
            // Check there're some containers allocated on NM[1]
            NUnit.Framework.Assert.IsTrue(maxRunningContainersOnNMs[1] > 0);
        }
Ejemplo n.º 6
0
		/// <exception cref="NSch.JSchException"></exception>
		public override void Connect()
		{
			try
			{
				Session _session = GetSession();
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				if (io.@in != null)
				{
					thread = new Sharpen.Thread(this);
					thread.SetName("DirectTCPIP thread " + _session.GetHost());
					if (_session.daemon_thread)
					{
						thread.SetDaemon(_session.daemon_thread);
					}
					thread.Start();
				}
			}
			catch (Exception e)
			{
				io.Close();
				io = null;
				Channel.Del(this);
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
			}
		}
Ejemplo n.º 7
0
		/// <exception cref="NSch.JSchException"></exception>
		public override void Start()
		{
			Session _session = GetSession();
			try
			{
				SendRequests();
				Request request = new RequestExec(command);
				request.DoRequest(_session, this);
			}
			catch (Exception e)
			{
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				if (e is Exception)
				{
					throw new JSchException("ChannelExec", (Exception)e);
				}
				throw new JSchException("ChannelExec");
			}
			if (io.@in != null)
			{
				thread = new Sharpen.Thread(this);
				thread.SetName("Exec thread " + _session.GetHost());
				if (_session.daemon_thread)
				{
					thread.SetDaemon(_session.daemon_thread);
				}
				thread.Start();
			}
		}
Ejemplo n.º 8
0
        // use a small block size and a large write so that DN is busy creating
        // new blocks.  This makes it almost 100% sure we can reproduce
        // case of client getting a DN that hasn't yet created the blocks
        /// <exception cref="System.IO.IOException"/>
        public virtual void TestImmediateReadOfNewFile()
        {
            int           blockSize = 64 * 1024;
            int           writeSize = 10 * blockSize;
            Configuration conf      = new Configuration();

            conf.SetLong(DFSConfigKeys.DfsBlockSizeKey, blockSize);
            Init(conf);
            int                      requiredSuccessfulOpens = 100;
            Path                     file         = new Path("/file1");
            AtomicBoolean            openerDone   = new AtomicBoolean(false);
            AtomicReference <string> errorMessage = new AtomicReference <string>();
            FSDataOutputStream       @out         = fileSystem.Create(file);

            Sharpen.Thread writer = new Sharpen.Thread(new _Runnable_219(openerDone, @out, writeSize
                                                                         ));
            Sharpen.Thread opener = new Sharpen.Thread(new _Runnable_239(this, requiredSuccessfulOpens
                                                                         , file, openerDone, errorMessage, writer));
            writer.Start();
            opener.Start();
            try
            {
                writer.Join();
                opener.Join();
            }
            catch (Exception)
            {
                Sharpen.Thread.CurrentThread().Interrupt();
            }
            NUnit.Framework.Assert.IsNull(errorMessage.Get(), errorMessage.Get());
        }
Ejemplo n.º 9
0
        /// <exception cref="System.IO.IOException"/>
        private void RunTestUnfinishedBlockCRCError(bool transferToAllowed, TestFileConcurrentReader.SyncType
                                                    syncType, int writeSize, Configuration conf)
        {
            conf.SetBoolean(DFSConfigKeys.DfsDatanodeTransfertoAllowedKey, transferToAllowed);
            Init(conf);
            Path          file          = new Path("/block-being-written-to");
            int           numWrites     = 2000;
            AtomicBoolean writerDone    = new AtomicBoolean(false);
            AtomicBoolean writerStarted = new AtomicBoolean(false);
            AtomicBoolean error         = new AtomicBoolean(false);

            Sharpen.Thread writer = new Sharpen.Thread(new _Runnable_340(this, file, syncType
                                                                         , error, numWrites, writeSize, writerStarted, writerDone));
            Sharpen.Thread tailer = new Sharpen.Thread(new _Runnable_373(this, writerDone, error
                                                                         , writerStarted, file, writer));
            writer.Start();
            tailer.Start();
            try
            {
                writer.Join();
                tailer.Join();
                NUnit.Framework.Assert.IsFalse("error occurred, see log above", error.Get());
            }
            catch (Exception)
            {
                Log.Info("interrupted waiting for writer or tailer to complete");
                Sharpen.Thread.CurrentThread().Interrupt();
            }
        }
Ejemplo n.º 10
0
        /// <exception cref="System.Exception"/>
        protected override void ServiceStart()
        {
            client.Start();
            ThreadFactory tf = new ThreadFactoryBuilder().SetNameFormat(this.GetType().FullName
                                                                        + " #%d").SetDaemon(true).Build();
            // Start with a default core-pool size and change it dynamically.
            int initSize = Math.Min(InitialThreadPoolSize, maxThreadPoolSize);

            threadPool = new ThreadPoolExecutor(initSize, int.MaxValue, 1, TimeUnit.Hours, new
                                                LinkedBlockingQueue <Runnable>(), tf);
            eventDispatcherThread = new _Thread_125(this);
            // We can increase the pool size only if haven't reached the maximum
            // limit yet.
            // nodes where containers will run at *this* point of time. This is
            // *not* the cluster size and doesn't need to be.
            // Bump up the pool size to idealThreadPoolSize +
            // INITIAL_POOL_SIZE, the later is just a buffer so we are not
            // always increasing the pool-size
            // the events from the queue are handled in parallel with a thread
            // pool
            // TODO: Group launching of multiple containers to a single
            // NodeManager into a single connection
            eventDispatcherThread.SetName("Container  Event Dispatcher");
            eventDispatcherThread.SetDaemon(false);
            eventDispatcherThread.Start();
            base.ServiceStart();
        }
 /// <exception cref="System.Exception"></exception>
 private static void RunOnThread(Runnable task)
 {
     Sharpen.Thread t = new Sharpen.Thread(task);
     t.Start();
     t.Join(1000);
     NUnit.Framework.Assert.IsFalse(t.IsAlive(), "thread has stopped");
 }
Ejemplo n.º 12
0
        /// <exception cref="System.Exception"/>
        public virtual void TestTransitionedToStandbyShouldNotHang()
        {
            configuration.SetBoolean(YarnConfiguration.AutoFailoverEnabled, false);
            Configuration      conf     = new YarnConfiguration(configuration);
            MemoryRMStateStore memStore = new _MemoryRMStateStore_464();

            memStore.Init(conf);
            rm = new _MockRM_472(conf, memStore);
            rm.Init(conf);
            HAServiceProtocol.StateChangeRequestInfo requestInfo = new HAServiceProtocol.StateChangeRequestInfo
                                                                       (HAServiceProtocol.RequestSource.RequestByUser);
            NUnit.Framework.Assert.AreEqual(StateErr, HAServiceProtocol.HAServiceState.Initializing
                                            , rm.adminService.GetServiceStatus().GetState());
            NUnit.Framework.Assert.IsFalse("RM is ready to become active before being started"
                                           , rm.adminService.GetServiceStatus().IsReadyToBecomeActive());
            CheckMonitorHealth();
            rm.Start();
            CheckMonitorHealth();
            CheckStandbyRMFunctionality();
            // 2. Transition to Active.
            rm.adminService.TransitionToActive(requestInfo);
            // 3. Try Transition to standby
            Sharpen.Thread t = new Sharpen.Thread(new _Runnable_498(this));
            // TODO Auto-generated catch block
            t.Start();
            rm.GetRMContext().GetStateStore().UpdateApplicationState(null);
            t.Join();
            // wait for thread to finish
            rm.adminService.TransitionToStandby(requestInfo);
            CheckStandbyRMFunctionality();
            rm.Stop();
        }
Ejemplo n.º 13
0
 /// <exception cref="System.Exception"/>
 protected override void ServiceStart()
 {
     lostTaskCheckerThread = new Sharpen.Thread(new TaskHeartbeatHandler.PingChecker(this
                                                                                     ));
     lostTaskCheckerThread.SetName("TaskHeartbeatHandler PingChecker");
     lostTaskCheckerThread.Start();
     base.ServiceStart();
 }
Ejemplo n.º 14
0
 /// <exception cref="System.Exception"/>
 protected override void ServiceStart()
 {
     //start all the components
     base.ServiceStart();
     eventHandlingThread = new Sharpen.Thread(CreateThread());
     eventHandlingThread.SetName("AsyncDispatcher event handler");
     eventHandlingThread.Start();
 }
Ejemplo n.º 15
0
 public virtual void StartCheckpointThread()
 {
     Preconditions.CheckState(checkpointThread == null, "Should not already have a thread"
                              );
     Preconditions.CheckState(shouldRun, "shouldRun should be true");
     checkpointThread = new Daemon(this);
     checkpointThread.Start();
 }
Ejemplo n.º 16
0
 /// <exception cref="System.Exception"/>
 protected override void ServiceStart()
 {
     System.Diagnostics.Debug.Assert(!stopped, "starting when already stopped");
     checkerThread = new Sharpen.Thread(new SchedulingMonitor.PreemptionChecker(this));
     checkerThread.SetName(GetName());
     checkerThread.Start();
     base.ServiceStart();
 }
Ejemplo n.º 17
0
		/// <exception cref="System.Exception"></exception>
		private void RunTestScript()
		{
			// will start new thread to get as close as possible to original
			// environment, however the same behavior is exposed using new
			// ScriptRunner(script).run();
			Sharpen.Thread thread = new Sharpen.Thread(new Bug421071Test.ScriptRunner(this, testScript));
			thread.Start();
			thread.Join();
		}
Ejemplo n.º 18
0
Archivo: Util.cs Proyecto: shoff/ngit
        /// <exception cref="NSch.JSchException"></exception>
        internal static Socket CreateSocket(string host, int port, int timeout)
        {
            Socket socket = null;

            if (timeout == 0)
            {
                try
                {
                    socket = Sharpen.Extensions.CreateSocket(host, port);
                    return(socket);
                }
                catch (Exception e)
                {
                    string message = e.Message;
                    if (e is Exception)
                    {
                        throw new JSchException(message, (Exception)e);
                    }
                    throw new JSchException(message);
                }
            }
            string _host = host;
            int    _port = port;

            Socket[]    sockp     = new Socket[1];
            Exception[] ee        = new Exception[1];
            string      message_1 = string.Empty;

            Sharpen.Thread tmp = new Sharpen.Thread(new _Runnable_350(sockp, _host, _port, ee
                                                                      ));
            tmp.SetName("Opening Socket " + host);
            tmp.Start();
            try
            {
                tmp.Join(timeout);
                message_1 = "timeout: ";
            }
            catch (Exception)
            {
            }
            if (sockp[0] != null && sockp[0].Connected)
            {
                socket = sockp[0];
            }
            else
            {
                message_1 += "socket is not established";
                if (ee[0] != null)
                {
                    message_1 = ee[0].ToString();
                }
                tmp.Interrupt();
                tmp = null;
                throw new JSchException(message_1);
            }
            return(socket);
        }
Ejemplo n.º 19
0
        /*   *************************************************************    */
        // This is the task-mongering that creates the two new threads -- one for
        //  processing events from the event queue and one for periodically
        //  looking for speculation opportunities
        /// <exception cref="System.Exception"/>
        protected override void ServiceStart()
        {
            Runnable speculationBackgroundCore = new _Runnable_192(this);

            speculationBackgroundThread = new Sharpen.Thread(speculationBackgroundCore, "DefaultSpeculator background processing"
                                                             );
            speculationBackgroundThread.Start();
            base.ServiceStart();
        }
Ejemplo n.º 20
0
 /// <exception cref="System.Exception"/>
 internal virtual void Start()
 {
     bkthread.Start();
     if (!LocalBookKeeper.WaitForServerUp(zkEnsemble, 10000))
     {
         throw new Exception("Error starting zookeeper/bookkeeper");
     }
     NUnit.Framework.Assert.AreEqual("Not all bookies started", numBookies, CheckBookiesUp
                                         (numBookies, 10));
 }
Ejemplo n.º 21
0
 /// <exception cref="System.Exception"/>
 protected override void ServiceStart()
 {
     System.Diagnostics.Debug.Assert(!stopped, "starting when already stopped");
     ResetTimer();
     checkerThread = new Sharpen.Thread(new AbstractLivelinessMonitor.PingChecker(this
                                                                                  ));
     checkerThread.SetName("Ping Checker");
     checkerThread.Start();
     base.ServiceStart();
 }
 internal virtual void Start()
 {
     Preconditions.CheckState(state.CompareAndSet(TestAppendSnapshotTruncate.Worker.State
                                                  .Idle, TestAppendSnapshotTruncate.Worker.State.Running));
     if (thread.Get() == null)
     {
         Sharpen.Thread t = new Sharpen.Thread(null, new _Runnable_446(this), name);
         Preconditions.CheckState(thread.CompareAndSet(null, t));
         t.Start();
     }
 }
Ejemplo n.º 23
0
        public bool Start()
        {
            this.Error = null;
            string maskedRemoteWithoutCredentials = databaseURL.ToString();

            maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@", "://---:---@");
            // TODO: Replace Thread object with TPL.
            thread = new Sharpen.Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials);
            thread.Start();
            return(true);
        }
Ejemplo n.º 24
0
        public virtual bool Start()
        {
            this.error = null;
            string maskedRemoteWithoutCredentials = databaseURL.ToExternalForm();

            maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@"
                                                                                       , "://---:---@");
            thread = new Sharpen.Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials
                                        );
            thread.Start();
            return(true);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Starts a background thread that accepts one and only one client connection
 /// on the server socket, sends an HTTP 307 Temporary Redirect response, and
 /// then exits.
 /// </summary>
 /// <remarks>
 /// Starts a background thread that accepts one and only one client connection
 /// on the server socket, sends an HTTP 307 Temporary Redirect response, and
 /// then exits.  This is useful for testing timeouts on the second step of
 /// methods that issue 2 HTTP requests (request 1, redirect, request 2).
 /// For handling the first request, this method sets socket timeout to use the
 /// initial values defined in URLUtils.  Afterwards, it guarantees that the
 /// second request will use a very short timeout.
 /// Optionally, the thread may consume the connection backlog immediately after
 /// receiving its one and only client connection.  This is useful for forcing a
 /// connection timeout on the second request.
 /// On tearDown, open client connections are closed, and the thread is joined.
 /// </remarks>
 /// <param name="consumeConnectionBacklog">
 /// boolean whether or not to consume connection
 /// backlog and thus force a connection timeout on the second request
 /// </param>
 private void StartSingleTemporaryRedirectResponseThread(bool consumeConnectionBacklog
                                                         )
 {
     fs.connectionFactory = URLConnectionFactory.DefaultSystemConnectionFactory;
     serverThread         = new _Thread_254(this, consumeConnectionBacklog);
     // Accept one and only one client connection.
     // Immediately setup conditions for subsequent connections.
     // Consume client's HTTP request by reading until EOF or empty line.
     // Write response.
     // Fail the test on any I/O error in the server thread.
     // Clean it all up.
     serverThread.Start();
 }
Ejemplo n.º 26
0
 // Relocalization note/future FIXME (per chrisdo, 20110315):  At moment,
 // full localization info is in AppSubmissionContext passed from client to
 // RM and then to NM for AM-container launch:  no difference between AM-
 // localization and MapTask- or ReduceTask-localization, so can assume all
 // OK.  Longer-term, will need to override uber-AM container-localization
 // request ("needed resources") with union of regular-AM-resources + task-
 // resources (and, if maps and reduces ever differ, then union of all three
 // types), OR will need localizer service/API that uber-AM can request
 // after running (e.g., "localizeForTask()" or "localizeForMapTask()").
 /// <exception cref="System.Exception"/>
 protected override void ServiceStart()
 {
     // create a single thread for serial execution of tasks
     // make it a daemon thread so that the process can exit even if the task is
     // not interruptible
     taskRunner = Executors.NewSingleThreadExecutor(new ThreadFactoryBuilder().SetDaemon
                                                        (true).SetNameFormat("uber-SubtaskRunner").Build());
     // create and start an event handling thread
     eventHandler = new Sharpen.Thread(new LocalContainerLauncher.EventHandler(this),
                                       "uber-EventHandler");
     eventHandler.Start();
     base.ServiceStart();
 }
Ejemplo n.º 27
0
        public virtual void TestUncaughtExceptionHandlerWithOutOfMemoryError()
        {
            ExitUtil.DisableSystemHalt();
            YarnUncaughtExceptionHandler spyOomHandler = Org.Mockito.Mockito.Spy(exHandler);
            OutOfMemoryException         oomError      = new OutOfMemoryException("out-of-memory-error");

            Sharpen.Thread oomThread = new Sharpen.Thread(new _Runnable_104(oomError));
            oomThread.SetUncaughtExceptionHandler(spyOomHandler);
            NUnit.Framework.Assert.AreSame(spyOomHandler, oomThread.GetUncaughtExceptionHandler
                                               ());
            oomThread.Start();
            oomThread.Join();
            Org.Mockito.Mockito.Verify(spyOomHandler).UncaughtException(oomThread, oomError);
        }
Ejemplo n.º 28
0
        public virtual void TestUncaughtExceptionHandlerWithError()
        {
            ExitUtil.DisableSystemExit();
            YarnUncaughtExceptionHandler spyErrorHandler = Org.Mockito.Mockito.Spy(exHandler);
            Error error = new Error("test-error");

            Sharpen.Thread errorThread = new Sharpen.Thread(new _Runnable_75(error));
            errorThread.SetUncaughtExceptionHandler(spyErrorHandler);
            NUnit.Framework.Assert.AreSame(spyErrorHandler, errorThread.GetUncaughtExceptionHandler
                                               ());
            errorThread.Start();
            errorThread.Join();
            Org.Mockito.Mockito.Verify(spyErrorHandler).UncaughtException(errorThread, error);
        }
Ejemplo n.º 29
0
        public virtual void TestUncaughtExceptionHandlerWithRuntimeException()
        {
            YarnUncaughtExceptionHandler spyYarnHandler = Org.Mockito.Mockito.Spy(exHandler);
            YarnRuntimeException         yarnException  = new YarnRuntimeException("test-yarn-runtime-exception"
                                                                                   );

            Sharpen.Thread yarnThread = new Sharpen.Thread(new _Runnable_45(yarnException));
            yarnThread.SetUncaughtExceptionHandler(spyYarnHandler);
            NUnit.Framework.Assert.AreSame(spyYarnHandler, yarnThread.GetUncaughtExceptionHandler
                                               ());
            yarnThread.Start();
            yarnThread.Join();
            Org.Mockito.Mockito.Verify(spyYarnHandler).UncaughtException(yarnThread, yarnException
                                                                         );
        }
Ejemplo n.º 30
0
 /// <summary>Start this daemon on a background thread.</summary>
 /// <remarks>Start this daemon on a background thread.</remarks>
 /// <exception cref="System.IO.IOException">the server socket could not be opened.</exception>
 /// <exception cref="System.InvalidOperationException">the daemon is already running.
 ///     </exception>
 public virtual void Start()
 {
     lock (this)
     {
         if (acceptThread != null)
         {
             throw new InvalidOperationException(JGitText.Get().daemonAlreadyRunning);
         }
         Socket listenSock = Sharpen.Extensions.CreateServerSocket(myAddress != null ? myAddress
                                                                   .Port : 0, BACKLOG, myAddress != null ? myAddress.Address : null);
         myAddress    = (IPEndPoint)listenSock.LocalEndPoint;
         run          = true;
         acceptThread = new _Thread_289(this, listenSock, processors, "Git-Daemon-Accept");
         // Test again to see if we should keep accepting.
         //
         acceptThread.Start();
     }
 }
Ejemplo n.º 31
0
        /// <exception cref="NSch.JSchException"></exception>
        public override void Start()
        {
            Session _session = GetSession();

            try
            {
                Request request;
                if (xforwading)
                {
                    request = new RequestX11();
                    request.DoRequest(_session, this);
                }
                if (pty)
                {
                    request = new RequestPtyReq();
                    request.DoRequest(_session, this);
                }
                request = new RequestSubsystem();
                ((RequestSubsystem)request).Request(_session, this, subsystem, want_reply);
            }
            catch (Exception e)
            {
                if (e is JSchException)
                {
                    throw (JSchException)e;
                }
                if (e is Exception)
                {
                    throw new JSchException("ChannelSubsystem", (Exception)e);
                }
                throw new JSchException("ChannelSubsystem");
            }
            if (io.@in != null)
            {
                thread = new Sharpen.Thread(this);
                thread.SetName("Subsystem for " + _session.host);
                if (_session.daemon_thread)
                {
                    thread.SetDaemon(_session.daemon_thread);
                }
                thread.Start();
            }
        }
Ejemplo n.º 32
0
 protected internal virtual void RebootNodeStatusUpdaterAndRegisterWithRM()
 {
     // Interrupt the updater.
     this.isStopped = true;
     try
     {
         statusUpdater.Join();
         RegisterWithRM();
         statusUpdater  = new Sharpen.Thread(statusUpdaterRunnable, "Node Status Updater");
         this.isStopped = false;
         statusUpdater.Start();
         Log.Info("NodeStatusUpdater thread is reRegistered and restarted");
     }
     catch (Exception e)
     {
         string errorMessage = "Unexpected error rebooting NodeStatusUpdater";
         Log.Error(errorMessage, e);
         throw new YarnRuntimeException(e);
     }
 }
Ejemplo n.º 33
0
 protected internal virtual void StartStatusUpdater()
 {
     statusUpdaterRunnable = new _Runnable_579(this);
     // Send heartbeat
     //get next heartbeat interval from response
     // Invalidate the RMIdentifier while resync
     // Explicitly put this method after checking the resync response. We
     // don't want to remove the completed containers before resync
     // because these completed containers will be reported back to RM
     // when NM re-registers with RM.
     // Only remove the cleanedup containers that are acked
     //Only start tracking for keepAlive on FINISH_APP
     //catch and throw the exception if tried MAX wait time to connect RM
     // TODO Better error handling. Thread can die with the rest of the
     // NM still running.
     // Do Nothing
     // See if the master-key has rolled over
     // Will be non-null only on roll-over on RM side
     statusUpdater = new Sharpen.Thread(statusUpdaterRunnable, "Node Status Updater");
     statusUpdater.Start();
 }
Ejemplo n.º 34
0
		public bool Start()
		{
			this.Error = null;
			string maskedRemoteWithoutCredentials = databaseURL.ToString();
			maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@", "://---:---@");
            // TODO: Replace Thread object with TPL.
            thread = new Sharpen.Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials);
			thread.Start();
			return true;
		}
Ejemplo n.º 35
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual int SetPortForwardingL(string boundaddress, int lport, string host
			, int rport, ServerSocketFactory ssf)
		{
			PortWatcher pw = PortWatcher.AddPort(this, boundaddress, lport, host, rport, ssf);
			Sharpen.Thread tmp = new Sharpen.Thread(pw);
			tmp.SetName("PortWatcher Thread for " + host);
			if (daemon_thread)
			{
				tmp.SetDaemon(daemon_thread);
			}
			tmp.Start();
			return pw.lport;
		}
Ejemplo n.º 36
0
		/// <exception cref="NSch.JSchException"></exception>
		public virtual void Connect(int connectTimeout)
		{
			if (isConnected)
			{
				throw new JSchException("session is already connected");
			}
			io = new IO();
			if (random == null)
			{
				try
				{
					Type c = Sharpen.Runtime.GetType(GetConfig("random"));
					random = (Random)(System.Activator.CreateInstance(c));
				}
				catch (Exception e)
				{
					throw new JSchException(e.ToString(), e);
				}
			}
			Packet.SetRandom(random);
			if (JSch.GetLogger().IsEnabled(Logger.INFO))
			{
				JSch.GetLogger().Log(Logger.INFO, "Connecting to " + host + " port " + port);
			}
			try
			{
				int i;
				int j;
				if (proxy == null)
				{
					InputStream @in;
					OutputStream @out;
					if (socket_factory == null)
					{
						socket = Util.CreateSocket(host, port, connectTimeout);
						@in = socket.GetInputStream();
						@out = socket.GetOutputStream();
					}
					else
					{
						socket = socket_factory.CreateSocket(host, port);
						@in = socket_factory.GetInputStream(socket);
						@out = socket_factory.GetOutputStream(socket);
					}
					//if(timeout>0){ socket.setSoTimeout(timeout); }
					socket.NoDelay = true;
					io.SetInputStream(@in);
					io.SetOutputStream(@out);
				}
				else
				{
					lock (proxy)
					{
						proxy.Connect(socket_factory, host, port, connectTimeout);
						io.SetInputStream(proxy.GetInputStream());
						io.SetOutputStream(proxy.GetOutputStream());
						socket = proxy.GetSocket();
					}
				}
				if (connectTimeout > 0 && socket != null)
				{
					socket.ReceiveTimeout = connectTimeout;
				}
				isConnected = true;
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Connection established");
				}
				jsch.AddSession(this);
				{
					// Some Cisco devices will miss to read '\n' if it is sent separately.
					byte[] foo = new byte[V_C.Length + 1];
					System.Array.Copy(V_C, 0, foo, 0, V_C.Length);
					foo[foo.Length - 1] = unchecked((byte)(byte)('\n'));
					io.Put(foo, 0, foo.Length);
				}
				while (true)
				{
					i = 0;
					j = 0;
					while (i < buf.buffer.Length)
					{
						j = io.GetByte();
						if (j < 0)
						{
							break;
						}
						buf.buffer[i] = unchecked((byte)j);
						i++;
						if (j == 10)
						{
							break;
						}
					}
					if (j < 0)
					{
						throw new JSchException("connection is closed by foreign host");
					}
					if (buf.buffer[i - 1] == 10)
					{
						// 0x0a
						i--;
						if (i > 0 && buf.buffer[i - 1] == 13)
						{
							// 0x0d
							i--;
						}
					}
					if (i <= 3 || ((i != buf.buffer.Length) && (buf.buffer[0] != 'S' || buf.buffer[1]
						 != 'S' || buf.buffer[2] != 'H' || buf.buffer[3] != '-')))
					{
						// It must not start with 'SSH-'
						//System.err.println(new String(buf.buffer, 0, i);
						continue;
					}
					if (i == buf.buffer.Length || i < 7 || (buf.buffer[4] == '1' && buf.buffer[6] != 
						'9'))
					{
						// SSH-1.99 or SSH-2.0
						// SSH-1.5
						throw new JSchException("invalid server's version string");
					}
					break;
				}
				V_S = new byte[i];
				System.Array.Copy(buf.buffer, 0, V_S, 0, i);
				//System.err.println("V_S: ("+i+") ["+new String(V_S)+"]");
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Remote version string: " + Util.Byte2str(V_S));
					JSch.GetLogger().Log(Logger.INFO, "Local version string: " + Util.Byte2str(V_C));
				}
				Send_kexinit();
				buf = Read(buf);
				if (buf.GetCommand() != SSH_MSG_KEXINIT)
				{
					in_kex = false;
					throw new JSchException("invalid protocol: " + buf.GetCommand());
				}
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_KEXINIT received");
				}
				KeyExchange kex = Receive_kexinit(buf);
				while (true)
				{
					buf = Read(buf);
					if (kex.GetState() == buf.GetCommand())
					{
						kex_start_time = Runtime.CurrentTimeMillis();
						bool result = kex.Next(buf);
						if (!result)
						{
							//System.err.println("verify: "+result);
							in_kex = false;
							throw new JSchException("verify: " + result);
						}
					}
					else
					{
						in_kex = false;
						throw new JSchException("invalid protocol(kex): " + buf.GetCommand());
					}
					if (kex.GetState() == KeyExchange.STATE_END)
					{
						break;
					}
				}
				try
				{
					CheckHost(host, port, kex);
				}
				catch (JSchException ee)
				{
					in_kex = false;
					throw;
				}
				Send_newkeys();
				// receive SSH_MSG_NEWKEYS(21)
				buf = Read(buf);
				//System.err.println("read: 21 ? "+buf.getCommand());
				if (buf.GetCommand() == SSH_MSG_NEWKEYS)
				{
					if (JSch.GetLogger().IsEnabled(Logger.INFO))
					{
						JSch.GetLogger().Log(Logger.INFO, "SSH_MSG_NEWKEYS received");
					}
					Receive_newkeys(buf, kex);
				}
				else
				{
					in_kex = false;
					throw new JSchException("invalid protocol(newkyes): " + buf.GetCommand());
				}
				bool auth = false;
				bool auth_cancel = false;
				UserAuth ua = null;
				try
				{
					Type c = Sharpen.Runtime.GetType(GetConfig("userauth.none"));
					ua = (UserAuth)(System.Activator.CreateInstance(c));
				}
				catch (Exception e)
				{
					throw new JSchException(e.ToString(), e);
				}
				auth = ua.Start(this);
				string cmethods = GetConfig("PreferredAuthentications");
				string[] cmethoda = Util.Split(cmethods, ",");
				string smethods = null;
				if (!auth)
				{
					smethods = ((UserAuthNone)ua).GetMethods();
					if (smethods != null)
					{
						smethods = smethods.ToLower();
					}
					else
					{
						// methods: publickey,password,keyboard-interactive
						//smethods="publickey,password,keyboard-interactive";
						smethods = cmethods;
					}
				}
				string[] smethoda = Util.Split(smethods, ",");
				int methodi = 0;
				while (true)
				{
					//System.err.println("methods: "+methods);
					while (!auth && cmethoda != null && methodi < cmethoda.Length)
					{
						string method = cmethoda[methodi++];
						bool acceptable = false;
						for (int k = 0; k < smethoda.Length; k++)
						{
							if (smethoda[k].Equals(method))
							{
								acceptable = true;
								break;
							}
						}
						if (!acceptable)
						{
							continue;
						}
						//System.err.println("  method: "+method);
						if (JSch.GetLogger().IsEnabled(Logger.INFO))
						{
							string str = "Authentications that can continue: ";
							for (int k_1 = methodi - 1; k_1 < cmethoda.Length; k_1++)
							{
								str += cmethoda[k_1];
								if (k_1 + 1 < cmethoda.Length)
								{
									str += ",";
								}
							}
							JSch.GetLogger().Log(Logger.INFO, str);
							JSch.GetLogger().Log(Logger.INFO, "Next authentication method: " + method);
						}
						ua = null;
						try
						{
							Type c = null;
							if (GetConfig("userauth." + method) != null)
							{
								c = Sharpen.Runtime.GetType(GetConfig("userauth." + method));
								ua = (UserAuth)(System.Activator.CreateInstance(c));
							}
						}
						catch (Exception)
						{
							if (JSch.GetLogger().IsEnabled(Logger.WARN))
							{
								JSch.GetLogger().Log(Logger.WARN, "failed to load " + method + " method");
							}
						}
						if (ua != null)
						{
							auth_cancel = false;
							try
							{
								auth = ua.Start(this);
								if (auth && JSch.GetLogger().IsEnabled(Logger.INFO))
								{
									JSch.GetLogger().Log(Logger.INFO, "Authentication succeeded (" + method + ").");
								}
							}
							catch (JSchAuthCancelException)
							{
								auth_cancel = true;
							}
							catch (JSchPartialAuthException ee)
							{
								string tmp = smethods;
								smethods = ee.GetMethods();
								smethoda = Util.Split(smethods, ",");
								if (!tmp.Equals(smethods))
								{
									methodi = 0;
								}
								//System.err.println("PartialAuth: "+methods);
								auth_cancel = false;
								goto loop_continue;
							}
							catch (RuntimeException ee)
							{
								throw;
							}
							catch (Exception)
							{
								//System.err.println("ee: "+ee); // SSH_MSG_DISCONNECT: 2 Too many authentication failures
								goto loop_break;
							}
						}
					}
					break;
loop_continue: ;
				}
loop_break: ;
				if (!auth)
				{
					if (auth_cancel)
					{
						throw new JSchException("Auth cancel");
					}
					throw new JSchException("Auth fail");
				}
				if (connectTimeout > 0 || timeout > 0)
				{
					socket.ReceiveTimeout = timeout;
				}
				isAuthed = true;
				lock (Lock)
				{
					if (isConnected)
					{
						connectThread = new Sharpen.Thread(this);
						connectThread.SetName("Connect thread " + host + " session");
						if (daemon_thread)
						{
							connectThread.SetDaemon(daemon_thread);
						}
						connectThread.Start();
					}
				}
			}
			catch (Exception e)
			{
				// The session has been already down and
				// we don't have to start new thread.
				in_kex = false;
				if (isConnected)
				{
					try
					{
						packet.Reset();
						buf.PutByte(unchecked((byte)SSH_MSG_DISCONNECT));
						buf.PutInt(3);
						buf.PutString(Util.Str2byte(e.ToString()));
						buf.PutString(Util.Str2byte("en"));
						Write(packet);
						Disconnect();
					}
					catch (Exception)
					{
					}
				}
				isConnected = false;
				//e.printStackTrace();
				if (e is RuntimeException)
				{
					throw (RuntimeException)e;
				}
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				throw new JSchException("Session.connect: " + e);
			}
			finally
			{
				Util.Bzero(this.password);
				this.password = null;
			}
		}
Ejemplo n.º 37
0
		/// <exception cref="System.Exception"></exception>
		public static void Run(ShellContextFactory shellContextFactory, FilePath jsFile, ShellTest.Parameters parameters, ShellTest.Status status)
		{
			Global global = new Global();
			MemoryStream @out = new MemoryStream();
			TextWriter p = new TextWriter(@out);
			global.SetOut(p);
			global.SetErr(p);
			global.DefineFunctionProperties(new string[] { "options" }, typeof(ShellTest), ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
			// test suite expects keywords to be disallowed as identifiers
			shellContextFactory.SetAllowReservedKeywords(false);
			ShellTest.TestState testState = new ShellTest.TestState();
			if (jsFile.GetName().EndsWith("-n.js"))
			{
				status.SetNegative();
			}
			Exception[] thrown = new Exception[] { null };
			Sharpen.Thread t = new Sharpen.Thread(new _Runnable_274(shellContextFactory, thrown, testState, status, jsFile, global), jsFile.GetPath());
			t.SetDaemon(true);
			t.Start();
			t.Join(parameters.GetTimeoutMilliseconds());
			lock (testState)
			{
				if (!testState.finished)
				{
					CallStop(t);
					status.TimedOut();
				}
			}
			int expectedExitCode = 0;
			p.Flush();
			status.OutputWas(Sharpen.Runtime.GetStringForBytes(@out.ToArray()));
			BufferedReader r = new BufferedReader(new StreamReader(new MemoryStream(@out.ToArray())));
			string failures = string.Empty;
			for (; ; )
			{
				string s = r.ReadLine();
				if (s == null)
				{
					break;
				}
				if (s.IndexOf("FAILED!") != -1)
				{
					failures += s + '\n';
				}
				int expex = s.IndexOf("EXPECT EXIT CODE ");
				if (expex != -1)
				{
					expectedExitCode = s[expex + "EXPECT EXIT CODE ".Length] - '0';
				}
			}
			if (thrown[0] != null)
			{
				status.Threw(thrown[0]);
			}
			status.ExitCodesWere(expectedExitCode, testState.exitCode);
			if (failures != string.Empty)
			{
				status.Failed(failures);
			}
		}
Ejemplo n.º 38
0
		public virtual void Run()
		{
			thread = this;
			byte[] foo;
			Buffer buf = new Buffer();
			Packet packet = new Packet(buf);
			int i = 0;
			Channel channel;
			int[] start = new int[1];
			int[] length = new int[1];
			KeyExchange kex = null;
			int stimeout = 0;
			try
			{
				while (isConnected && thread != null)
				{
					try
					{
						buf = Read(buf);
						stimeout = 0;
					}
					catch (ThreadInterruptedException ee)
					{
						if (!in_kex && stimeout < serverAliveCountMax)
						{
							SendKeepAliveMsg();
							stimeout++;
							continue;
						}
						throw;
					}
					int msgType = buf.GetCommand() & unchecked((int)(0xff));
					if (kex != null && kex.GetState() == msgType)
					{
						kex_start_time = Runtime.CurrentTimeMillis();
						bool result = kex.Next(buf);
						if (!result)
						{
							throw new JSchException("verify: " + result);
						}
						continue;
					}
					switch (msgType)
					{
						case SSH_MSG_KEXINIT:
						{
							//System.err.println("KEXINIT");
							kex = Receive_kexinit(buf);
							break;
						}

						case SSH_MSG_NEWKEYS:
						{
							//System.err.println("NEWKEYS");
							Send_newkeys();
							Receive_newkeys(buf, kex);
							kex = null;
							break;
						}

						case SSH_MSG_CHANNEL_DATA:
						{
							buf.GetInt();
							buf.GetByte();
							buf.GetByte();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							foo = buf.GetString(start, length);
							if (channel == null)
							{
								break;
							}
							if (length[0] == 0)
							{
								break;
							}
							try
							{
								channel.Write(foo, start[0], length[0]);
							}
							catch (Exception)
							{
								//System.err.println(e);
								try
								{
									channel.Disconnect();
								}
								catch (Exception)
								{
								}
								break;
							}
							int len = length[0];
							channel.SetLocalWindowSize(channel.lwsize - len);
							if (channel.lwsize < channel.lwsize_max / 2)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST));
								buf.PutInt(channel.GetRecipient());
								buf.PutInt(channel.lwsize_max - channel.lwsize);
								Write(packet);
								channel.SetLocalWindowSize(channel.lwsize_max);
							}
							break;
						}

						case SSH_MSG_CHANNEL_EXTENDED_DATA:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							buf.GetInt();
							// data_type_code == 1
							foo = buf.GetString(start, length);
							//System.err.println("stderr: "+new String(foo,start[0],length[0]));
							if (channel == null)
							{
								break;
							}
							if (length[0] == 0)
							{
								break;
							}
							channel.Write_ext(foo, start[0], length[0]);
							int len = length[0];
							channel.SetLocalWindowSize(channel.lwsize - len);
							if (channel.lwsize < channel.lwsize_max / 2)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST));
								buf.PutInt(channel.GetRecipient());
								buf.PutInt(channel.lwsize_max - channel.lwsize);
								Write(packet);
								channel.SetLocalWindowSize(channel.lwsize_max);
							}
							break;
						}

						case SSH_MSG_CHANNEL_WINDOW_ADJUST:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.AddRemoteWindowSize(buf.GetInt());
							break;
						}

						case SSH_MSG_CHANNEL_EOF:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								//channel.eof_remote=true;
								//channel.eof();
								channel.Eof_remote();
							}
							break;
						}

						case SSH_MSG_CHANNEL_CLOSE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								//	      channel.close();
								channel.Disconnect();
							}
							break;
						}

						case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
							}
							//break;
							int r = buf.GetInt();
							long rws = buf.GetUInt();
							int rps = buf.GetInt();
							channel.SetRemoteWindowSize(rws);
							channel.SetRemotePacketSize(rps);
							channel.SetRecipient(r);
							break;
						}

						case SSH_MSG_CHANNEL_OPEN_FAILURE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
							}
							//break;
							int reason_code = buf.GetInt();
							//foo=buf.getString();  // additional textual information
							//foo=buf.getString();  // language tag 
							channel.exitstatus = reason_code;
							channel.close = true;
							channel.eof_remote = true;
							channel.SetRecipient(0);
							break;
						}

						case SSH_MSG_CHANNEL_REQUEST:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							foo = buf.GetString();
							bool reply = (buf.GetByte() != 0);
							channel = Channel.GetChannel(i, this);
							if (channel != null)
							{
								byte reply_type = unchecked((byte)SSH_MSG_CHANNEL_FAILURE);
								if ((Util.Byte2str(foo)).Equals("exit-status"))
								{
									i = buf.GetInt();
									// exit-status
									channel.SetExitStatus(i);
									reply_type = unchecked((byte)SSH_MSG_CHANNEL_SUCCESS);
								}
								if (reply)
								{
									packet.Reset();
									buf.PutByte(reply_type);
									buf.PutInt(channel.GetRecipient());
									Write(packet);
								}
							}
							break;
						}

						case SSH_MSG_CHANNEL_OPEN:
						{
							buf.GetInt();
							buf.GetShort();
							foo = buf.GetString();
							string ctyp = Util.Byte2str(foo);
							if (!"forwarded-tcpip".Equals(ctyp) && !("x11".Equals(ctyp) && x11_forwarding) &&
								 !("*****@*****.**".Equals(ctyp) && agent_forwarding))
							{
								//System.err.println("Session.run: CHANNEL OPEN "+ctyp); 
								//throw new IOException("Session.run: CHANNEL OPEN "+ctyp);
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_CHANNEL_OPEN_FAILURE));
								buf.PutInt(buf.GetInt());
								buf.PutInt(Channel.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED);
								buf.PutString(Util.empty);
								buf.PutString(Util.empty);
								Write(packet);
							}
							else
							{
								channel = Channel.GetChannel(ctyp);
								AddChannel(channel);
								channel.GetData(buf);
								channel.Init();
								Sharpen.Thread tmp = new Sharpen.Thread(channel);
								tmp.SetName("Channel " + ctyp + " " + host);
								if (daemon_thread)
								{
									tmp.SetDaemon(daemon_thread);
								}
								tmp.Start();
								break;
							}
							goto case SSH_MSG_CHANNEL_SUCCESS;
						}

						case SSH_MSG_CHANNEL_SUCCESS:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.reply = 1;
							break;
						}

						case SSH_MSG_CHANNEL_FAILURE:
						{
							buf.GetInt();
							buf.GetShort();
							i = buf.GetInt();
							channel = Channel.GetChannel(i, this);
							if (channel == null)
							{
								break;
							}
							channel.reply = 0;
							break;
						}

						case SSH_MSG_GLOBAL_REQUEST:
						{
							buf.GetInt();
							buf.GetShort();
							foo = buf.GetString();
							// request name
							bool reply = (buf.GetByte() != 0);
							if (reply)
							{
								packet.Reset();
								buf.PutByte(unchecked((byte)SSH_MSG_REQUEST_FAILURE));
								Write(packet);
							}
							break;
						}

						case SSH_MSG_REQUEST_FAILURE:
						case SSH_MSG_REQUEST_SUCCESS:
						{
							Sharpen.Thread t = grr.GetThread();
							if (t != null)
							{
								grr.SetReply(msgType == SSH_MSG_REQUEST_SUCCESS ? 1 : 0);
								t.Interrupt();
							}
							break;
						}

						default:
						{
							//System.err.println("Session.run: unsupported type "+msgType); 
							throw new IOException("Unknown SSH message type " + msgType);
						}
					}
				}
			}
			catch (Exception e)
			{
				in_kex = false;
				if (JSch.GetLogger().IsEnabled(Logger.INFO))
				{
					JSch.GetLogger().Log(Logger.INFO, "Caught an exception, leaving main loop due to "
						 + e.Message);
				}
			}
			//System.err.println("# Session.run");
			//e.printStackTrace();
			try
			{
				Disconnect();
			}
			catch (ArgumentNullException)
			{
			}
			catch (Exception)
			{
			}
			//System.err.println("@1");
			//e.printStackTrace();
			//System.err.println("@2");
			//e.printStackTrace();
			isConnected = false;
		}
Ejemplo n.º 39
0
		/// <summary>Start this daemon on a background thread.</summary>
		/// <remarks>Start this daemon on a background thread.</remarks>
		/// <exception cref="System.IO.IOException">the server socket could not be opened.</exception>
		/// <exception cref="System.InvalidOperationException">the daemon is already running.
		/// 	</exception>
		public virtual void Start()
		{
			lock (this)
			{
				if (acceptThread != null)
				{
					throw new InvalidOperationException(JGitText.Get().daemonAlreadyRunning);
				}
				Socket listenSock = Sharpen.Extensions.CreateServerSocket(myAddress != null ? myAddress
					.Port : 0, BACKLOG, myAddress != null ? myAddress.Address : null);
				myAddress = (IPEndPoint)listenSock.LocalEndPoint;
				run = true;
				acceptThread = new _Thread_278(this, listenSock, processors, "Git-Daemon-Accept");
				// Test again to see if we should keep accepting.
				//
				acceptThread.Start();
			}
		}
Ejemplo n.º 40
0
		/// <exception cref="NSch.JSchException"></exception>
		public override void Start()
		{
			Session _session = GetSession();
			try
			{
				Request request;
				if (xforwading)
				{
					request = new RequestX11();
					request.DoRequest(_session, this);
				}
				if (pty)
				{
					request = new RequestPtyReq();
					request.DoRequest(_session, this);
				}
				request = new RequestSubsystem();
				((RequestSubsystem)request).Request(_session, this, subsystem, want_reply);
			}
			catch (Exception e)
			{
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				if (e is Exception)
				{
					throw new JSchException("ChannelSubsystem", (Exception)e);
				}
				throw new JSchException("ChannelSubsystem");
			}
			if (io.@in != null)
			{
				thread = new Sharpen.Thread(this);
				thread.SetName("Subsystem for " + _session.host);
				if (_session.daemon_thread)
				{
					thread.SetDaemon(_session.daemon_thread);
				}
				thread.Start();
			}
		}
Ejemplo n.º 41
0
		/// <exception cref="NSch.JSchException"></exception>
		public override void Connect()
		{
			try
			{
				Session _session = GetSession();
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				Buffer buf = new Buffer(150);
				Packet packet = new Packet(buf);
				// send
				// byte   SSH_MSG_CHANNEL_OPEN(90)
				// string channel type         //
				// uint32 sender channel       // 0
				// uint32 initial window size  // 0x100000(65536)
				// uint32 maxmum packet size   // 0x4000(16384)
				packet.Reset();
				buf.PutByte(unchecked((byte)90));
				buf.PutString(Util.Str2byte("direct-tcpip"));
				buf.PutInt(id);
				buf.PutInt(lwsize);
				buf.PutInt(lmpsize);
				buf.PutString(Util.Str2byte(host));
				buf.PutInt(port);
				buf.PutString(Util.Str2byte(originator_IP_address));
				buf.PutInt(originator_port);
				_session.Write(packet);
				int retry = 1000;
				try
				{
					while (this.GetRecipient() == -1 && _session.IsConnected() && retry > 0 && !eof_remote
						)
					{
						//Thread.sleep(500);
						Sharpen.Thread.Sleep(50);
						retry--;
					}
				}
				catch (Exception)
				{
				}
				if (!_session.IsConnected())
				{
					throw new JSchException("session is down");
				}
				if (retry == 0 || this.eof_remote)
				{
					throw new JSchException("channel is not opened.");
				}
				connected = true;
				if (io.@in != null)
				{
					thread = new Sharpen.Thread(this);
					thread.SetName("DirectTCPIP thread " + _session.GetHost());
					if (_session.daemon_thread)
					{
						thread.SetDaemon(_session.daemon_thread);
					}
					thread.Start();
				}
			}
			catch (Exception e)
			{
				io.Close();
				io = null;
				Channel.Del(this);
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
			}
		}
Ejemplo n.º 42
0
		/// <exception cref="NSch.JSchException"></exception>
		internal static Socket CreateSocket(string host, int port, int timeout)
		{
			Socket socket = null;
			if (timeout == 0)
			{
				try
				{
					socket = Sharpen.Extensions.CreateSocket(host, port);
					return socket;
				}
				catch (Exception e)
				{
					string message = e.ToString();
					if (e is Exception)
					{
						throw new JSchException(message, (Exception)e);
					}
					throw new JSchException(message);
				}
			}
			string _host = host;
			int _port = port;
			Socket[] sockp = new Socket[1];
			Exception[] ee = new Exception[1];
			string message_1 = string.Empty;
			Sharpen.Thread tmp = new Sharpen.Thread(new _Runnable_350(sockp, _host, _port, ee
				));
			tmp.SetName("Opening Socket " + host);
			tmp.Start();
			try
			{
				tmp.Join(timeout);
				message_1 = "timeout: ";
			}
			catch (Exception)
			{
			}
			if (sockp[0] != null && sockp[0].Connected)
			{
				socket = sockp[0];
			}
			else
			{
				message_1 += "socket is not established";
				if (ee[0] != null)
				{
					message_1 = ee[0].ToString();
				}
				tmp.Interrupt();
				tmp = null;
				throw new JSchException(message_1);
			}
			return socket;
		}
		/// <exception cref="System.Exception"></exception>
		private static void RunOnThread(Runnable task)
		{
			Sharpen.Thread t = new Sharpen.Thread(task);
			t.Start();
			t.Join(1000);
			NUnit.Framework.Assert.IsFalse(t.IsAlive(), "thread has stopped");
		}
Ejemplo n.º 44
0
		public virtual bool Start()
		{
			this.error = null;
			string maskedRemoteWithoutCredentials = databaseURL.ToExternalForm();
			maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@"
				, "://---:---@");
			thread = new Sharpen.Thread(this, "ChangeTracker-" + maskedRemoteWithoutCredentials
				);
			thread.Start();
			return true;
		}
Ejemplo n.º 45
0
		/// <summary>
		/// The spawn function runs a given function or script in a different
		/// thread.
		/// </summary>
		/// <remarks>
		/// The spawn function runs a given function or script in a different
		/// thread.
		/// js&gt; function g() { a = 7; }
		/// js&gt; a = 3;
		/// 3
		/// js&gt; spawn(g)
		/// Thread[Thread-1,5,main]
		/// js&gt; a
		/// 3
		/// </remarks>
		public static object Spawn(Context cx, Scriptable thisObj, object[] args, Function funObj)
		{
			Scriptable scope = funObj.GetParentScope();
			Runner runner;
			if (args.Length != 0 && args[0] is Function)
			{
				object[] newArgs = null;
				if (args.Length > 1 && args[1] is Scriptable)
				{
					newArgs = cx.GetElements((Scriptable)args[1]);
				}
				if (newArgs == null)
				{
					newArgs = ScriptRuntime.emptyArgs;
				}
				runner = new Runner(scope, (Function)args[0], newArgs);
			}
			else
			{
				if (args.Length != 0 && args[0] is Script)
				{
					runner = new Runner(scope, (Script)args[0]);
				}
				else
				{
					throw ReportRuntimeError("msg.spawn.args");
				}
			}
			runner.factory = cx.GetFactory();
			Sharpen.Thread thread = new Sharpen.Thread(runner);
			thread.Start();
			return thread;
		}