forked from redhat-developer/web-terminal-exec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperations.go
More file actions
173 lines (156 loc) · 5.42 KB
/
Copy pathoperations.go
File metadata and controls
173 lines (156 loc) · 5.42 KB
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
// Copyright (c) 2019-2025 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
package operations
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"github.com/redhat-developer/web-terminal-exec/pkg/config"
authenticationv1 "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
)
func StopDevWorkspace(devworkspaceClient dynamic.Interface) error {
stopWorkspacePatch := &unstructured.Unstructured{
Object: map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
"controller.devfile.io/stopped-by": "inactivity",
},
},
"spec": map[string]interface{}{
"started": false,
},
},
}
patchJSON, err := stopWorkspacePatch.MarshalJSON()
if err != nil {
return err
}
_, err = devworkspaceClient.Resource(devworkspaceGVR).Namespace(config.DevWorkspaceNamespace).Patch(context.TODO(), config.DevWorkspaceName, types.MergePatchType, patchJSON, v1.PatchOptions{})
if err != nil {
return fmt.Errorf("failed to patch DevWorkspace: %s", err)
}
return nil
}
func ExecCommandInPod(client kubernetes.Interface, restconfig *rest.Config, podName, containerName, command string) (stdout, stderr *bytes.Buffer, err error) {
req := client.CoreV1().RESTClient().
Post().
Namespace(config.DevWorkspaceNamespace).
Resource("pods").
Name(podName).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: containerName,
Command: []string{"/bin/sh"},
Stdout: true,
Stderr: true,
Stdin: true,
TTY: false,
}, scheme.ParameterCodec)
executor, err := NewSPDYExecutor(restconfig, "POST", req.URL())
if err != nil {
return nil, nil, fmt.Errorf("error setting up executor for command: %s", err)
}
input := strings.NewReader(command)
var outBuf, errBuf bytes.Buffer
if err := executor.Stream(remotecommand.StreamOptions{
Stdin: input,
Stdout: &outBuf,
Stderr: &errBuf,
}); err != nil {
return &outBuf, &errBuf, fmt.Errorf("error executing command in container: %s", err)
}
return &outBuf, &errBuf, nil
}
func GetCurrentWorkspacePod(client kubernetes.Interface) (*corev1.Pod, error) {
filterOptions := metav1.ListOptions{LabelSelector: config.PodSelector, FieldSelector: "status.phase=Running"}
podList, err := client.CoreV1().Pods(config.DevWorkspaceNamespace).List(context.TODO(), filterOptions)
if err != nil {
return nil, fmt.Errorf("failed to list pods in namespace '%s': %s", config.DevWorkspaceNamespace, err)
}
switch len(podList.Items) {
case 0:
return nil, fmt.Errorf("no workspace pods found in namespace '%s'", config.DevWorkspaceNamespace)
case 1:
return &podList.Items[0], nil
default:
// Multiple pods found -- try to get pod that exec is running in; may occur if dedicated pods are used
// Workaround as current pod name is not available -- hostname is substitute
podName := os.Getenv("HOSTNAME")
if podName == "" {
return &podList.Items[0], nil
}
for idx, pod := range podList.Items {
if pod.Name == podName {
return &podList.Items[idx], nil
}
}
return nil, fmt.Errorf("failed to get current workspace pod")
}
}
func GetCurrentUserUID(token string, clientProvider ClientProvider) (string, error) {
uid, err := getCurrentUserUIDFromOpenShiftUserAPI(token, clientProvider)
if err == nil {
return uid, nil
}
// Fall back to SelfSubjectReview on clusters where the OpenShift User API is unavailable
// (e.g. BYO external authentication without user.openshift.io).
uid, fallbackErr := getCurrentUserUIDFromSelfSubjectReview(token, clientProvider)
if fallbackErr == nil {
return uid, nil
}
return "", fmt.Errorf(
"failed to get current user information: OpenShift User API error: %w; SelfSubjectReview error: %w",
err,
fallbackErr,
)
}
func getCurrentUserUIDFromSelfSubjectReview(token string, clientProvider ClientProvider) (string, error) {
client, _, err := clientProvider.NewClientWithToken(token)
if err != nil {
return "", fmt.Errorf("failed to create client to check user info: %w", err)
}
review, err := client.AuthenticationV1().SelfSubjectReviews().Create(
context.Background(),
&authenticationv1.SelfSubjectReview{},
metav1.CreateOptions{},
)
if err != nil {
return "", err
}
if review.Status.UserInfo.UID == "" {
return "", fmt.Errorf("SelfSubjectReview returned empty UID")
}
return review.Status.UserInfo.UID, nil
}
func getCurrentUserUIDFromOpenShiftUserAPI(token string, clientProvider ClientProvider) (string, error) {
userClient, _, err := clientProvider.NewOpenShiftUserClient(token)
if err != nil {
return "", err
}
userInfo, err := userClient.Resource(userGVR).Namespace("").Get(context.Background(), "~", metav1.GetOptions{})
if err != nil {
return "", err
}
// kube:admin / kubeadmin have no Kubernetes UID; empty string is a valid identifier
// when AUTHENTICATED_USER_ID is also empty (see config.AuthenticatedUserID).
return string(userInfo.GetUID()), nil
}