@@ -19,9 +19,11 @@ import (
1919 "net/http"
2020 "net/http/httputil"
2121 "net/url"
22+ "os"
2223 "strings"
2324 "time"
2425
26+ "github.com/v3io/sidecar-proxy/pkg/common"
2527 "github.com/v3io/sidecar-proxy/pkg/sidecarproxy/metricshandler"
2628 "github.com/v3io/sidecar-proxy/pkg/sidecarproxy/metricshandler/abstract"
2729
@@ -85,6 +87,8 @@ func (n *metricsHandler) Start() error {
8587 return errors .Wrap (err , "Failed to initiate proxy" )
8688 }
8789
90+ go n .monitorSSHConnection ()
91+
8892 // adds one data point on service initialization so metric will be initialized and queryable
8993 n .incrementMetric ()
9094 return nil
@@ -145,3 +149,41 @@ func (n *metricsHandler) forwardRequest(res http.ResponseWriter, req *http.Reque
145149 n .proxy .ServeHTTP (res , req )
146150 return nil
147151}
152+
153+ // monitorSSHConnection runs in a goroutine and checks if the ssh connection is still alive, by reading a file shared
154+ // between the sidecar and main container.
155+ func (n * metricsHandler ) monitorSSHConnection () {
156+ filePath := metricshandler .OpenSSHConnectionFilePath
157+
158+ n .Logger .Info ("Starting SSH connection monitor" , "filePath" , filePath )
159+
160+ // create a ticker that will check the file every 10 seconds
161+ ticker := time .NewTicker (10 * time .Second )
162+ for range ticker .C {
163+
164+ // if the file doesn't exist, do nothing
165+ if exists , err := common .FileExists (filePath ); ! exists {
166+ if err != nil {
167+ n .Logger .WarnWith ("Failed to check if file exists" , "err" , err )
168+ }
169+ continue
170+ }
171+
172+ // file exists, read it
173+ contentBytes , err := os .ReadFile (filePath )
174+ if err != nil {
175+ n .Logger .WarnWith ("Failed to read file" , "err" , err )
176+ continue
177+ }
178+
179+ // convert content to a 'string'
180+ content := strings .TrimSpace (string (contentBytes ))
181+
182+ // if it contains "1", the connection is alive - increment the metric
183+ // otherwise, do nothing
184+ if content == metricshandler .SSHConnectionIsAlive {
185+ n .Logger .Debug ("SSH connection is alive, incrementing metric" )
186+ n .incrementMetric ()
187+ }
188+ }
189+ }
0 commit comments