agent.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. package kubernetes
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "strings"
  9. "github.com/porter-dev/porter/internal/kubernetes/provisioner"
  10. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws"
  11. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/ecr"
  12. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/eks"
  13. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do"
  14. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/docr"
  15. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/doks"
  16. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp"
  17. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp/gke"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/models/integrations"
  20. "github.com/porter-dev/porter/internal/oauth"
  21. "github.com/porter-dev/porter/internal/registry"
  22. "github.com/porter-dev/porter/internal/repository"
  23. "golang.org/x/oauth2"
  24. "github.com/gorilla/websocket"
  25. "github.com/porter-dev/porter/internal/helm/grapher"
  26. appsv1 "k8s.io/api/apps/v1"
  27. batchv1 "k8s.io/api/batch/v1"
  28. batchv1beta1 "k8s.io/api/batch/v1beta1"
  29. v1 "k8s.io/api/core/v1"
  30. v1beta1 "k8s.io/api/extensions/v1beta1"
  31. "k8s.io/apimachinery/pkg/api/errors"
  32. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  33. "k8s.io/cli-runtime/pkg/genericclioptions"
  34. "k8s.io/client-go/informers"
  35. "k8s.io/client-go/kubernetes"
  36. "k8s.io/client-go/tools/cache"
  37. "github.com/porter-dev/porter/internal/config"
  38. )
  39. // Agent is a Kubernetes agent for performing operations that interact with the
  40. // api server
  41. type Agent struct {
  42. RESTClientGetter genericclioptions.RESTClientGetter
  43. Clientset kubernetes.Interface
  44. }
  45. type Message struct {
  46. EventType string
  47. Object interface{}
  48. Kind string
  49. }
  50. type ListOptions struct {
  51. FieldSelector string
  52. }
  53. // ListNamespaces simply lists namespaces
  54. func (a *Agent) ListNamespaces() (*v1.NamespaceList, error) {
  55. return a.Clientset.CoreV1().Namespaces().List(
  56. context.TODO(),
  57. metav1.ListOptions{},
  58. )
  59. }
  60. // GetIngress gets ingress given the name and namespace
  61. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  62. return a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  63. context.TODO(),
  64. name,
  65. metav1.GetOptions{},
  66. )
  67. }
  68. // GetDeployment gets the deployment given the name and namespace
  69. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  70. return a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  71. context.TODO(),
  72. c.Name,
  73. metav1.GetOptions{},
  74. )
  75. }
  76. // GetStatefulSet gets the statefulset given the name and namespace
  77. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  78. return a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  79. context.TODO(),
  80. c.Name,
  81. metav1.GetOptions{},
  82. )
  83. }
  84. // GetReplicaSet gets the replicaset given the name and namespace
  85. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  86. return a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  87. context.TODO(),
  88. c.Name,
  89. metav1.GetOptions{},
  90. )
  91. }
  92. // GetDaemonSet gets the daemonset by name and namespace
  93. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  94. return a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  95. context.TODO(),
  96. c.Name,
  97. metav1.GetOptions{},
  98. )
  99. }
  100. // GetJob gets the job by name and namespace
  101. func (a *Agent) GetJob(c grapher.Object) (*batchv1.Job, error) {
  102. return a.Clientset.BatchV1().Jobs(c.Namespace).Get(
  103. context.TODO(),
  104. c.Name,
  105. metav1.GetOptions{},
  106. )
  107. }
  108. // GetCronJob gets the CronJob by name and namespace
  109. func (a *Agent) GetCronJob(c grapher.Object) (*batchv1beta1.CronJob, error) {
  110. return a.Clientset.BatchV1beta1().CronJobs(c.Namespace).Get(
  111. context.TODO(),
  112. c.Name,
  113. metav1.GetOptions{},
  114. )
  115. }
  116. // GetPodsByLabel retrieves pods with matching labels
  117. func (a *Agent) GetPodsByLabel(selector string) (*v1.PodList, error) {
  118. // Search in all namespaces for matching pods
  119. return a.Clientset.CoreV1().Pods("").List(
  120. context.TODO(),
  121. metav1.ListOptions{
  122. LabelSelector: selector,
  123. },
  124. )
  125. }
  126. // GetPodLogs streams real-time logs from a given pod.
  127. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  128. tails := int64(400)
  129. // follow logs
  130. podLogOpts := v1.PodLogOptions{
  131. Follow: true,
  132. TailLines: &tails,
  133. }
  134. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  135. podLogs, err := req.Stream(context.TODO())
  136. if err != nil {
  137. return fmt.Errorf("Cannot open log stream for pod %s", name)
  138. }
  139. defer podLogs.Close()
  140. r := bufio.NewReader(podLogs)
  141. errorchan := make(chan error)
  142. go func() {
  143. // listens for websocket closing handshake
  144. for {
  145. if _, _, err := conn.ReadMessage(); err != nil {
  146. defer conn.Close()
  147. errorchan <- nil
  148. return
  149. }
  150. }
  151. }()
  152. go func() {
  153. for {
  154. select {
  155. case <-errorchan:
  156. defer close(errorchan)
  157. return
  158. default:
  159. }
  160. bytes, err := r.ReadBytes('\n')
  161. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  162. errorchan <- writeErr
  163. return
  164. }
  165. if err != nil {
  166. if err != io.EOF {
  167. errorchan <- err
  168. return
  169. }
  170. errorchan <- nil
  171. return
  172. }
  173. }
  174. }()
  175. for {
  176. select {
  177. case err = <-errorchan:
  178. return err
  179. }
  180. }
  181. }
  182. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  183. // TODO: Support Jobs
  184. func (a *Agent) StreamControllerStatus(conn *websocket.Conn, kind string) error {
  185. factory := informers.NewSharedInformerFactory(
  186. a.Clientset,
  187. 0,
  188. )
  189. var informer cache.SharedInformer
  190. // Spins up an informer depending on kind. Convert to lowercase for robustness
  191. switch strings.ToLower(kind) {
  192. case "deployment":
  193. informer = factory.Apps().V1().Deployments().Informer()
  194. case "statefulset":
  195. informer = factory.Apps().V1().StatefulSets().Informer()
  196. case "replicaset":
  197. informer = factory.Apps().V1().ReplicaSets().Informer()
  198. case "daemonset":
  199. informer = factory.Apps().V1().DaemonSets().Informer()
  200. }
  201. stopper := make(chan struct{})
  202. errorchan := make(chan error)
  203. defer close(errorchan)
  204. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  205. UpdateFunc: func(oldObj, newObj interface{}) {
  206. msg := Message{
  207. EventType: "UPDATE",
  208. Object: newObj,
  209. Kind: strings.ToLower(kind),
  210. }
  211. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  212. errorchan <- writeErr
  213. return
  214. }
  215. },
  216. })
  217. go func() {
  218. // listens for websocket closing handshake
  219. for {
  220. if _, _, err := conn.ReadMessage(); err != nil {
  221. defer conn.Close()
  222. defer close(stopper)
  223. errorchan <- nil
  224. return
  225. }
  226. }
  227. }()
  228. go informer.Run(stopper)
  229. for {
  230. select {
  231. case err := <-errorchan:
  232. return err
  233. }
  234. }
  235. }
  236. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  237. func (a *Agent) ProvisionECR(
  238. projectID uint,
  239. awsConf *integrations.AWSIntegration,
  240. ecrName string,
  241. repo repository.Repository,
  242. infra *models.Infra,
  243. operation provisioner.ProvisionerOperation,
  244. pgConf *config.DBConf,
  245. redisConf *config.RedisConf,
  246. provImageTag string,
  247. ) (*batchv1.Job, error) {
  248. id := infra.GetUniqueName()
  249. prov := &provisioner.Conf{
  250. ID: id,
  251. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  252. Kind: provisioner.ECR,
  253. Operation: operation,
  254. Redis: redisConf,
  255. Postgres: pgConf,
  256. ProvisionerImageTag: provImageTag,
  257. LastApplied: infra.LastApplied,
  258. AWS: &aws.Conf{
  259. AWSRegion: awsConf.AWSRegion,
  260. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  261. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  262. },
  263. ECR: &ecr.Conf{
  264. ECRName: ecrName,
  265. },
  266. }
  267. return a.provision(prov, infra, repo)
  268. }
  269. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  270. func (a *Agent) ProvisionEKS(
  271. projectID uint,
  272. awsConf *integrations.AWSIntegration,
  273. eksName string,
  274. repo repository.Repository,
  275. infra *models.Infra,
  276. operation provisioner.ProvisionerOperation,
  277. pgConf *config.DBConf,
  278. redisConf *config.RedisConf,
  279. provImageTag string,
  280. ) (*batchv1.Job, error) {
  281. id := infra.GetUniqueName()
  282. prov := &provisioner.Conf{
  283. ID: id,
  284. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  285. Kind: provisioner.EKS,
  286. Operation: operation,
  287. Redis: redisConf,
  288. Postgres: pgConf,
  289. ProvisionerImageTag: provImageTag,
  290. LastApplied: infra.LastApplied,
  291. AWS: &aws.Conf{
  292. AWSRegion: awsConf.AWSRegion,
  293. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  294. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  295. },
  296. EKS: &eks.Conf{
  297. ClusterName: eksName,
  298. },
  299. }
  300. return a.provision(prov, infra, repo)
  301. }
  302. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  303. func (a *Agent) ProvisionGCR(
  304. projectID uint,
  305. gcpConf *integrations.GCPIntegration,
  306. repo repository.Repository,
  307. infra *models.Infra,
  308. operation provisioner.ProvisionerOperation,
  309. pgConf *config.DBConf,
  310. redisConf *config.RedisConf,
  311. provImageTag string,
  312. ) (*batchv1.Job, error) {
  313. id := infra.GetUniqueName()
  314. prov := &provisioner.Conf{
  315. ID: id,
  316. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  317. Kind: provisioner.GCR,
  318. Operation: operation,
  319. Redis: redisConf,
  320. Postgres: pgConf,
  321. ProvisionerImageTag: provImageTag,
  322. LastApplied: infra.LastApplied,
  323. GCP: &gcp.Conf{
  324. GCPRegion: gcpConf.GCPRegion,
  325. GCPProjectID: gcpConf.GCPProjectID,
  326. GCPKeyData: string(gcpConf.GCPKeyData),
  327. },
  328. }
  329. return a.provision(prov, infra, repo)
  330. }
  331. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  332. func (a *Agent) ProvisionGKE(
  333. projectID uint,
  334. gcpConf *integrations.GCPIntegration,
  335. gkeName string,
  336. repo repository.Repository,
  337. infra *models.Infra,
  338. operation provisioner.ProvisionerOperation,
  339. pgConf *config.DBConf,
  340. redisConf *config.RedisConf,
  341. provImageTag string,
  342. ) (*batchv1.Job, error) {
  343. id := infra.GetUniqueName()
  344. prov := &provisioner.Conf{
  345. ID: id,
  346. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  347. Kind: provisioner.GKE,
  348. Operation: operation,
  349. Redis: redisConf,
  350. Postgres: pgConf,
  351. ProvisionerImageTag: provImageTag,
  352. LastApplied: infra.LastApplied,
  353. GCP: &gcp.Conf{
  354. GCPRegion: gcpConf.GCPRegion,
  355. GCPProjectID: gcpConf.GCPProjectID,
  356. GCPKeyData: string(gcpConf.GCPKeyData),
  357. },
  358. GKE: &gke.Conf{
  359. ClusterName: gkeName,
  360. },
  361. }
  362. return a.provision(prov, infra, repo)
  363. }
  364. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  365. func (a *Agent) ProvisionDOCR(
  366. projectID uint,
  367. doConf *integrations.OAuthIntegration,
  368. doAuth *oauth2.Config,
  369. repo repository.Repository,
  370. docrName, docrSubscriptionTier string,
  371. infra *models.Infra,
  372. operation provisioner.ProvisionerOperation,
  373. pgConf *config.DBConf,
  374. redisConf *config.RedisConf,
  375. provImageTag string,
  376. ) (*batchv1.Job, error) {
  377. // get the token
  378. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  379. infra.DOIntegrationID,
  380. )
  381. if err != nil {
  382. return nil, err
  383. }
  384. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  385. if err != nil {
  386. return nil, err
  387. }
  388. id := infra.GetUniqueName()
  389. prov := &provisioner.Conf{
  390. ID: id,
  391. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  392. Kind: provisioner.DOCR,
  393. Operation: operation,
  394. Redis: redisConf,
  395. Postgres: pgConf,
  396. ProvisionerImageTag: provImageTag,
  397. LastApplied: infra.LastApplied,
  398. DO: &do.Conf{
  399. DOToken: tok,
  400. },
  401. DOCR: &docr.Conf{
  402. DOCRName: docrName,
  403. DOCRSubscriptionTier: docrSubscriptionTier,
  404. },
  405. }
  406. return a.provision(prov, infra, repo)
  407. }
  408. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  409. func (a *Agent) ProvisionDOKS(
  410. projectID uint,
  411. doConf *integrations.OAuthIntegration,
  412. doAuth *oauth2.Config,
  413. repo repository.Repository,
  414. doRegion, doksClusterName string,
  415. infra *models.Infra,
  416. operation provisioner.ProvisionerOperation,
  417. pgConf *config.DBConf,
  418. redisConf *config.RedisConf,
  419. provImageTag string,
  420. ) (*batchv1.Job, error) {
  421. // get the token
  422. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  423. infra.DOIntegrationID,
  424. )
  425. if err != nil {
  426. return nil, err
  427. }
  428. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  429. if err != nil {
  430. return nil, err
  431. }
  432. id := infra.GetUniqueName()
  433. prov := &provisioner.Conf{
  434. ID: id,
  435. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  436. Kind: provisioner.DOKS,
  437. Operation: operation,
  438. Redis: redisConf,
  439. Postgres: pgConf,
  440. LastApplied: infra.LastApplied,
  441. ProvisionerImageTag: provImageTag,
  442. DO: &do.Conf{
  443. DOToken: tok,
  444. },
  445. DOKS: &doks.Conf{
  446. DORegion: doRegion,
  447. DOKSClusterName: doksClusterName,
  448. },
  449. }
  450. return a.provision(prov, infra, repo)
  451. }
  452. // ProvisionTest spawns a new provisioning pod that tests provisioning
  453. func (a *Agent) ProvisionTest(
  454. projectID uint,
  455. infra *models.Infra,
  456. repo repository.Repository,
  457. operation provisioner.ProvisionerOperation,
  458. pgConf *config.DBConf,
  459. redisConf *config.RedisConf,
  460. provImageTag string,
  461. ) (*batchv1.Job, error) {
  462. id := infra.GetUniqueName()
  463. prov := &provisioner.Conf{
  464. ID: id,
  465. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  466. Operation: operation,
  467. Kind: provisioner.Test,
  468. Redis: redisConf,
  469. Postgres: pgConf,
  470. ProvisionerImageTag: provImageTag,
  471. }
  472. return a.provision(prov, infra, repo)
  473. }
  474. func (a *Agent) provision(
  475. prov *provisioner.Conf,
  476. infra *models.Infra,
  477. repo repository.Repository,
  478. ) (*batchv1.Job, error) {
  479. prov.Namespace = "default"
  480. job, err := prov.GetProvisionerJobTemplate()
  481. if err != nil {
  482. return nil, err
  483. }
  484. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  485. context.TODO(),
  486. job,
  487. metav1.CreateOptions{},
  488. )
  489. if err != nil {
  490. return nil, err
  491. }
  492. infra.LastApplied = prov.LastApplied
  493. infra, err = repo.Infra.UpdateInfra(infra)
  494. if err != nil {
  495. return nil, err
  496. }
  497. return job, nil
  498. }
  499. // CreateImagePullSecrets will create the required image pull secrets and
  500. // return a map from the registry name to the name of the secret.
  501. func (a *Agent) CreateImagePullSecrets(
  502. repo repository.Repository,
  503. namespace string,
  504. linkedRegs map[string]*models.Registry,
  505. doAuth *oauth2.Config,
  506. ) (map[string]string, error) {
  507. res := make(map[string]string)
  508. for key, val := range linkedRegs {
  509. _reg := registry.Registry(*val)
  510. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  511. if err != nil {
  512. return nil, err
  513. }
  514. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  515. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  516. context.TODO(),
  517. secretName,
  518. metav1.GetOptions{},
  519. )
  520. // if not found, create the secret
  521. if err != nil && errors.IsNotFound(err) {
  522. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  523. context.TODO(),
  524. &v1.Secret{
  525. ObjectMeta: metav1.ObjectMeta{
  526. Name: secretName,
  527. },
  528. Data: map[string][]byte{
  529. string(v1.DockerConfigJsonKey): data,
  530. },
  531. Type: v1.SecretTypeDockerConfigJson,
  532. },
  533. metav1.CreateOptions{},
  534. )
  535. if err != nil {
  536. return nil, err
  537. }
  538. // add secret name to the map
  539. res[key] = secretName
  540. continue
  541. } else if err != nil {
  542. return nil, err
  543. }
  544. // otherwise, check that the secret contains the correct data: if
  545. // if doesn't, update it
  546. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  547. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  548. context.TODO(),
  549. &v1.Secret{
  550. ObjectMeta: metav1.ObjectMeta{
  551. Name: secretName,
  552. },
  553. Data: map[string][]byte{
  554. string(v1.DockerConfigJsonKey): data,
  555. },
  556. Type: v1.SecretTypeDockerConfigJson,
  557. },
  558. metav1.UpdateOptions{},
  559. )
  560. if err != nil {
  561. return nil, err
  562. }
  563. }
  564. // add secret name to the map
  565. res[key] = secretName
  566. }
  567. return res, nil
  568. }