k8s.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package k8s
  15. import (
  16. "fmt"
  17. "net/http"
  18. "time"
  19. "k8s.io/client-go/kubernetes"
  20. "k8s.io/client-go/rest"
  21. "k8s.io/client-go/tools/clientcmd"
  22. "k8s.io/client-go/transport"
  23. )
  24. const (
  25. K8sWrapTransportTimeout = 30
  26. )
  27. type WrapTransport func(rt http.RoundTripper) http.RoundTripper
  28. func NewClientByFile(kubeConfigPath string, k8sWrapTransport WrapTransport) (*kubernetes.Clientset, error) {
  29. config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return kubernetes.NewForConfig(setConfigField(config, k8sWrapTransport))
  34. }
  35. func GetK8sClientConfig(kubeConfig []byte) (*rest.Config, error) {
  36. var config *rest.Config
  37. var err error
  38. if kubeConfig != nil {
  39. apiconfig, err := clientcmd.Load(kubeConfig)
  40. if err != nil {
  41. return nil, err
  42. }
  43. clientConfig := clientcmd.NewDefaultClientConfig(*apiconfig, &clientcmd.ConfigOverrides{})
  44. config, err = clientConfig.ClientConfig()
  45. if err != nil {
  46. return nil, err
  47. }
  48. } else {
  49. return nil, fmt.Errorf("kubeconfig value is nil")
  50. }
  51. if err != nil {
  52. return nil, fmt.Errorf("create kubernetes config failed: %v", err)
  53. }
  54. return config, nil
  55. }
  56. func NewClientByContent(kubeConfig []byte, k8sWrapTransport WrapTransport) (*kubernetes.Clientset, error) {
  57. config, err := GetK8sClientConfig(kubeConfig)
  58. if err != nil {
  59. return nil, fmt.Errorf("Create kubernetes config: %v", err)
  60. }
  61. return kubernetes.NewForConfig(setConfigField(config, k8sWrapTransport))
  62. }
  63. func setConfigField(c *rest.Config, tr WrapTransport) *rest.Config {
  64. if tr != nil {
  65. c.WrapTransport = transport.WrapperFunc(tr)
  66. }
  67. c.Timeout = time.Second * time.Duration(K8sWrapTransportTimeout)
  68. return c
  69. }