/
psql.go
192 lines (156 loc) · 4.51 KB
/
psql.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
/*
Copyright The CloudNativePG Contributors
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 psql
import (
"context"
"fmt"
"os"
"os/exec"
"syscall"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/cloudnative-pg/cloudnative-pg/internal/cmd/plugin"
"github.com/cloudnative-pg/cloudnative-pg/pkg/specs"
"github.com/cloudnative-pg/cloudnative-pg/pkg/utils"
)
const (
// kubectlCommand is used to execute a command inside a Pod
kubectlCommand = "kubectl"
)
// Command is the launcher of `psql` with `kubectl exec`
type Command struct {
CommandOptions
// The list of possible pods where to launch psql
podList []corev1.Pod
// The path of kubectl
kubectlPath string
}
// CommandOptions are the options required to start psql
type CommandOptions struct {
// Require a connection to a Replica
Replica bool
// The cluster Name
Name string
// The Namespace where we're working in
Namespace string
// Whether we should we allocate a TTY for psql
AllocateTTY bool
// Whether we should we pass stdin to psql
PassStdin bool
// Arguments to pass to psql
Args []string
}
// NewCommand creates a new psql command
func NewCommand(
ctx context.Context,
options CommandOptions,
) (*Command, error) {
var pods corev1.PodList
if err := plugin.Client.List(
ctx,
&pods,
client.MatchingLabels{utils.ClusterLabelName: options.Name},
client.InNamespace(plugin.Namespace),
); err != nil {
return nil, err
}
kubectlPath, err := exec.LookPath(kubectlCommand)
if err != nil {
return nil, fmt.Errorf("while getting kubectl path: %w", err)
}
return &Command{
CommandOptions: options,
podList: pods.Items,
kubectlPath: kubectlPath,
}, nil
}
// getKubectlInvocation gets the kubectl command to be executed
func (psql *Command) getKubectlInvocation() ([]string, error) {
result := make([]string, 0, 11+len(psql.Args))
result = append(result, "kubectl", "exec")
if psql.AllocateTTY {
result = append(result, "-t")
}
if psql.PassStdin {
result = append(result, "-i")
}
if len(psql.Namespace) > 0 {
result = append(result, "-n", psql.Namespace)
}
result = append(result, "-c", specs.PostgresContainerName)
podName, err := psql.getPodName()
if err != nil {
return nil, err
}
result = append(result, podName)
result = append(result, "--", "psql")
result = append(result, psql.Args...)
return result, nil
}
// getPodName get the first Pod name with the required role
func (psql *Command) getPodName() (string, error) {
targetPodRole := specs.ClusterRoleLabelPrimary
if psql.Replica {
targetPodRole = specs.ClusterRoleLabelReplica
}
for i := range psql.podList {
podRole, _ := utils.GetInstanceRole(psql.podList[i].Labels)
if podRole == targetPodRole {
return psql.podList[i].Name, nil
}
}
return "", &ErrMissingPod{role: targetPodRole}
}
// Exec replaces the current process with a `kubectl Exec` invocation.
// This function won't return
func (psql *Command) Exec() error {
kubectlExec, err := psql.getKubectlInvocation()
if err != nil {
return err
}
err = syscall.Exec(psql.kubectlPath, kubectlExec, os.Environ()) // #nosec
if err != nil {
return err
}
return nil
}
// Run starts a psql process inside the target pod
func (psql *Command) Run() error {
kubectlExec, err := psql.getKubectlInvocation()
if err != nil {
return err
}
cmd := exec.Command(psql.kubectlPath, kubectlExec[1:]...) // nolint:gosec
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// Output starts a psql process inside the target pod
// and returns its stdout
func (psql *Command) Output() ([]byte, error) {
kubectlExec, err := psql.getKubectlInvocation()
if err != nil {
return nil, err
}
cmd := exec.Command(psql.kubectlPath, kubectlExec[1:]...) // nolint:gosec
cmd.Stderr = os.Stderr
return cmd.Output()
}
// ErrMissingPod is raised when we can't find a Pod having the desired role
type ErrMissingPod struct {
role string
}
// Error implements the error interface
func (err *ErrMissingPod) Error() string {
return fmt.Sprintf("cannot find Pod with role \"%s\"", err.role)
}