forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gke_capabilities.go
114 lines (91 loc) · 2.52 KB
/
gke_capabilities.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
package capabilities
import (
"context"
"encoding/json"
"fmt"
"github.com/rancher/kontainer-engine/drivers/gke"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/container/v1"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
type capabilitiesRequestBody struct {
Credentials string `json:"credentials"`
ProjectID string `json:"projectId"`
}
func validateRequestBody(writer http.ResponseWriter, body *capabilitiesRequestBody) error {
credentials := body.Credentials
projectID := body.ProjectID
if projectID == "" {
writer.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("invalid projectId")
}
if credentials == "" {
writer.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("invalid credentials")
}
return nil
}
func extractRequestBody(writer http.ResponseWriter, req *http.Request, body interface{}) error {
raw, err := ioutil.ReadAll(req.Body)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("cannot read request body: " + err.Error())
}
err = json.Unmarshal(raw, &body)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return fmt.Errorf("cannot parse request body: " + err.Error())
}
return nil
}
func getOAuthClient(ctx context.Context, credentialContent string) (*http.Client, error) {
// The google SDK has no sane way to pass in a TokenSource give all the different types (user, service account, etc)
// So we actually set an environment variable and then unset it
gke.EnvMutex.Lock()
locked := true
setEnv := false
cleanup := func() {
if setEnv {
os.Unsetenv(defaultCredentialEnv)
}
if locked {
gke.EnvMutex.Unlock()
locked = false
}
}
defer cleanup()
file, err := ioutil.TempFile("", "credential-file")
if err != nil {
return nil, err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := io.Copy(file, strings.NewReader(credentialContent)); err != nil {
return nil, err
}
setEnv = true
os.Setenv(defaultCredentialEnv, file.Name())
ts, err := google.DefaultTokenSource(ctx, container.CloudPlatformScope)
if err != nil {
return nil, err
}
// Unlocks
cleanup()
return oauth2.NewClient(ctx, ts), nil
}
func handleErr(writer http.ResponseWriter, originalErr error) {
resp := errorResponse{originalErr.Error()}
asJSON, err := json.Marshal(resp)
if err != nil {
logrus.Error("error while marshalling error message '" + originalErr.Error() + "' error was '" + err.Error() + "'")
writer.Write([]byte(err.Error()))
return
}
writer.Write([]byte(asJSON))
}