/
controller.go
245 lines (208 loc) · 7.42 KB
/
controller.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright © 2023 Horizoncd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License 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 terminal
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"strconv"
"strings"
"k8s.io/client-go/tools/remotecommand"
herrors "github.com/horizoncd/horizon/core/errors"
applicationmanager "github.com/horizoncd/horizon/pkg/application/manager"
"github.com/horizoncd/horizon/pkg/cluster/gitrepo"
"github.com/horizoncd/horizon/pkg/cluster/kubeclient"
clustermanager "github.com/horizoncd/horizon/pkg/cluster/manager"
envmanager "github.com/horizoncd/horizon/pkg/environment/manager"
envregionmanager "github.com/horizoncd/horizon/pkg/environmentregion/manager"
perror "github.com/horizoncd/horizon/pkg/errors"
"github.com/horizoncd/horizon/pkg/param"
regionmanager "github.com/horizoncd/horizon/pkg/region/manager"
trmanager "github.com/horizoncd/horizon/pkg/templaterelease/manager"
"github.com/horizoncd/horizon/pkg/util/errors"
"github.com/horizoncd/horizon/pkg/util/wlog"
"gopkg.in/igm/sockjs-go.v3/sockjs"
)
type Controller interface {
GetTerminalID(ctx context.Context, clusterID uint, podName, containerName string) (*SessionIDResp, error)
GetSockJSHandler(ctx context.Context, sessionID string) (http.Handler, error)
// CreateShell returns sessionID and sockJSHandler according to clusterID,podName,containerName
CreateShell(ctx context.Context, clusterID uint, podName, containerName string) (sessionID string,
sockJSHandler http.Handler, err error)
}
type controller struct {
kubeClientFty kubeclient.Factory
clusterMgr clustermanager.Manager
applicationMgr applicationmanager.Manager
templateReleaseMgr trmanager.Manager
envMgr envmanager.Manager
envRegionMgr envregionmanager.Manager
regionMgr regionmanager.Manager
clusterGitRepo gitrepo.ClusterGitRepo
}
var _ Controller = (*controller)(nil)
func NewController(param *param.Param) Controller {
return &controller{
kubeClientFty: kubeclient.Fty,
clusterMgr: param.ClusterMgr,
applicationMgr: param.ApplicationMgr,
templateReleaseMgr: param.TemplateReleaseMgr,
envMgr: param.EnvMgr,
envRegionMgr: param.EnvRegionMgr,
regionMgr: param.RegionMgr,
clusterGitRepo: param.ClusterGitRepo,
}
}
func (c *controller) GetTerminalID(ctx context.Context, clusterID uint, podName,
containerName string) (*SessionIDResp, error) {
const op = "terminal: get terminal id"
defer wlog.Start(ctx, op).StopPrint()
sessionID := &SessionIDResp{}
randomID, err := genRandomID()
if err != nil {
return nil, err
}
sessionID.ID = genSessionID(clusterID, podName, containerName, randomID)
return sessionID, nil
}
func (c *controller) GetSockJSHandler(ctx context.Context, sessionID string) (http.Handler, error) {
const op = "terminal: get sockjs handler"
defer wlog.Start(ctx, op).StopPrint()
clusterID, podName, containerName, randomID, err := parseSessionID(sessionID)
if err != nil {
return nil, errors.E(op, err)
}
cluster, err := c.clusterMgr.GetByID(ctx, clusterID)
if err != nil {
return nil, err
}
application, err := c.applicationMgr.GetByID(ctx, cluster.ApplicationID)
if err != nil {
return nil, err
}
regionEntity, err := c.regionMgr.GetRegionEntity(ctx, cluster.RegionName)
if err != nil {
return nil, err
}
kubeConfig, kubeClient, err := c.kubeClientFty.GetByK8SServer(regionEntity.Server, regionEntity.Certificate)
if err != nil {
return nil, err
}
tr, err := c.templateReleaseMgr.GetByTemplateNameAndRelease(ctx, cluster.Template, cluster.TemplateRelease)
if err != nil {
return nil, err
}
envValue, err := c.clusterGitRepo.GetEnvValue(ctx, application.Name, cluster.Name, tr.ChartName)
if err != nil {
return nil, err
}
ref := ContainerRef{
Environment: cluster.EnvironmentName,
Cluster: cluster.Name,
ClusterID: cluster.ID,
Namespace: envValue.Namespace,
Pod: podName,
Container: containerName,
RandomID: randomID,
}
terminalSessions.Set(ref.String(), Session{
id: ref.String(),
bound: make(chan error),
sizeChan: make(chan remotecommand.TerminalSize),
})
go WaitForTerminal(kubeClient.Basic, kubeConfig, ref)
handler := sockjs.NewHandler("/apis/front/v1", sockjs.DefaultOptions, handleTerminalSession)
return handler, nil
}
func (c *controller) CreateShell(ctx context.Context, clusterID uint, podName,
containerName string) (string, http.Handler, error) {
const op = "terminal controller: create shell"
defer wlog.Start(ctx, op).StopPrint()
cluster, err := c.clusterMgr.GetByID(ctx, clusterID)
if err != nil {
return "", nil, err
}
application, err := c.applicationMgr.GetByID(ctx, cluster.ApplicationID)
if err != nil {
return "", nil, err
}
regionEntity, err := c.regionMgr.GetRegionEntity(ctx, cluster.RegionName)
if err != nil {
return "", nil, err
}
kubeConfig, kubeClient, err := c.kubeClientFty.GetByK8SServer(regionEntity.Server, regionEntity.Certificate)
if err != nil {
return "", nil, err
}
tr, err := c.templateReleaseMgr.GetByTemplateNameAndRelease(ctx, cluster.Template, cluster.TemplateRelease)
if err != nil {
return "", nil, err
}
envValue, err := c.clusterGitRepo.GetEnvValue(ctx, application.Name, cluster.Name, tr.ChartName)
if err != nil {
return "", nil, err
}
// Generate a random number as the session id
randomID, err := genRandomID()
if err != nil {
return "", nil, err
}
ref := ContainerRef{
Environment: cluster.EnvironmentName,
Cluster: cluster.Name,
ClusterID: cluster.ID,
Namespace: envValue.Namespace,
Pod: podName,
Container: containerName,
RandomID: randomID,
}
terminalSessions.Set(ref.String(), Session{
id: ref.String(),
bound: make(chan error),
sizeChan: make(chan remotecommand.TerminalSize),
})
handler := sockjs.NewHandler("/apis/core/v1", sockjs.DefaultOptions, handleShellSession(ctx, ref.String()))
go WaitForTerminal(kubeClient.Basic, kubeConfig, ref)
return randomID, handler, nil
}
func genRandomID() (string, error) {
bytes := make([]byte, 5)
if _, err := rand.Read(bytes); err != nil {
return "", perror.Wrap(herrors.ErrGenerateRandomID, err.Error())
}
id := make([]byte, hex.EncodedLen(len(bytes)))
hex.Encode(id, bytes)
return string(id), nil
}
func genSessionID(clusterID uint, podName, containerName, randomID string) string {
return fmt.Sprintf("%d:%s:%s:%s", clusterID, podName, containerName, randomID)
}
func parseSessionID(sessionID string) (clusterID uint, podName string, containerName string, randomID string,
err error) {
parts := strings.Split(sessionID, ":")
if len(parts) != 4 {
return clusterID, podName, containerName, randomID, fmt.Errorf("invalid sessionID")
}
clusterIDInt64, err := strconv.ParseUint(parts[0], 10, 0)
if err != nil {
return clusterID, podName, containerName, randomID, err
}
clusterID = uint(clusterIDInt64)
podName = parts[1]
containerName = parts[2]
randomID = parts[3]
return clusterID, podName, containerName, randomID, nil
}