@@ -4,11 +4,13 @@ import (
44 "encoding/json"
55 "errors"
66 "strings"
7+ "sync"
78
89 "net"
910 "strconv"
1011 "time"
1112
13+ comm "github.com/cloud-barista/cm-cicada/common"
1214 "github.com/cloud-barista/cm-cicada/lib/config"
1315 "github.com/cloud-barista/cm-cicada/pkg/api/rest/common"
1416 "github.com/cloud-barista/cm-cicada/pkg/api/rest/model"
@@ -18,10 +20,12 @@ import (
1820
1921type Client struct {
2022 * goph.Client
21- SSHTarget * model.SSHTarget
22- nsID string
23- mciID string
24- id string
23+ SSHTarget * model.SSHTarget
24+ nsID string
25+ mciID string
26+ id string
27+ keepAliveStop chan struct {}
28+ keepAliveOnce sync.Once
2529}
2630
2731func (c * Client ) NewSessionWithRetry () (* ssh.Session , error ) {
@@ -61,6 +65,37 @@ func (c *Client) NewSessionWithRetry() (*ssh.Session, error) {
6165 return nil , err
6266}
6367
68+ func (c * Client ) startKeepAlive () {
69+ c .keepAliveOnce .Do (func () {
70+ c .keepAliveStop = make (chan struct {})
71+ go func () {
72+ ticker := time .NewTicker (1 * time .Second )
73+ defer ticker .Stop ()
74+
75+ for {
76+ select {
77+ case <- ticker .C :
78+ if c .Client != nil {
79+ _ , _ , _ = c .SendRequest ("keepalive@" + comm .ShortModuleName , true , nil )
80+ }
81+ case <- c .keepAliveStop :
82+ return
83+ }
84+ }
85+ }()
86+ })
87+ }
88+
89+ func (c * Client ) Close () error {
90+ if c .keepAliveStop != nil {
91+ close (c .keepAliveStop )
92+ }
93+ if c .Client != nil {
94+ return c .Client .Close ()
95+ }
96+ return nil
97+ }
98+
6499func AddKnownHost (host string , remote net.Addr , key ssh.PublicKey ) error {
65100 hostFound , _ := goph .CheckKnownHost (host , remote , key , "" )
66101
@@ -146,11 +181,16 @@ func NewSSHClient(nsID string, mciID string, vmID string) (*Client, error) {
146181 PrivateKey : sshKeyInfo .PrivateKey ,
147182 }
148183
149- return & Client {
184+ sshClient := & Client {
150185 Client : client ,
151186 SSHTarget : sshTarget ,
152187 nsID : nsID ,
153188 mciID : mciID ,
154189 id : vmID ,
155- }, nil
190+ }
191+
192+ // Start SSH KeepAlive to prevent connection timeout
193+ sshClient .startKeepAlive ()
194+
195+ return sshClient , nil
156196}
0 commit comments