forked from aws/session-manager-plugin
/
sessionhandler.go
163 lines (141 loc) · 5.53 KB
/
sessionhandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
// Package session starts the session.
package session
import (
"fmt"
"math/rand"
"os"
"github.com/matipan/ssm/src/config"
"github.com/matipan/ssm/src/log"
"github.com/matipan/ssm/src/message"
"github.com/matipan/ssm/src/retry"
"github.com/matipan/ssm/src/sdkutil"
sdkSession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
)
// OpenDataChannel initializes datachannel
func (s *Session) OpenDataChannel(log log.T) (err error) {
s.retryParams = retry.RepeatableExponentialRetryer{
GeometricRatio: config.RetryBase,
InitialDelayInMilli: rand.Intn(config.DataChannelRetryInitialDelayMillis) + config.DataChannelRetryInitialDelayMillis,
MaxDelayInMilli: config.DataChannelRetryMaxIntervalMillis,
MaxAttempts: config.DataChannelNumMaxRetries,
}
s.DataChannel.Initialize(log, s.ClientId, s.SessionId, s.TargetId, s.IsAwsCliUpgradeNeeded)
s.DataChannel.SetWebsocket(log, s.StreamUrl, s.TokenValue)
s.DataChannel.GetWsChannel().SetOnMessage(
func(input []byte) {
s.DataChannel.OutputMessageHandler(log, s.Stop, s.SessionId, input)
})
s.DataChannel.RegisterOutputStreamHandler(s.ProcessFirstMessage, false)
if err = s.DataChannel.Open(log); err != nil {
log.Errorf("Retrying connection for data channel id: %s failed with error: %s", s.SessionId, err)
s.retryParams.CallableFunc = func() (err error) { return s.DataChannel.Reconnect(log) }
if err = s.retryParams.Call(); err != nil {
log.Error(err)
}
}
s.DataChannel.GetWsChannel().SetOnError(
func(err error) {
log.Errorf("Trying to reconnect the session: %v with seq num: %d", s.StreamUrl, s.DataChannel.GetStreamDataSequenceNumber())
s.retryParams.CallableFunc = func() (err error) { return s.ResumeSessionHandler(log) }
if err = s.retryParams.Call(); err != nil {
log.Error(err)
}
})
// Scheduler for resending of data
s.DataChannel.ResendStreamDataMessageScheduler(log)
return nil
}
// ProcessFirstMessage only processes messages with PayloadType Output to determine the
// sessionType of the session to be launched. This is a fallback for agent versions that do not support handshake, they
// immediately start sending shell output.
func (s *Session) ProcessFirstMessage(log log.T, outputMessage message.ClientMessage) (isHandlerReady bool, err error) {
// Immediately deregister self so that this handler is only called once, for the first message
s.DataChannel.DeregisterOutputStreamHandler(s.ProcessFirstMessage)
// Only set session type if the session type has not already been set. Usually session type will be set
// by handshake protocol which would be the first message but older agents may not perform handshake
if s.SessionType == "" {
if outputMessage.PayloadType == uint32(message.Output) {
log.Warn("Setting session type to shell based on PayloadType!")
s.DataChannel.SetSessionType(config.ShellPluginName)
s.DisplayMode.DisplayMessage(log, outputMessage)
}
}
return true, nil
}
// Stop will end the session
func (s *Session) Stop() {
os.Exit(0)
}
// GetResumeSessionParams calls ResumeSession API and gets tokenvalue for reconnecting
func (s *Session) GetResumeSessionParams(log log.T) (string, error) {
var (
resumeSessionOutput *ssm.ResumeSessionOutput
err error
sdkSession *sdkSession.Session
)
if sdkSession, err = sdkutil.GetNewSessionWithEndpoint(s.Endpoint); err != nil {
return "", err
}
s.sdk = ssm.New(sdkSession)
resumeSessionInput := ssm.ResumeSessionInput{
SessionId: &s.SessionId,
}
log.Debugf("Resume Session input parameters: %v", resumeSessionInput)
if resumeSessionOutput, err = s.sdk.ResumeSession(&resumeSessionInput); err != nil {
log.Errorf("Resume Session failed: %v", err)
return "", err
}
if resumeSessionOutput.TokenValue == nil {
return "", nil
}
return *resumeSessionOutput.TokenValue, nil
}
// ResumeSessionHandler gets token value and tries to Reconnect to datachannel
func (s *Session) ResumeSessionHandler(log log.T) (err error) {
s.TokenValue, err = s.GetResumeSessionParams(log)
if err != nil {
log.Errorf("Failed to get token: %v", err)
return
} else if s.TokenValue == "" {
log.Debugf("Session: %s timed out", s.SessionId)
fmt.Fprintf(os.Stdout, "Session: %s timed out.\n", s.SessionId)
os.Exit(0)
}
s.DataChannel.GetWsChannel().SetChannelToken(s.TokenValue)
err = s.DataChannel.Reconnect(log)
return
}
// TerminateSession calls TerminateSession API
func (s *Session) TerminateSession(log log.T) error {
var (
err error
newSession *sdkSession.Session
)
if newSession, err = sdkutil.GetNewSessionWithEndpoint(s.Endpoint); err != nil {
log.Errorf("Terminate Session failed: %v", err)
return err
}
s.sdk = ssm.New(newSession)
terminateSessionInput := ssm.TerminateSessionInput{
SessionId: &s.SessionId,
}
log.Debugf("Terminate Session input parameters: %v", terminateSessionInput)
if _, err = s.sdk.TerminateSession(&terminateSessionInput); err != nil {
log.Errorf("Terminate Session failed: %v", err)
return err
}
return nil
}