37 Star 411 Fork 76

GVPrancher/rancher

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
gke_capabilities.go 2.52 KB
一键复制 编辑 原始数据 按行查看 历史
Nathan Jenan 提交于 2018-01-19 22:04 . Fixing lint, fmt issues
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))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rancher/rancher.git
git@gitee.com:rancher/rancher.git
rancher
rancher
rancher
v2.0.0-rc3

搜索帮助

0d507c66 1850385 C8b1a773 1850385