agent.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package kubernetes
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "github.com/gorilla/websocket"
  8. v1 "k8s.io/api/core/v1"
  9. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  10. "k8s.io/cli-runtime/pkg/genericclioptions"
  11. "k8s.io/client-go/kubernetes"
  12. )
  13. // Agent is a Kubernetes agent for performing operations that interact with the
  14. // api server
  15. type Agent struct {
  16. RESTClientGetter genericclioptions.RESTClientGetter
  17. Clientset kubernetes.Interface
  18. }
  19. // ListNamespaces simply lists namespaces
  20. func (a *Agent) ListNamespaces() (*v1.NamespaceList, error) {
  21. return a.Clientset.CoreV1().Namespaces().List(
  22. context.TODO(),
  23. metav1.ListOptions{},
  24. )
  25. }
  26. // GetPodsByLabel retrieves pods with matching labels
  27. func (a *Agent) GetPodsByLabel(selector string) (*v1.PodList, error) {
  28. // Search in all namespaces for matching pods
  29. return a.Clientset.CoreV1().Pods("").List(
  30. context.TODO(),
  31. metav1.ListOptions{
  32. LabelSelector: selector,
  33. },
  34. )
  35. }
  36. // GetPodLogs streams real-time logs from a given pod.
  37. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  38. // follow logs
  39. tails := int64(30)
  40. podLogOpts := v1.PodLogOptions{
  41. Follow: true,
  42. TailLines: &tails,
  43. }
  44. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  45. podLogs, err := req.Stream(context.TODO())
  46. if err != nil {
  47. return fmt.Errorf("Cannot open log stream for pod %s", name)
  48. }
  49. defer podLogs.Close()
  50. r := bufio.NewReader(podLogs)
  51. for {
  52. bytes, err := r.ReadBytes('\n')
  53. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  54. return writeErr
  55. }
  56. if err != nil {
  57. if err != io.EOF {
  58. return err
  59. }
  60. return nil
  61. }
  62. }
  63. }