dacr / jassh

High level scala SSH API for easy and fast operations on remote servers.
Apache License 2.0
71 stars 27 forks source link

How does the resource of the connection get managed? #5

Closed PhilAndrew closed 10 years ago

PhilAndrew commented 10 years ago

Can you explain how the resource of the connection is managed?

Lets say I have a class with a method doWork and this method does SSH commands frequently and gets called frequently, I think I should make a member of this class as a lazy val as:

lazy val ssh = SSH(?, ?, ?)

I am expecting that when I go to use ssh the first time, it will open the connection, then since the object is around as a member of this class, it will keep using the same connection.

Is this how it works?

What if I kept re-creating the SSH(...), would it cache the connection?

dacr commented 10 years ago

If you use the factories (object apply methods), it will be up to you to close the resource using close method, like that:

val ssh= SSH(host="localhost", username="test")
try {
  ssh.execute("ls")
} finally {ssh.close()}

But SSH object brings helper methods that auto-close resource for you :

val result = SSH.once(host="localhost", username="test") { ssh =>
  ssh.execute("ls")
}

Another one, with a persited shell session

val result = SSH.shell(host="localhost", username="test") {sh =>
   s"""My name is ${sh.execute("hostname")} and my uptime is ${sh.execute("uptime")}"""
}

In that last case, both commands hostname and uptime are executed within the same shell, the proof :

val result = SSH.shell(host="localhost", username="test") {sh =>
  sh.execute("HELLO=`hostname`")
  sh.execute("echo hello $HELLO")
}

You can also define such function in order to use your own safe autoclose mechanism :

def using[R, T<%{def close()}](getres: =>T)(proc : T => R):R = {
   val res=getres
   try {proc(res)} finally {res.close}
}

val result = using(SSH(host="localhost", username="test")) { ssh =>
  ssh.execute("ls")
}