agent.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. package kubernetes
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "github.com/porter-dev/porter/internal/kubernetes/provisioner"
  11. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws"
  12. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/ecr"
  13. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/eks"
  14. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do"
  15. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/docr"
  16. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/doks"
  17. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp"
  18. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp/gke"
  19. "github.com/porter-dev/porter/internal/models"
  20. "github.com/porter-dev/porter/internal/models/integrations"
  21. "github.com/porter-dev/porter/internal/oauth"
  22. "github.com/porter-dev/porter/internal/registry"
  23. "github.com/porter-dev/porter/internal/repository"
  24. "golang.org/x/oauth2"
  25. "github.com/gorilla/websocket"
  26. "github.com/porter-dev/porter/internal/helm/grapher"
  27. appsv1 "k8s.io/api/apps/v1"
  28. batchv1 "k8s.io/api/batch/v1"
  29. batchv1beta1 "k8s.io/api/batch/v1beta1"
  30. v1 "k8s.io/api/core/v1"
  31. v1beta1 "k8s.io/api/extensions/v1beta1"
  32. "k8s.io/apimachinery/pkg/api/errors"
  33. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  34. "k8s.io/apimachinery/pkg/runtime"
  35. "k8s.io/apimachinery/pkg/runtime/schema"
  36. "k8s.io/apimachinery/pkg/types"
  37. "k8s.io/cli-runtime/pkg/genericclioptions"
  38. "k8s.io/client-go/informers"
  39. "k8s.io/client-go/kubernetes"
  40. "k8s.io/client-go/rest"
  41. "k8s.io/client-go/tools/cache"
  42. "k8s.io/client-go/tools/remotecommand"
  43. "github.com/porter-dev/porter/internal/config"
  44. )
  45. // Agent is a Kubernetes agent for performing operations that interact with the
  46. // api server
  47. type Agent struct {
  48. RESTClientGetter genericclioptions.RESTClientGetter
  49. Clientset kubernetes.Interface
  50. }
  51. type Message struct {
  52. EventType string `json:"event_type"`
  53. Object interface{}
  54. Kind string
  55. }
  56. type ListOptions struct {
  57. FieldSelector string
  58. }
  59. // CreateConfigMap creates the configmap given the key-value pairs and namespace
  60. func (a *Agent) CreateConfigMap(name string, namespace string, configMap map[string]string) (*v1.ConfigMap, error) {
  61. return a.Clientset.CoreV1().ConfigMaps(namespace).Create(
  62. context.TODO(),
  63. &v1.ConfigMap{
  64. ObjectMeta: metav1.ObjectMeta{
  65. Name: name,
  66. Namespace: namespace,
  67. Labels: map[string]string{
  68. "porter": "true",
  69. },
  70. },
  71. Data: configMap,
  72. },
  73. metav1.CreateOptions{},
  74. )
  75. }
  76. // CreateLinkedSecret creates a secret given the key-value pairs and namespace. Values are
  77. // base64 encoded
  78. func (a *Agent) CreateLinkedSecret(name, namespace, cmName string, data map[string][]byte) (*v1.Secret, error) {
  79. return a.Clientset.CoreV1().Secrets(namespace).Create(
  80. context.TODO(),
  81. &v1.Secret{
  82. ObjectMeta: metav1.ObjectMeta{
  83. Name: name,
  84. Namespace: namespace,
  85. Labels: map[string]string{
  86. "porter": "true",
  87. "configmap": cmName,
  88. },
  89. },
  90. Data: data,
  91. },
  92. metav1.CreateOptions{},
  93. )
  94. }
  95. type mergeConfigMapData struct {
  96. Data map[string]*string `json:"data"`
  97. }
  98. // UpdateConfigMap updates the configmap given its name and namespace
  99. func (a *Agent) UpdateConfigMap(name string, namespace string, configMap map[string]string) error {
  100. cmData := make(map[string]*string)
  101. for key, val := range configMap {
  102. valCopy := val
  103. cmData[key] = &valCopy
  104. if len(val) == 0 {
  105. cmData[key] = nil
  106. }
  107. }
  108. mergeCM := &mergeConfigMapData{
  109. Data: cmData,
  110. }
  111. patchBytes, err := json.Marshal(mergeCM)
  112. if err != nil {
  113. return err
  114. }
  115. _, err = a.Clientset.CoreV1().ConfigMaps(namespace).Patch(
  116. context.Background(),
  117. name,
  118. types.MergePatchType,
  119. patchBytes,
  120. metav1.PatchOptions{},
  121. )
  122. return err
  123. }
  124. type mergeLinkedSecretData struct {
  125. Data map[string]*[]byte `json:"data"`
  126. }
  127. // UpdateLinkedSecret updates the secret given its name and namespace
  128. func (a *Agent) UpdateLinkedSecret(name, namespace, cmName string, data map[string][]byte) error {
  129. secretData := make(map[string]*[]byte)
  130. for key, val := range data {
  131. valCopy := val
  132. secretData[key] = &valCopy
  133. if len(val) == 0 {
  134. secretData[key] = nil
  135. }
  136. }
  137. mergeSecret := &mergeLinkedSecretData{
  138. Data: secretData,
  139. }
  140. patchBytes, err := json.Marshal(mergeSecret)
  141. if err != nil {
  142. return err
  143. }
  144. _, err = a.Clientset.CoreV1().Secrets(namespace).Patch(
  145. context.TODO(),
  146. name,
  147. types.MergePatchType,
  148. patchBytes,
  149. metav1.PatchOptions{},
  150. )
  151. return err
  152. }
  153. // DeleteConfigMap deletes the configmap given its name and namespace
  154. func (a *Agent) DeleteConfigMap(name string, namespace string) error {
  155. return a.Clientset.CoreV1().ConfigMaps(namespace).Delete(
  156. context.TODO(),
  157. name,
  158. metav1.DeleteOptions{},
  159. )
  160. }
  161. // DeleteLinkedSecret deletes the secret given its name and namespace
  162. func (a *Agent) DeleteLinkedSecret(name, namespace string) error {
  163. return a.Clientset.CoreV1().Secrets(namespace).Delete(
  164. context.TODO(),
  165. name,
  166. metav1.DeleteOptions{},
  167. )
  168. }
  169. // GetConfigMap retrieves the configmap given its name and namespace
  170. func (a *Agent) GetConfigMap(name string, namespace string) (*v1.ConfigMap, error) {
  171. return a.Clientset.CoreV1().ConfigMaps(namespace).Get(
  172. context.TODO(),
  173. name,
  174. metav1.GetOptions{},
  175. )
  176. }
  177. // ListConfigMaps simply lists namespaces
  178. func (a *Agent) ListConfigMaps(namespace string) (*v1.ConfigMapList, error) {
  179. return a.Clientset.CoreV1().ConfigMaps(namespace).List(
  180. context.TODO(),
  181. metav1.ListOptions{
  182. LabelSelector: "porter=true",
  183. },
  184. )
  185. }
  186. // ListEvents lists the events of a given object.
  187. func (a *Agent) ListEvents(name string, namespace string) (*v1.EventList, error) {
  188. return a.Clientset.CoreV1().Events(namespace).List(
  189. context.TODO(),
  190. metav1.ListOptions{
  191. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  192. },
  193. )
  194. }
  195. // ListNamespaces simply lists namespaces
  196. func (a *Agent) ListNamespaces() (*v1.NamespaceList, error) {
  197. return a.Clientset.CoreV1().Namespaces().List(
  198. context.TODO(),
  199. metav1.ListOptions{},
  200. )
  201. }
  202. // CreateNamespace creates a namespace with the given name.
  203. func (a *Agent) CreateNamespace(name string) (*v1.Namespace, error) {
  204. namespace := v1.Namespace{
  205. ObjectMeta: metav1.ObjectMeta{
  206. Name: name,
  207. },
  208. }
  209. return a.Clientset.CoreV1().Namespaces().Create(
  210. context.TODO(),
  211. &namespace,
  212. metav1.CreateOptions{},
  213. )
  214. }
  215. // DeleteNamespace deletes the namespace given the name.
  216. func (a *Agent) DeleteNamespace(name string) error {
  217. return a.Clientset.CoreV1().Namespaces().Delete(
  218. context.TODO(),
  219. name,
  220. metav1.DeleteOptions{},
  221. )
  222. }
  223. // ListJobsByLabel lists jobs in a namespace matching a label
  224. type Label struct {
  225. Key string
  226. Val string
  227. }
  228. func (a *Agent) ListJobsByLabel(namespace string, labels ...Label) ([]batchv1.Job, error) {
  229. selectors := make([]string, 0)
  230. for _, label := range labels {
  231. selectors = append(selectors, fmt.Sprintf("%s=%s", label.Key, label.Val))
  232. }
  233. resp, err := a.Clientset.BatchV1().Jobs(namespace).List(
  234. context.TODO(),
  235. metav1.ListOptions{
  236. LabelSelector: strings.Join(selectors, ","),
  237. },
  238. )
  239. if err != nil {
  240. return nil, err
  241. }
  242. return resp.Items, nil
  243. }
  244. // DeleteJob deletes the job in the given name and namespace.
  245. func (a *Agent) DeleteJob(name, namespace string) error {
  246. return a.Clientset.BatchV1().Jobs(namespace).Delete(
  247. context.TODO(),
  248. name,
  249. metav1.DeleteOptions{},
  250. )
  251. }
  252. // GetJobPods lists all pods belonging to a job in a namespace
  253. func (a *Agent) GetJobPods(namespace, jobName string) ([]v1.Pod, error) {
  254. resp, err := a.Clientset.CoreV1().Pods(namespace).List(
  255. context.TODO(),
  256. metav1.ListOptions{
  257. LabelSelector: fmt.Sprintf("%s=%s", "job-name", jobName),
  258. },
  259. )
  260. if err != nil {
  261. return nil, err
  262. }
  263. return resp.Items, nil
  264. }
  265. // GetIngress gets ingress given the name and namespace
  266. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  267. return a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  268. context.TODO(),
  269. name,
  270. metav1.GetOptions{},
  271. )
  272. }
  273. // GetDeployment gets the deployment given the name and namespace
  274. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  275. return a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  276. context.TODO(),
  277. c.Name,
  278. metav1.GetOptions{},
  279. )
  280. }
  281. // GetStatefulSet gets the statefulset given the name and namespace
  282. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  283. return a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  284. context.TODO(),
  285. c.Name,
  286. metav1.GetOptions{},
  287. )
  288. }
  289. // GetReplicaSet gets the replicaset given the name and namespace
  290. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  291. return a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  292. context.TODO(),
  293. c.Name,
  294. metav1.GetOptions{},
  295. )
  296. }
  297. // GetDaemonSet gets the daemonset by name and namespace
  298. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  299. return a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  300. context.TODO(),
  301. c.Name,
  302. metav1.GetOptions{},
  303. )
  304. }
  305. // GetJob gets the job by name and namespace
  306. func (a *Agent) GetJob(c grapher.Object) (*batchv1.Job, error) {
  307. return a.Clientset.BatchV1().Jobs(c.Namespace).Get(
  308. context.TODO(),
  309. c.Name,
  310. metav1.GetOptions{},
  311. )
  312. }
  313. // GetCronJob gets the CronJob by name and namespace
  314. func (a *Agent) GetCronJob(c grapher.Object) (*batchv1beta1.CronJob, error) {
  315. return a.Clientset.BatchV1beta1().CronJobs(c.Namespace).Get(
  316. context.TODO(),
  317. c.Name,
  318. metav1.GetOptions{},
  319. )
  320. }
  321. // GetPodsByLabel retrieves pods with matching labels
  322. func (a *Agent) GetPodsByLabel(selector string, namespace string) (*v1.PodList, error) {
  323. // Search in all namespaces for matching pods
  324. return a.Clientset.CoreV1().Pods(namespace).List(
  325. context.TODO(),
  326. metav1.ListOptions{
  327. LabelSelector: selector,
  328. },
  329. )
  330. }
  331. // DeletePod deletes a pod by name and namespace
  332. func (a *Agent) DeletePod(namespace string, name string) error {
  333. return a.Clientset.CoreV1().Pods(namespace).Delete(
  334. context.TODO(),
  335. name,
  336. metav1.DeleteOptions{},
  337. )
  338. }
  339. // GetPodLogs streams real-time logs from a given pod.
  340. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  341. // get the pod to read in the list of contains
  342. pod, err := a.Clientset.CoreV1().Pods(namespace).Get(
  343. context.Background(),
  344. name,
  345. metav1.GetOptions{},
  346. )
  347. if err != nil {
  348. return fmt.Errorf("Cannot get pod %s: %s", name, err.Error())
  349. }
  350. container := pod.Spec.Containers[0].Name
  351. tails := int64(400)
  352. // follow logs
  353. podLogOpts := v1.PodLogOptions{
  354. Follow: true,
  355. TailLines: &tails,
  356. Container: container,
  357. }
  358. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  359. podLogs, err := req.Stream(context.TODO())
  360. if err != nil {
  361. return fmt.Errorf("Cannot open log stream for pod %s: %s", name, err.Error())
  362. }
  363. defer podLogs.Close()
  364. r := bufio.NewReader(podLogs)
  365. errorchan := make(chan error)
  366. go func() {
  367. // listens for websocket closing handshake
  368. for {
  369. if _, _, err := conn.ReadMessage(); err != nil {
  370. defer conn.Close()
  371. errorchan <- nil
  372. return
  373. }
  374. }
  375. }()
  376. go func() {
  377. for {
  378. select {
  379. case <-errorchan:
  380. defer close(errorchan)
  381. return
  382. default:
  383. }
  384. bytes, err := r.ReadBytes('\n')
  385. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  386. errorchan <- writeErr
  387. return
  388. }
  389. if err != nil {
  390. if err != io.EOF {
  391. errorchan <- err
  392. return
  393. }
  394. errorchan <- nil
  395. return
  396. }
  397. }
  398. }()
  399. for {
  400. select {
  401. case err = <-errorchan:
  402. return err
  403. }
  404. }
  405. }
  406. // StopJobWithJobSidecar sends a termination signal to a job running with a sidecar
  407. func (a *Agent) StopJobWithJobSidecar(namespace, name string) error {
  408. jobPods, err := a.GetJobPods(namespace, name)
  409. if err != nil {
  410. return err
  411. }
  412. podName := jobPods[0].ObjectMeta.Name
  413. restConf, err := a.RESTClientGetter.ToRESTConfig()
  414. restConf.GroupVersion = &schema.GroupVersion{
  415. Group: "api",
  416. Version: "v1",
  417. }
  418. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  419. restClient, err := rest.RESTClientFor(restConf)
  420. if err != nil {
  421. return err
  422. }
  423. req := restClient.Post().
  424. Resource("pods").
  425. Name(podName).
  426. Namespace(namespace).
  427. SubResource("exec")
  428. req.Param("command", "./signal.sh")
  429. req.Param("container", "sidecar")
  430. req.Param("stdin", "true")
  431. req.Param("stdout", "false")
  432. req.Param("tty", "false")
  433. exec, err := remotecommand.NewSPDYExecutor(restConf, "POST", req.URL())
  434. if err != nil {
  435. return err
  436. }
  437. return exec.Stream(remotecommand.StreamOptions{
  438. Tty: false,
  439. Stdin: strings.NewReader("./signal.sh"),
  440. })
  441. }
  442. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  443. // TODO: Support Jobs
  444. func (a *Agent) StreamControllerStatus(conn *websocket.Conn, kind string) error {
  445. factory := informers.NewSharedInformerFactory(
  446. a.Clientset,
  447. 0,
  448. )
  449. var informer cache.SharedInformer
  450. // Spins up an informer depending on kind. Convert to lowercase for robustness
  451. switch strings.ToLower(kind) {
  452. case "deployment":
  453. informer = factory.Apps().V1().Deployments().Informer()
  454. case "statefulset":
  455. informer = factory.Apps().V1().StatefulSets().Informer()
  456. case "replicaset":
  457. informer = factory.Apps().V1().ReplicaSets().Informer()
  458. case "daemonset":
  459. informer = factory.Apps().V1().DaemonSets().Informer()
  460. case "job":
  461. informer = factory.Batch().V1().Jobs().Informer()
  462. case "cronjob":
  463. informer = factory.Batch().V1beta1().CronJobs().Informer()
  464. }
  465. stopper := make(chan struct{})
  466. errorchan := make(chan error)
  467. defer close(errorchan)
  468. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  469. UpdateFunc: func(oldObj, newObj interface{}) {
  470. msg := Message{
  471. EventType: "UPDATE",
  472. Object: newObj,
  473. Kind: strings.ToLower(kind),
  474. }
  475. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  476. errorchan <- writeErr
  477. return
  478. }
  479. },
  480. AddFunc: func(obj interface{}) {
  481. msg := Message{
  482. EventType: "ADD",
  483. Object: obj,
  484. Kind: strings.ToLower(kind),
  485. }
  486. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  487. errorchan <- writeErr
  488. return
  489. }
  490. },
  491. DeleteFunc: func(obj interface{}) {
  492. msg := Message{
  493. EventType: "DELETE",
  494. Object: obj,
  495. Kind: strings.ToLower(kind),
  496. }
  497. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  498. errorchan <- writeErr
  499. return
  500. }
  501. },
  502. })
  503. go func() {
  504. // listens for websocket closing handshake
  505. for {
  506. if _, _, err := conn.ReadMessage(); err != nil {
  507. defer conn.Close()
  508. defer close(stopper)
  509. errorchan <- nil
  510. return
  511. }
  512. }
  513. }()
  514. go informer.Run(stopper)
  515. for {
  516. select {
  517. case err := <-errorchan:
  518. return err
  519. }
  520. }
  521. }
  522. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  523. func (a *Agent) ProvisionECR(
  524. projectID uint,
  525. awsConf *integrations.AWSIntegration,
  526. ecrName string,
  527. repo repository.Repository,
  528. infra *models.Infra,
  529. operation provisioner.ProvisionerOperation,
  530. pgConf *config.DBConf,
  531. redisConf *config.RedisConf,
  532. provImageTag string,
  533. ) (*batchv1.Job, error) {
  534. id := infra.GetUniqueName()
  535. prov := &provisioner.Conf{
  536. ID: id,
  537. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  538. Kind: provisioner.ECR,
  539. Operation: operation,
  540. Redis: redisConf,
  541. Postgres: pgConf,
  542. ProvisionerImageTag: provImageTag,
  543. LastApplied: infra.LastApplied,
  544. AWS: &aws.Conf{
  545. AWSRegion: awsConf.AWSRegion,
  546. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  547. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  548. },
  549. ECR: &ecr.Conf{
  550. ECRName: ecrName,
  551. },
  552. }
  553. return a.provision(prov, infra, repo)
  554. }
  555. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  556. func (a *Agent) ProvisionEKS(
  557. projectID uint,
  558. awsConf *integrations.AWSIntegration,
  559. eksName, machineType string,
  560. repo repository.Repository,
  561. infra *models.Infra,
  562. operation provisioner.ProvisionerOperation,
  563. pgConf *config.DBConf,
  564. redisConf *config.RedisConf,
  565. provImageTag string,
  566. ) (*batchv1.Job, error) {
  567. id := infra.GetUniqueName()
  568. prov := &provisioner.Conf{
  569. ID: id,
  570. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  571. Kind: provisioner.EKS,
  572. Operation: operation,
  573. Redis: redisConf,
  574. Postgres: pgConf,
  575. ProvisionerImageTag: provImageTag,
  576. LastApplied: infra.LastApplied,
  577. AWS: &aws.Conf{
  578. AWSRegion: awsConf.AWSRegion,
  579. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  580. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  581. },
  582. EKS: &eks.Conf{
  583. ClusterName: eksName,
  584. MachineType: machineType,
  585. },
  586. }
  587. return a.provision(prov, infra, repo)
  588. }
  589. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  590. func (a *Agent) ProvisionGCR(
  591. projectID uint,
  592. gcpConf *integrations.GCPIntegration,
  593. repo repository.Repository,
  594. infra *models.Infra,
  595. operation provisioner.ProvisionerOperation,
  596. pgConf *config.DBConf,
  597. redisConf *config.RedisConf,
  598. provImageTag string,
  599. ) (*batchv1.Job, error) {
  600. id := infra.GetUniqueName()
  601. prov := &provisioner.Conf{
  602. ID: id,
  603. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  604. Kind: provisioner.GCR,
  605. Operation: operation,
  606. Redis: redisConf,
  607. Postgres: pgConf,
  608. ProvisionerImageTag: provImageTag,
  609. LastApplied: infra.LastApplied,
  610. GCP: &gcp.Conf{
  611. GCPRegion: gcpConf.GCPRegion,
  612. GCPProjectID: gcpConf.GCPProjectID,
  613. GCPKeyData: string(gcpConf.GCPKeyData),
  614. },
  615. }
  616. return a.provision(prov, infra, repo)
  617. }
  618. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  619. func (a *Agent) ProvisionGKE(
  620. projectID uint,
  621. gcpConf *integrations.GCPIntegration,
  622. gkeName string,
  623. repo repository.Repository,
  624. infra *models.Infra,
  625. operation provisioner.ProvisionerOperation,
  626. pgConf *config.DBConf,
  627. redisConf *config.RedisConf,
  628. provImageTag string,
  629. ) (*batchv1.Job, error) {
  630. id := infra.GetUniqueName()
  631. prov := &provisioner.Conf{
  632. ID: id,
  633. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  634. Kind: provisioner.GKE,
  635. Operation: operation,
  636. Redis: redisConf,
  637. Postgres: pgConf,
  638. ProvisionerImageTag: provImageTag,
  639. LastApplied: infra.LastApplied,
  640. GCP: &gcp.Conf{
  641. GCPRegion: gcpConf.GCPRegion,
  642. GCPProjectID: gcpConf.GCPProjectID,
  643. GCPKeyData: string(gcpConf.GCPKeyData),
  644. },
  645. GKE: &gke.Conf{
  646. ClusterName: gkeName,
  647. },
  648. }
  649. return a.provision(prov, infra, repo)
  650. }
  651. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  652. func (a *Agent) ProvisionDOCR(
  653. projectID uint,
  654. doConf *integrations.OAuthIntegration,
  655. doAuth *oauth2.Config,
  656. repo repository.Repository,
  657. docrName, docrSubscriptionTier string,
  658. infra *models.Infra,
  659. operation provisioner.ProvisionerOperation,
  660. pgConf *config.DBConf,
  661. redisConf *config.RedisConf,
  662. provImageTag string,
  663. ) (*batchv1.Job, error) {
  664. // get the token
  665. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  666. infra.DOIntegrationID,
  667. )
  668. if err != nil {
  669. return nil, err
  670. }
  671. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  672. if err != nil {
  673. return nil, err
  674. }
  675. id := infra.GetUniqueName()
  676. prov := &provisioner.Conf{
  677. ID: id,
  678. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  679. Kind: provisioner.DOCR,
  680. Operation: operation,
  681. Redis: redisConf,
  682. Postgres: pgConf,
  683. ProvisionerImageTag: provImageTag,
  684. LastApplied: infra.LastApplied,
  685. DO: &do.Conf{
  686. DOToken: tok,
  687. },
  688. DOCR: &docr.Conf{
  689. DOCRName: docrName,
  690. DOCRSubscriptionTier: docrSubscriptionTier,
  691. },
  692. }
  693. return a.provision(prov, infra, repo)
  694. }
  695. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  696. func (a *Agent) ProvisionDOKS(
  697. projectID uint,
  698. doConf *integrations.OAuthIntegration,
  699. doAuth *oauth2.Config,
  700. repo repository.Repository,
  701. doRegion, doksClusterName string,
  702. infra *models.Infra,
  703. operation provisioner.ProvisionerOperation,
  704. pgConf *config.DBConf,
  705. redisConf *config.RedisConf,
  706. provImageTag string,
  707. ) (*batchv1.Job, error) {
  708. // get the token
  709. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  710. infra.DOIntegrationID,
  711. )
  712. if err != nil {
  713. return nil, err
  714. }
  715. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  716. if err != nil {
  717. return nil, err
  718. }
  719. id := infra.GetUniqueName()
  720. prov := &provisioner.Conf{
  721. ID: id,
  722. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  723. Kind: provisioner.DOKS,
  724. Operation: operation,
  725. Redis: redisConf,
  726. Postgres: pgConf,
  727. LastApplied: infra.LastApplied,
  728. ProvisionerImageTag: provImageTag,
  729. DO: &do.Conf{
  730. DOToken: tok,
  731. },
  732. DOKS: &doks.Conf{
  733. DORegion: doRegion,
  734. DOKSClusterName: doksClusterName,
  735. },
  736. }
  737. return a.provision(prov, infra, repo)
  738. }
  739. // ProvisionTest spawns a new provisioning pod that tests provisioning
  740. func (a *Agent) ProvisionTest(
  741. projectID uint,
  742. infra *models.Infra,
  743. repo repository.Repository,
  744. operation provisioner.ProvisionerOperation,
  745. pgConf *config.DBConf,
  746. redisConf *config.RedisConf,
  747. provImageTag string,
  748. ) (*batchv1.Job, error) {
  749. id := infra.GetUniqueName()
  750. prov := &provisioner.Conf{
  751. ID: id,
  752. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  753. Operation: operation,
  754. Kind: provisioner.Test,
  755. Redis: redisConf,
  756. Postgres: pgConf,
  757. ProvisionerImageTag: provImageTag,
  758. }
  759. return a.provision(prov, infra, repo)
  760. }
  761. func (a *Agent) provision(
  762. prov *provisioner.Conf,
  763. infra *models.Infra,
  764. repo repository.Repository,
  765. ) (*batchv1.Job, error) {
  766. prov.Namespace = "default"
  767. job, err := prov.GetProvisionerJobTemplate()
  768. if err != nil {
  769. return nil, err
  770. }
  771. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  772. context.TODO(),
  773. job,
  774. metav1.CreateOptions{},
  775. )
  776. if err != nil {
  777. return nil, err
  778. }
  779. infra.LastApplied = prov.LastApplied
  780. infra, err = repo.Infra.UpdateInfra(infra)
  781. if err != nil {
  782. return nil, err
  783. }
  784. return job, nil
  785. }
  786. // CreateImagePullSecrets will create the required image pull secrets and
  787. // return a map from the registry name to the name of the secret.
  788. func (a *Agent) CreateImagePullSecrets(
  789. repo repository.Repository,
  790. namespace string,
  791. linkedRegs map[string]*models.Registry,
  792. doAuth *oauth2.Config,
  793. ) (map[string]string, error) {
  794. res := make(map[string]string)
  795. for key, val := range linkedRegs {
  796. _reg := registry.Registry(*val)
  797. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  798. if err != nil {
  799. return nil, err
  800. }
  801. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  802. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  803. context.TODO(),
  804. secretName,
  805. metav1.GetOptions{},
  806. )
  807. // if not found, create the secret
  808. if err != nil && errors.IsNotFound(err) {
  809. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  810. context.TODO(),
  811. &v1.Secret{
  812. ObjectMeta: metav1.ObjectMeta{
  813. Name: secretName,
  814. },
  815. Data: map[string][]byte{
  816. string(v1.DockerConfigJsonKey): data,
  817. },
  818. Type: v1.SecretTypeDockerConfigJson,
  819. },
  820. metav1.CreateOptions{},
  821. )
  822. if err != nil {
  823. return nil, err
  824. }
  825. // add secret name to the map
  826. res[key] = secretName
  827. continue
  828. } else if err != nil {
  829. return nil, err
  830. }
  831. // otherwise, check that the secret contains the correct data: if
  832. // if doesn't, update it
  833. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  834. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  835. context.TODO(),
  836. &v1.Secret{
  837. ObjectMeta: metav1.ObjectMeta{
  838. Name: secretName,
  839. },
  840. Data: map[string][]byte{
  841. string(v1.DockerConfigJsonKey): data,
  842. },
  843. Type: v1.SecretTypeDockerConfigJson,
  844. },
  845. metav1.UpdateOptions{},
  846. )
  847. if err != nil {
  848. return nil, err
  849. }
  850. }
  851. // add secret name to the map
  852. res[key] = secretName
  853. }
  854. return res, nil
  855. }