agent.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. // GetJobPods lists all pods belonging to a job in a namespace
  245. func (a *Agent) GetJobPods(namespace, jobName string) ([]v1.Pod, error) {
  246. resp, err := a.Clientset.CoreV1().Pods(namespace).List(
  247. context.TODO(),
  248. metav1.ListOptions{
  249. LabelSelector: fmt.Sprintf("%s=%s", "job-name", jobName),
  250. },
  251. )
  252. if err != nil {
  253. return nil, err
  254. }
  255. return resp.Items, nil
  256. }
  257. // GetIngress gets ingress given the name and namespace
  258. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  259. return a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  260. context.TODO(),
  261. name,
  262. metav1.GetOptions{},
  263. )
  264. }
  265. // GetDeployment gets the deployment given the name and namespace
  266. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  267. return a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  268. context.TODO(),
  269. c.Name,
  270. metav1.GetOptions{},
  271. )
  272. }
  273. // GetStatefulSet gets the statefulset given the name and namespace
  274. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  275. return a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  276. context.TODO(),
  277. c.Name,
  278. metav1.GetOptions{},
  279. )
  280. }
  281. // GetReplicaSet gets the replicaset given the name and namespace
  282. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  283. return a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  284. context.TODO(),
  285. c.Name,
  286. metav1.GetOptions{},
  287. )
  288. }
  289. // GetDaemonSet gets the daemonset by name and namespace
  290. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  291. return a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  292. context.TODO(),
  293. c.Name,
  294. metav1.GetOptions{},
  295. )
  296. }
  297. // GetJob gets the job by name and namespace
  298. func (a *Agent) GetJob(c grapher.Object) (*batchv1.Job, error) {
  299. return a.Clientset.BatchV1().Jobs(c.Namespace).Get(
  300. context.TODO(),
  301. c.Name,
  302. metav1.GetOptions{},
  303. )
  304. }
  305. // GetCronJob gets the CronJob by name and namespace
  306. func (a *Agent) GetCronJob(c grapher.Object) (*batchv1beta1.CronJob, error) {
  307. return a.Clientset.BatchV1beta1().CronJobs(c.Namespace).Get(
  308. context.TODO(),
  309. c.Name,
  310. metav1.GetOptions{},
  311. )
  312. }
  313. // GetPodsByLabel retrieves pods with matching labels
  314. func (a *Agent) GetPodsByLabel(selector string, namespace string) (*v1.PodList, error) {
  315. // Search in all namespaces for matching pods
  316. return a.Clientset.CoreV1().Pods(namespace).List(
  317. context.TODO(),
  318. metav1.ListOptions{
  319. LabelSelector: selector,
  320. },
  321. )
  322. }
  323. // DeletePod deletes a pod by name and namespace
  324. func (a *Agent) DeletePod(namespace string, name string) error {
  325. return a.Clientset.CoreV1().Pods(namespace).Delete(
  326. context.TODO(),
  327. name,
  328. metav1.DeleteOptions{},
  329. )
  330. }
  331. // GetPodLogs streams real-time logs from a given pod.
  332. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  333. // get the pod to read in the list of contains
  334. pod, err := a.Clientset.CoreV1().Pods(namespace).Get(
  335. context.Background(),
  336. name,
  337. metav1.GetOptions{},
  338. )
  339. if err != nil {
  340. return fmt.Errorf("Cannot get pod %s: %s", name, err.Error())
  341. }
  342. container := pod.Spec.Containers[0].Name
  343. tails := int64(400)
  344. // follow logs
  345. podLogOpts := v1.PodLogOptions{
  346. Follow: true,
  347. TailLines: &tails,
  348. Container: container,
  349. }
  350. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  351. podLogs, err := req.Stream(context.TODO())
  352. if err != nil {
  353. return fmt.Errorf("Cannot open log stream for pod %s: %s", name, err.Error())
  354. }
  355. defer podLogs.Close()
  356. r := bufio.NewReader(podLogs)
  357. errorchan := make(chan error)
  358. go func() {
  359. // listens for websocket closing handshake
  360. for {
  361. if _, _, err := conn.ReadMessage(); err != nil {
  362. defer conn.Close()
  363. errorchan <- nil
  364. return
  365. }
  366. }
  367. }()
  368. go func() {
  369. for {
  370. select {
  371. case <-errorchan:
  372. defer close(errorchan)
  373. return
  374. default:
  375. }
  376. bytes, err := r.ReadBytes('\n')
  377. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  378. errorchan <- writeErr
  379. return
  380. }
  381. if err != nil {
  382. if err != io.EOF {
  383. errorchan <- err
  384. return
  385. }
  386. errorchan <- nil
  387. return
  388. }
  389. }
  390. }()
  391. for {
  392. select {
  393. case err = <-errorchan:
  394. return err
  395. }
  396. }
  397. }
  398. // StopJobWithJobSidecar sends a termination signal to a job running with a sidecar
  399. func (a *Agent) StopJobWithJobSidecar(namespace, name string) error {
  400. jobPods, err := a.GetJobPods(namespace, name)
  401. if err != nil {
  402. return err
  403. }
  404. podName := jobPods[0].ObjectMeta.Name
  405. restConf, err := a.RESTClientGetter.ToRESTConfig()
  406. restConf.GroupVersion = &schema.GroupVersion{
  407. Group: "api",
  408. Version: "v1",
  409. }
  410. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  411. restClient, err := rest.RESTClientFor(restConf)
  412. if err != nil {
  413. return err
  414. }
  415. req := restClient.Post().
  416. Resource("pods").
  417. Name(podName).
  418. Namespace(namespace).
  419. SubResource("exec")
  420. req.Param("command", "./signal.sh")
  421. req.Param("container", "sidecar")
  422. req.Param("stdin", "true")
  423. req.Param("stdout", "false")
  424. req.Param("tty", "false")
  425. exec, err := remotecommand.NewSPDYExecutor(restConf, "POST", req.URL())
  426. if err != nil {
  427. return err
  428. }
  429. return exec.Stream(remotecommand.StreamOptions{
  430. Tty: false,
  431. Stdin: strings.NewReader("./signal.sh"),
  432. })
  433. }
  434. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  435. // TODO: Support Jobs
  436. func (a *Agent) StreamControllerStatus(conn *websocket.Conn, kind string) error {
  437. factory := informers.NewSharedInformerFactory(
  438. a.Clientset,
  439. 0,
  440. )
  441. var informer cache.SharedInformer
  442. // Spins up an informer depending on kind. Convert to lowercase for robustness
  443. switch strings.ToLower(kind) {
  444. case "deployment":
  445. informer = factory.Apps().V1().Deployments().Informer()
  446. case "statefulset":
  447. informer = factory.Apps().V1().StatefulSets().Informer()
  448. case "replicaset":
  449. informer = factory.Apps().V1().ReplicaSets().Informer()
  450. case "daemonset":
  451. informer = factory.Apps().V1().DaemonSets().Informer()
  452. case "job":
  453. informer = factory.Batch().V1().Jobs().Informer()
  454. case "cronjob":
  455. informer = factory.Batch().V1beta1().CronJobs().Informer()
  456. }
  457. stopper := make(chan struct{})
  458. errorchan := make(chan error)
  459. defer close(errorchan)
  460. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  461. UpdateFunc: func(oldObj, newObj interface{}) {
  462. msg := Message{
  463. EventType: "UPDATE",
  464. Object: newObj,
  465. Kind: strings.ToLower(kind),
  466. }
  467. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  468. errorchan <- writeErr
  469. return
  470. }
  471. },
  472. AddFunc: func(obj interface{}) {
  473. msg := Message{
  474. EventType: "ADD",
  475. Object: obj,
  476. Kind: strings.ToLower(kind),
  477. }
  478. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  479. errorchan <- writeErr
  480. return
  481. }
  482. },
  483. DeleteFunc: func(obj interface{}) {
  484. msg := Message{
  485. EventType: "DELETE",
  486. Object: obj,
  487. Kind: strings.ToLower(kind),
  488. }
  489. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  490. errorchan <- writeErr
  491. return
  492. }
  493. },
  494. })
  495. go func() {
  496. // listens for websocket closing handshake
  497. for {
  498. if _, _, err := conn.ReadMessage(); err != nil {
  499. defer conn.Close()
  500. defer close(stopper)
  501. errorchan <- nil
  502. return
  503. }
  504. }
  505. }()
  506. go informer.Run(stopper)
  507. for {
  508. select {
  509. case err := <-errorchan:
  510. return err
  511. }
  512. }
  513. }
  514. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  515. func (a *Agent) ProvisionECR(
  516. projectID uint,
  517. awsConf *integrations.AWSIntegration,
  518. ecrName string,
  519. repo repository.Repository,
  520. infra *models.Infra,
  521. operation provisioner.ProvisionerOperation,
  522. pgConf *config.DBConf,
  523. redisConf *config.RedisConf,
  524. provImageTag string,
  525. ) (*batchv1.Job, error) {
  526. id := infra.GetUniqueName()
  527. prov := &provisioner.Conf{
  528. ID: id,
  529. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  530. Kind: provisioner.ECR,
  531. Operation: operation,
  532. Redis: redisConf,
  533. Postgres: pgConf,
  534. ProvisionerImageTag: provImageTag,
  535. LastApplied: infra.LastApplied,
  536. AWS: &aws.Conf{
  537. AWSRegion: awsConf.AWSRegion,
  538. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  539. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  540. },
  541. ECR: &ecr.Conf{
  542. ECRName: ecrName,
  543. },
  544. }
  545. return a.provision(prov, infra, repo)
  546. }
  547. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  548. func (a *Agent) ProvisionEKS(
  549. projectID uint,
  550. awsConf *integrations.AWSIntegration,
  551. eksName, machineType string,
  552. repo repository.Repository,
  553. infra *models.Infra,
  554. operation provisioner.ProvisionerOperation,
  555. pgConf *config.DBConf,
  556. redisConf *config.RedisConf,
  557. provImageTag string,
  558. ) (*batchv1.Job, error) {
  559. id := infra.GetUniqueName()
  560. prov := &provisioner.Conf{
  561. ID: id,
  562. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  563. Kind: provisioner.EKS,
  564. Operation: operation,
  565. Redis: redisConf,
  566. Postgres: pgConf,
  567. ProvisionerImageTag: provImageTag,
  568. LastApplied: infra.LastApplied,
  569. AWS: &aws.Conf{
  570. AWSRegion: awsConf.AWSRegion,
  571. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  572. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  573. },
  574. EKS: &eks.Conf{
  575. ClusterName: eksName,
  576. MachineType: machineType,
  577. },
  578. }
  579. return a.provision(prov, infra, repo)
  580. }
  581. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  582. func (a *Agent) ProvisionGCR(
  583. projectID uint,
  584. gcpConf *integrations.GCPIntegration,
  585. repo repository.Repository,
  586. infra *models.Infra,
  587. operation provisioner.ProvisionerOperation,
  588. pgConf *config.DBConf,
  589. redisConf *config.RedisConf,
  590. provImageTag string,
  591. ) (*batchv1.Job, error) {
  592. id := infra.GetUniqueName()
  593. prov := &provisioner.Conf{
  594. ID: id,
  595. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  596. Kind: provisioner.GCR,
  597. Operation: operation,
  598. Redis: redisConf,
  599. Postgres: pgConf,
  600. ProvisionerImageTag: provImageTag,
  601. LastApplied: infra.LastApplied,
  602. GCP: &gcp.Conf{
  603. GCPRegion: gcpConf.GCPRegion,
  604. GCPProjectID: gcpConf.GCPProjectID,
  605. GCPKeyData: string(gcpConf.GCPKeyData),
  606. },
  607. }
  608. return a.provision(prov, infra, repo)
  609. }
  610. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  611. func (a *Agent) ProvisionGKE(
  612. projectID uint,
  613. gcpConf *integrations.GCPIntegration,
  614. gkeName string,
  615. repo repository.Repository,
  616. infra *models.Infra,
  617. operation provisioner.ProvisionerOperation,
  618. pgConf *config.DBConf,
  619. redisConf *config.RedisConf,
  620. provImageTag string,
  621. ) (*batchv1.Job, error) {
  622. id := infra.GetUniqueName()
  623. prov := &provisioner.Conf{
  624. ID: id,
  625. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  626. Kind: provisioner.GKE,
  627. Operation: operation,
  628. Redis: redisConf,
  629. Postgres: pgConf,
  630. ProvisionerImageTag: provImageTag,
  631. LastApplied: infra.LastApplied,
  632. GCP: &gcp.Conf{
  633. GCPRegion: gcpConf.GCPRegion,
  634. GCPProjectID: gcpConf.GCPProjectID,
  635. GCPKeyData: string(gcpConf.GCPKeyData),
  636. },
  637. GKE: &gke.Conf{
  638. ClusterName: gkeName,
  639. },
  640. }
  641. return a.provision(prov, infra, repo)
  642. }
  643. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  644. func (a *Agent) ProvisionDOCR(
  645. projectID uint,
  646. doConf *integrations.OAuthIntegration,
  647. doAuth *oauth2.Config,
  648. repo repository.Repository,
  649. docrName, docrSubscriptionTier string,
  650. infra *models.Infra,
  651. operation provisioner.ProvisionerOperation,
  652. pgConf *config.DBConf,
  653. redisConf *config.RedisConf,
  654. provImageTag string,
  655. ) (*batchv1.Job, error) {
  656. // get the token
  657. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  658. infra.DOIntegrationID,
  659. )
  660. if err != nil {
  661. return nil, err
  662. }
  663. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  664. if err != nil {
  665. return nil, err
  666. }
  667. id := infra.GetUniqueName()
  668. prov := &provisioner.Conf{
  669. ID: id,
  670. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  671. Kind: provisioner.DOCR,
  672. Operation: operation,
  673. Redis: redisConf,
  674. Postgres: pgConf,
  675. ProvisionerImageTag: provImageTag,
  676. LastApplied: infra.LastApplied,
  677. DO: &do.Conf{
  678. DOToken: tok,
  679. },
  680. DOCR: &docr.Conf{
  681. DOCRName: docrName,
  682. DOCRSubscriptionTier: docrSubscriptionTier,
  683. },
  684. }
  685. return a.provision(prov, infra, repo)
  686. }
  687. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  688. func (a *Agent) ProvisionDOKS(
  689. projectID uint,
  690. doConf *integrations.OAuthIntegration,
  691. doAuth *oauth2.Config,
  692. repo repository.Repository,
  693. doRegion, doksClusterName string,
  694. infra *models.Infra,
  695. operation provisioner.ProvisionerOperation,
  696. pgConf *config.DBConf,
  697. redisConf *config.RedisConf,
  698. provImageTag string,
  699. ) (*batchv1.Job, error) {
  700. // get the token
  701. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  702. infra.DOIntegrationID,
  703. )
  704. if err != nil {
  705. return nil, err
  706. }
  707. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  708. if err != nil {
  709. return nil, err
  710. }
  711. id := infra.GetUniqueName()
  712. prov := &provisioner.Conf{
  713. ID: id,
  714. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  715. Kind: provisioner.DOKS,
  716. Operation: operation,
  717. Redis: redisConf,
  718. Postgres: pgConf,
  719. LastApplied: infra.LastApplied,
  720. ProvisionerImageTag: provImageTag,
  721. DO: &do.Conf{
  722. DOToken: tok,
  723. },
  724. DOKS: &doks.Conf{
  725. DORegion: doRegion,
  726. DOKSClusterName: doksClusterName,
  727. },
  728. }
  729. return a.provision(prov, infra, repo)
  730. }
  731. // ProvisionTest spawns a new provisioning pod that tests provisioning
  732. func (a *Agent) ProvisionTest(
  733. projectID uint,
  734. infra *models.Infra,
  735. repo repository.Repository,
  736. operation provisioner.ProvisionerOperation,
  737. pgConf *config.DBConf,
  738. redisConf *config.RedisConf,
  739. provImageTag string,
  740. ) (*batchv1.Job, error) {
  741. id := infra.GetUniqueName()
  742. prov := &provisioner.Conf{
  743. ID: id,
  744. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  745. Operation: operation,
  746. Kind: provisioner.Test,
  747. Redis: redisConf,
  748. Postgres: pgConf,
  749. ProvisionerImageTag: provImageTag,
  750. }
  751. return a.provision(prov, infra, repo)
  752. }
  753. func (a *Agent) provision(
  754. prov *provisioner.Conf,
  755. infra *models.Infra,
  756. repo repository.Repository,
  757. ) (*batchv1.Job, error) {
  758. prov.Namespace = "default"
  759. job, err := prov.GetProvisionerJobTemplate()
  760. if err != nil {
  761. return nil, err
  762. }
  763. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  764. context.TODO(),
  765. job,
  766. metav1.CreateOptions{},
  767. )
  768. if err != nil {
  769. return nil, err
  770. }
  771. infra.LastApplied = prov.LastApplied
  772. infra, err = repo.Infra.UpdateInfra(infra)
  773. if err != nil {
  774. return nil, err
  775. }
  776. return job, nil
  777. }
  778. // CreateImagePullSecrets will create the required image pull secrets and
  779. // return a map from the registry name to the name of the secret.
  780. func (a *Agent) CreateImagePullSecrets(
  781. repo repository.Repository,
  782. namespace string,
  783. linkedRegs map[string]*models.Registry,
  784. doAuth *oauth2.Config,
  785. ) (map[string]string, error) {
  786. res := make(map[string]string)
  787. for key, val := range linkedRegs {
  788. _reg := registry.Registry(*val)
  789. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  790. if err != nil {
  791. return nil, err
  792. }
  793. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  794. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  795. context.TODO(),
  796. secretName,
  797. metav1.GetOptions{},
  798. )
  799. // if not found, create the secret
  800. if err != nil && errors.IsNotFound(err) {
  801. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  802. context.TODO(),
  803. &v1.Secret{
  804. ObjectMeta: metav1.ObjectMeta{
  805. Name: secretName,
  806. },
  807. Data: map[string][]byte{
  808. string(v1.DockerConfigJsonKey): data,
  809. },
  810. Type: v1.SecretTypeDockerConfigJson,
  811. },
  812. metav1.CreateOptions{},
  813. )
  814. if err != nil {
  815. return nil, err
  816. }
  817. // add secret name to the map
  818. res[key] = secretName
  819. continue
  820. } else if err != nil {
  821. return nil, err
  822. }
  823. // otherwise, check that the secret contains the correct data: if
  824. // if doesn't, update it
  825. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  826. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  827. context.TODO(),
  828. &v1.Secret{
  829. ObjectMeta: metav1.ObjectMeta{
  830. Name: secretName,
  831. },
  832. Data: map[string][]byte{
  833. string(v1.DockerConfigJsonKey): data,
  834. },
  835. Type: v1.SecretTypeDockerConfigJson,
  836. },
  837. metav1.UpdateOptions{},
  838. )
  839. if err != nil {
  840. return nil, err
  841. }
  842. }
  843. // add secret name to the map
  844. res[key] = secretName
  845. }
  846. return res, nil
  847. }