2
0

agent.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package kubernetes
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "github.com/porter-dev/porter/internal/kubernetes/provisioner"
  9. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws"
  10. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/ecr"
  11. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/eks"
  12. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp"
  13. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp/gke"
  14. "github.com/porter-dev/porter/internal/models"
  15. "github.com/porter-dev/porter/internal/models/integrations"
  16. "github.com/gorilla/websocket"
  17. "github.com/porter-dev/porter/internal/helm/grapher"
  18. appsv1 "k8s.io/api/apps/v1"
  19. batchv1 "k8s.io/api/batch/v1"
  20. v1 "k8s.io/api/core/v1"
  21. v1beta1 "k8s.io/api/extensions/v1beta1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/cli-runtime/pkg/genericclioptions"
  24. "k8s.io/client-go/informers"
  25. "k8s.io/client-go/kubernetes"
  26. "k8s.io/client-go/tools/cache"
  27. "github.com/porter-dev/porter/internal/config"
  28. )
  29. // Agent is a Kubernetes agent for performing operations that interact with the
  30. // api server
  31. type Agent struct {
  32. RESTClientGetter genericclioptions.RESTClientGetter
  33. Clientset kubernetes.Interface
  34. }
  35. type Message struct {
  36. EventType string
  37. Object interface{}
  38. Kind string
  39. }
  40. type ListOptions struct {
  41. FieldSelector string
  42. }
  43. // ListNamespaces simply lists namespaces
  44. func (a *Agent) ListNamespaces() (*v1.NamespaceList, error) {
  45. return a.Clientset.CoreV1().Namespaces().List(
  46. context.TODO(),
  47. metav1.ListOptions{},
  48. )
  49. }
  50. // GetIngress gets ingress given the name and namespace
  51. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  52. return a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  53. context.TODO(),
  54. name,
  55. metav1.GetOptions{},
  56. )
  57. }
  58. // GetDeployment gets the deployment given the name and namespace
  59. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  60. return a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  61. context.TODO(),
  62. c.Name,
  63. metav1.GetOptions{},
  64. )
  65. }
  66. // GetStatefulSet gets the statefulset given the name and namespace
  67. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  68. return a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  69. context.TODO(),
  70. c.Name,
  71. metav1.GetOptions{},
  72. )
  73. }
  74. // GetReplicaSet gets the replicaset given the name and namespace
  75. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  76. return a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  77. context.TODO(),
  78. c.Name,
  79. metav1.GetOptions{},
  80. )
  81. }
  82. // GetDaemonSet gets the daemonset by name and namespace
  83. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  84. return a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  85. context.TODO(),
  86. c.Name,
  87. metav1.GetOptions{},
  88. )
  89. }
  90. // GetPodsByLabel retrieves pods with matching labels
  91. func (a *Agent) GetPodsByLabel(selector string) (*v1.PodList, error) {
  92. // Search in all namespaces for matching pods
  93. return a.Clientset.CoreV1().Pods("").List(
  94. context.TODO(),
  95. metav1.ListOptions{
  96. LabelSelector: selector,
  97. },
  98. )
  99. }
  100. // GetPodLogs streams real-time logs from a given pod.
  101. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  102. // follow logs
  103. tails := int64(30)
  104. podLogOpts := v1.PodLogOptions{
  105. Follow: true,
  106. TailLines: &tails,
  107. }
  108. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  109. podLogs, err := req.Stream(context.TODO())
  110. if err != nil {
  111. return fmt.Errorf("Cannot open log stream for pod %s", name)
  112. }
  113. defer podLogs.Close()
  114. r := bufio.NewReader(podLogs)
  115. errorchan := make(chan error)
  116. go func() {
  117. // listens for websocket closing handshake
  118. for {
  119. if _, _, err := conn.ReadMessage(); err != nil {
  120. defer conn.Close()
  121. errorchan <- nil
  122. fmt.Println("Successfully closed log stream")
  123. return
  124. }
  125. }
  126. }()
  127. go func() {
  128. for {
  129. select {
  130. case <-errorchan:
  131. defer close(errorchan)
  132. return
  133. default:
  134. }
  135. bytes, err := r.ReadBytes('\n')
  136. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  137. errorchan <- writeErr
  138. return
  139. }
  140. if err != nil {
  141. if err != io.EOF {
  142. errorchan <- err
  143. return
  144. }
  145. errorchan <- nil
  146. return
  147. }
  148. }
  149. }()
  150. for {
  151. select {
  152. case err = <-errorchan:
  153. return err
  154. }
  155. }
  156. }
  157. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  158. // TODO: Support Jobs
  159. func (a *Agent) StreamControllerStatus(conn *websocket.Conn, kind string) error {
  160. factory := informers.NewSharedInformerFactory(
  161. a.Clientset,
  162. 0,
  163. )
  164. var informer cache.SharedInformer
  165. // Spins up an informer depending on kind. Convert to lowercase for robustness
  166. switch strings.ToLower(kind) {
  167. case "deployment":
  168. informer = factory.Apps().V1().Deployments().Informer()
  169. case "statefulset":
  170. informer = factory.Apps().V1().StatefulSets().Informer()
  171. case "replicaset":
  172. informer = factory.Apps().V1().ReplicaSets().Informer()
  173. case "daemonset":
  174. informer = factory.Apps().V1().DaemonSets().Informer()
  175. }
  176. stopper := make(chan struct{})
  177. errorchan := make(chan error)
  178. defer close(errorchan)
  179. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  180. UpdateFunc: func(oldObj, newObj interface{}) {
  181. msg := Message{
  182. EventType: "UPDATE",
  183. Object: newObj,
  184. Kind: strings.ToLower(kind),
  185. }
  186. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  187. errorchan <- writeErr
  188. return
  189. }
  190. },
  191. })
  192. go func() {
  193. // listens for websocket closing handshake
  194. for {
  195. if _, _, err := conn.ReadMessage(); err != nil {
  196. defer conn.Close()
  197. defer close(stopper)
  198. defer fmt.Println("Successfully closed controller status stream")
  199. errorchan <- nil
  200. return
  201. }
  202. }
  203. }()
  204. go informer.Run(stopper)
  205. for {
  206. select {
  207. case err := <-errorchan:
  208. return err
  209. }
  210. }
  211. }
  212. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  213. func (a *Agent) ProvisionECR(
  214. projectID uint,
  215. awsConf *integrations.AWSIntegration,
  216. ecrName string,
  217. infra *models.Infra,
  218. operation provisioner.ProvisionerOperation,
  219. pgConf *config.DBConf,
  220. redisConf *config.RedisConf,
  221. provImageTag string,
  222. ) (*batchv1.Job, error) {
  223. id := infra.GetID()
  224. prov := &provisioner.Conf{
  225. ID: id,
  226. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  227. Kind: provisioner.ECR,
  228. Operation: operation,
  229. Redis: redisConf,
  230. Postgres: pgConf,
  231. ProvisionerImageTag: provImageTag,
  232. AWS: &aws.Conf{
  233. AWSRegion: awsConf.AWSRegion,
  234. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  235. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  236. },
  237. ECR: &ecr.Conf{
  238. ECRName: ecrName,
  239. },
  240. }
  241. return a.provision(prov)
  242. }
  243. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  244. func (a *Agent) ProvisionEKS(
  245. projectID uint,
  246. awsConf *integrations.AWSIntegration,
  247. eksName string,
  248. infra *models.Infra,
  249. operation provisioner.ProvisionerOperation,
  250. pgConf *config.DBConf,
  251. redisConf *config.RedisConf,
  252. provImageTag string,
  253. ) (*batchv1.Job, error) {
  254. id := infra.GetID()
  255. prov := &provisioner.Conf{
  256. ID: id,
  257. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  258. Kind: provisioner.EKS,
  259. Operation: operation,
  260. Redis: redisConf,
  261. Postgres: pgConf,
  262. ProvisionerImageTag: provImageTag,
  263. AWS: &aws.Conf{
  264. AWSRegion: awsConf.AWSRegion,
  265. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  266. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  267. },
  268. EKS: &eks.Conf{
  269. ClusterName: eksName,
  270. },
  271. }
  272. return a.provision(prov)
  273. }
  274. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  275. func (a *Agent) ProvisionGCR(
  276. projectID uint,
  277. gcpConf *integrations.GCPIntegration,
  278. infra *models.Infra,
  279. operation provisioner.ProvisionerOperation,
  280. pgConf *config.DBConf,
  281. redisConf *config.RedisConf,
  282. provImageTag string,
  283. ) (*batchv1.Job, error) {
  284. id := infra.GetID()
  285. prov := &provisioner.Conf{
  286. ID: id,
  287. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  288. Kind: provisioner.GCR,
  289. Operation: operation,
  290. Redis: redisConf,
  291. Postgres: pgConf,
  292. ProvisionerImageTag: provImageTag,
  293. GCP: &gcp.Conf{
  294. GCPRegion: gcpConf.GCPRegion,
  295. GCPProjectID: gcpConf.GCPProjectID,
  296. GCPKeyData: string(gcpConf.GCPKeyData),
  297. },
  298. }
  299. return a.provision(prov)
  300. }
  301. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  302. func (a *Agent) ProvisionGKE(
  303. projectID uint,
  304. gcpConf *integrations.GCPIntegration,
  305. gkeName string,
  306. infra *models.Infra,
  307. operation provisioner.ProvisionerOperation,
  308. pgConf *config.DBConf,
  309. redisConf *config.RedisConf,
  310. provImageTag string,
  311. ) (*batchv1.Job, error) {
  312. id := infra.GetID()
  313. prov := &provisioner.Conf{
  314. ID: id,
  315. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  316. Kind: provisioner.GKE,
  317. Operation: operation,
  318. Redis: redisConf,
  319. Postgres: pgConf,
  320. ProvisionerImageTag: provImageTag,
  321. GCP: &gcp.Conf{
  322. GCPRegion: gcpConf.GCPRegion,
  323. GCPProjectID: gcpConf.GCPProjectID,
  324. GCPKeyData: string(gcpConf.GCPKeyData),
  325. },
  326. GKE: &gke.Conf{
  327. ClusterName: gkeName,
  328. },
  329. }
  330. return a.provision(prov)
  331. }
  332. // ProvisionTest spawns a new provisioning pod that tests provisioning
  333. func (a *Agent) ProvisionTest(
  334. projectID uint,
  335. operation provisioner.ProvisionerOperation,
  336. pgConf *config.DBConf,
  337. redisConf *config.RedisConf,
  338. provImageTag string,
  339. ) (*batchv1.Job, error) {
  340. prov := &provisioner.Conf{
  341. ID: fmt.Sprintf("%s-%d", "testing", projectID),
  342. Name: fmt.Sprintf("prov-%s-%d-%s", "testing", projectID, string(operation)),
  343. Operation: operation,
  344. Kind: provisioner.Test,
  345. Redis: redisConf,
  346. Postgres: pgConf,
  347. ProvisionerImageTag: provImageTag,
  348. }
  349. return a.provision(prov)
  350. }
  351. func (a *Agent) provision(
  352. prov *provisioner.Conf,
  353. ) (*batchv1.Job, error) {
  354. prov.Namespace = "default"
  355. job, err := prov.GetProvisionerJobTemplate()
  356. if err != nil {
  357. return nil, err
  358. }
  359. return a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  360. context.TODO(),
  361. job,
  362. metav1.CreateOptions{},
  363. )
  364. }