client.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // +build kube
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package client
  15. import (
  16. "context"
  17. "encoding/json"
  18. "fmt"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/cli-runtime/pkg/genericclioptions"
  22. "k8s.io/client-go/kubernetes"
  23. "github.com/docker/compose-cli/api/compose"
  24. )
  25. // KubeClient API to access kube objects
  26. type KubeClient struct {
  27. client *kubernetes.Clientset
  28. }
  29. // NewKubeClient new kubernetes client
  30. func NewKubeClient(config genericclioptions.RESTClientGetter) (*KubeClient, error) {
  31. restConfig, err := config.ToRESTConfig()
  32. if err != nil {
  33. return nil, err
  34. }
  35. clientset, err := kubernetes.NewForConfig(restConfig)
  36. if err != nil {
  37. return nil, err
  38. }
  39. return &KubeClient{
  40. client: clientset,
  41. }, nil
  42. }
  43. // GetContainers get containers for a given compose project
  44. func (kc KubeClient) GetContainers(ctx context.Context, projectName string, all bool) ([]compose.ContainerSummary, error) {
  45. pods, err := kc.client.CoreV1().Pods("").List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", compose.ProjectTag, projectName)})
  46. if err != nil {
  47. return nil, err
  48. }
  49. json, _ := json.MarshalIndent(pods, "", " ")
  50. fmt.Println(string(json))
  51. fmt.Printf("containers: %d\n", len(pods.Items))
  52. result := []compose.ContainerSummary{}
  53. for _, pod := range pods.Items {
  54. result = append(result, podToContainerSummary(pod))
  55. }
  56. return result, nil
  57. }
  58. func podToContainerSummary(pod v1.Pod) compose.ContainerSummary {
  59. return compose.ContainerSummary{
  60. ID: pod.GetObjectMeta().GetName(),
  61. Name: pod.GetObjectMeta().GetName(),
  62. Service: pod.GetObjectMeta().GetLabels()[compose.ServiceTag],
  63. State: string(pod.Status.Phase),
  64. Project: pod.GetObjectMeta().GetLabels()[compose.ProjectTag],
  65. }
  66. }