agent.go 15 KB

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