agent.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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, selectors string) error {
  445. // selectors is an array of max length 1. StreamControllerStatus accepts calls without the selectors argument.
  446. // selectors argument is a single string with comma separated key=value pairs. (e.g. "app=porter,porter=true")
  447. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  448. options.LabelSelector = selectors
  449. }
  450. factory := informers.NewSharedInformerFactoryWithOptions(
  451. a.Clientset,
  452. 0,
  453. informers.WithTweakListOptions(tweakListOptionsFunc),
  454. )
  455. var informer cache.SharedInformer
  456. // Spins up an informer depending on kind. Convert to lowercase for robustness
  457. switch strings.ToLower(kind) {
  458. case "deployment":
  459. informer = factory.Apps().V1().Deployments().Informer()
  460. case "statefulset":
  461. informer = factory.Apps().V1().StatefulSets().Informer()
  462. case "replicaset":
  463. informer = factory.Apps().V1().ReplicaSets().Informer()
  464. case "daemonset":
  465. informer = factory.Apps().V1().DaemonSets().Informer()
  466. case "job":
  467. informer = factory.Batch().V1().Jobs().Informer()
  468. case "cronjob":
  469. informer = factory.Batch().V1beta1().CronJobs().Informer()
  470. case "namespace":
  471. informer = factory.Core().V1().Namespaces().Informer()
  472. case "pod":
  473. informer = factory.Core().V1().Pods().Informer()
  474. }
  475. stopper := make(chan struct{})
  476. errorchan := make(chan error)
  477. defer close(errorchan)
  478. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  479. UpdateFunc: func(oldObj, newObj interface{}) {
  480. msg := Message{
  481. EventType: "UPDATE",
  482. Object: newObj,
  483. Kind: strings.ToLower(kind),
  484. }
  485. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  486. errorchan <- writeErr
  487. return
  488. }
  489. },
  490. AddFunc: func(obj interface{}) {
  491. msg := Message{
  492. EventType: "ADD",
  493. Object: obj,
  494. Kind: strings.ToLower(kind),
  495. }
  496. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  497. errorchan <- writeErr
  498. return
  499. }
  500. },
  501. DeleteFunc: func(obj interface{}) {
  502. msg := Message{
  503. EventType: "DELETE",
  504. Object: obj,
  505. Kind: strings.ToLower(kind),
  506. }
  507. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  508. errorchan <- writeErr
  509. return
  510. }
  511. },
  512. })
  513. go func() {
  514. // listens for websocket closing handshake
  515. for {
  516. if _, _, err := conn.ReadMessage(); err != nil {
  517. defer conn.Close()
  518. defer close(stopper)
  519. errorchan <- nil
  520. return
  521. }
  522. }
  523. }()
  524. go informer.Run(stopper)
  525. for {
  526. select {
  527. case err := <-errorchan:
  528. return err
  529. }
  530. }
  531. }
  532. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  533. func (a *Agent) ProvisionECR(
  534. projectID uint,
  535. awsConf *integrations.AWSIntegration,
  536. ecrName string,
  537. repo repository.Repository,
  538. infra *models.Infra,
  539. operation provisioner.ProvisionerOperation,
  540. pgConf *config.DBConf,
  541. redisConf *config.RedisConf,
  542. provImageTag string,
  543. ) (*batchv1.Job, error) {
  544. id := infra.GetUniqueName()
  545. prov := &provisioner.Conf{
  546. ID: id,
  547. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  548. Kind: provisioner.ECR,
  549. Operation: operation,
  550. Redis: redisConf,
  551. Postgres: pgConf,
  552. ProvisionerImageTag: provImageTag,
  553. LastApplied: infra.LastApplied,
  554. AWS: &aws.Conf{
  555. AWSRegion: awsConf.AWSRegion,
  556. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  557. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  558. },
  559. ECR: &ecr.Conf{
  560. ECRName: ecrName,
  561. },
  562. }
  563. return a.provision(prov, infra, repo)
  564. }
  565. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  566. func (a *Agent) ProvisionEKS(
  567. projectID uint,
  568. awsConf *integrations.AWSIntegration,
  569. eksName, machineType string,
  570. repo repository.Repository,
  571. infra *models.Infra,
  572. operation provisioner.ProvisionerOperation,
  573. pgConf *config.DBConf,
  574. redisConf *config.RedisConf,
  575. provImageTag string,
  576. ) (*batchv1.Job, error) {
  577. id := infra.GetUniqueName()
  578. prov := &provisioner.Conf{
  579. ID: id,
  580. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  581. Kind: provisioner.EKS,
  582. Operation: operation,
  583. Redis: redisConf,
  584. Postgres: pgConf,
  585. ProvisionerImageTag: provImageTag,
  586. LastApplied: infra.LastApplied,
  587. AWS: &aws.Conf{
  588. AWSRegion: awsConf.AWSRegion,
  589. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  590. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  591. },
  592. EKS: &eks.Conf{
  593. ClusterName: eksName,
  594. MachineType: machineType,
  595. },
  596. }
  597. return a.provision(prov, infra, repo)
  598. }
  599. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  600. func (a *Agent) ProvisionGCR(
  601. projectID uint,
  602. gcpConf *integrations.GCPIntegration,
  603. repo repository.Repository,
  604. infra *models.Infra,
  605. operation provisioner.ProvisionerOperation,
  606. pgConf *config.DBConf,
  607. redisConf *config.RedisConf,
  608. provImageTag string,
  609. ) (*batchv1.Job, error) {
  610. id := infra.GetUniqueName()
  611. prov := &provisioner.Conf{
  612. ID: id,
  613. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  614. Kind: provisioner.GCR,
  615. Operation: operation,
  616. Redis: redisConf,
  617. Postgres: pgConf,
  618. ProvisionerImageTag: provImageTag,
  619. LastApplied: infra.LastApplied,
  620. GCP: &gcp.Conf{
  621. GCPRegion: gcpConf.GCPRegion,
  622. GCPProjectID: gcpConf.GCPProjectID,
  623. GCPKeyData: string(gcpConf.GCPKeyData),
  624. },
  625. }
  626. return a.provision(prov, infra, repo)
  627. }
  628. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  629. func (a *Agent) ProvisionGKE(
  630. projectID uint,
  631. gcpConf *integrations.GCPIntegration,
  632. gkeName string,
  633. repo repository.Repository,
  634. infra *models.Infra,
  635. operation provisioner.ProvisionerOperation,
  636. pgConf *config.DBConf,
  637. redisConf *config.RedisConf,
  638. provImageTag string,
  639. ) (*batchv1.Job, error) {
  640. id := infra.GetUniqueName()
  641. prov := &provisioner.Conf{
  642. ID: id,
  643. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  644. Kind: provisioner.GKE,
  645. Operation: operation,
  646. Redis: redisConf,
  647. Postgres: pgConf,
  648. ProvisionerImageTag: provImageTag,
  649. LastApplied: infra.LastApplied,
  650. GCP: &gcp.Conf{
  651. GCPRegion: gcpConf.GCPRegion,
  652. GCPProjectID: gcpConf.GCPProjectID,
  653. GCPKeyData: string(gcpConf.GCPKeyData),
  654. },
  655. GKE: &gke.Conf{
  656. ClusterName: gkeName,
  657. },
  658. }
  659. return a.provision(prov, infra, repo)
  660. }
  661. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  662. func (a *Agent) ProvisionDOCR(
  663. projectID uint,
  664. doConf *integrations.OAuthIntegration,
  665. doAuth *oauth2.Config,
  666. repo repository.Repository,
  667. docrName, docrSubscriptionTier string,
  668. infra *models.Infra,
  669. operation provisioner.ProvisionerOperation,
  670. pgConf *config.DBConf,
  671. redisConf *config.RedisConf,
  672. provImageTag string,
  673. ) (*batchv1.Job, error) {
  674. // get the token
  675. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  676. infra.DOIntegrationID,
  677. )
  678. if err != nil {
  679. return nil, err
  680. }
  681. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  682. if err != nil {
  683. return nil, err
  684. }
  685. id := infra.GetUniqueName()
  686. prov := &provisioner.Conf{
  687. ID: id,
  688. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  689. Kind: provisioner.DOCR,
  690. Operation: operation,
  691. Redis: redisConf,
  692. Postgres: pgConf,
  693. ProvisionerImageTag: provImageTag,
  694. LastApplied: infra.LastApplied,
  695. DO: &do.Conf{
  696. DOToken: tok,
  697. },
  698. DOCR: &docr.Conf{
  699. DOCRName: docrName,
  700. DOCRSubscriptionTier: docrSubscriptionTier,
  701. },
  702. }
  703. return a.provision(prov, infra, repo)
  704. }
  705. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  706. func (a *Agent) ProvisionDOKS(
  707. projectID uint,
  708. doConf *integrations.OAuthIntegration,
  709. doAuth *oauth2.Config,
  710. repo repository.Repository,
  711. doRegion, doksClusterName string,
  712. infra *models.Infra,
  713. operation provisioner.ProvisionerOperation,
  714. pgConf *config.DBConf,
  715. redisConf *config.RedisConf,
  716. provImageTag string,
  717. ) (*batchv1.Job, error) {
  718. // get the token
  719. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  720. infra.DOIntegrationID,
  721. )
  722. if err != nil {
  723. return nil, err
  724. }
  725. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  726. if err != nil {
  727. return nil, err
  728. }
  729. id := infra.GetUniqueName()
  730. prov := &provisioner.Conf{
  731. ID: id,
  732. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  733. Kind: provisioner.DOKS,
  734. Operation: operation,
  735. Redis: redisConf,
  736. Postgres: pgConf,
  737. LastApplied: infra.LastApplied,
  738. ProvisionerImageTag: provImageTag,
  739. DO: &do.Conf{
  740. DOToken: tok,
  741. },
  742. DOKS: &doks.Conf{
  743. DORegion: doRegion,
  744. DOKSClusterName: doksClusterName,
  745. },
  746. }
  747. return a.provision(prov, infra, repo)
  748. }
  749. // ProvisionTest spawns a new provisioning pod that tests provisioning
  750. func (a *Agent) ProvisionTest(
  751. projectID uint,
  752. infra *models.Infra,
  753. repo repository.Repository,
  754. operation provisioner.ProvisionerOperation,
  755. pgConf *config.DBConf,
  756. redisConf *config.RedisConf,
  757. provImageTag string,
  758. ) (*batchv1.Job, error) {
  759. id := infra.GetUniqueName()
  760. prov := &provisioner.Conf{
  761. ID: id,
  762. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  763. Operation: operation,
  764. Kind: provisioner.Test,
  765. Redis: redisConf,
  766. Postgres: pgConf,
  767. ProvisionerImageTag: provImageTag,
  768. }
  769. return a.provision(prov, infra, repo)
  770. }
  771. func (a *Agent) provision(
  772. prov *provisioner.Conf,
  773. infra *models.Infra,
  774. repo repository.Repository,
  775. ) (*batchv1.Job, error) {
  776. prov.Namespace = "default"
  777. job, err := prov.GetProvisionerJobTemplate()
  778. if err != nil {
  779. return nil, err
  780. }
  781. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  782. context.TODO(),
  783. job,
  784. metav1.CreateOptions{},
  785. )
  786. if err != nil {
  787. return nil, err
  788. }
  789. infra.LastApplied = prov.LastApplied
  790. infra, err = repo.Infra.UpdateInfra(infra)
  791. if err != nil {
  792. return nil, err
  793. }
  794. return job, nil
  795. }
  796. // CreateImagePullSecrets will create the required image pull secrets and
  797. // return a map from the registry name to the name of the secret.
  798. func (a *Agent) CreateImagePullSecrets(
  799. repo repository.Repository,
  800. namespace string,
  801. linkedRegs map[string]*models.Registry,
  802. doAuth *oauth2.Config,
  803. ) (map[string]string, error) {
  804. res := make(map[string]string)
  805. for key, val := range linkedRegs {
  806. _reg := registry.Registry(*val)
  807. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  808. if err != nil {
  809. return nil, err
  810. }
  811. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  812. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  813. context.TODO(),
  814. secretName,
  815. metav1.GetOptions{},
  816. )
  817. // if not found, create the secret
  818. if err != nil && errors.IsNotFound(err) {
  819. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  820. context.TODO(),
  821. &v1.Secret{
  822. ObjectMeta: metav1.ObjectMeta{
  823. Name: secretName,
  824. },
  825. Data: map[string][]byte{
  826. string(v1.DockerConfigJsonKey): data,
  827. },
  828. Type: v1.SecretTypeDockerConfigJson,
  829. },
  830. metav1.CreateOptions{},
  831. )
  832. if err != nil {
  833. return nil, err
  834. }
  835. // add secret name to the map
  836. res[key] = secretName
  837. continue
  838. } else if err != nil {
  839. return nil, err
  840. }
  841. // otherwise, check that the secret contains the correct data: if
  842. // if doesn't, update it
  843. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  844. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  845. context.TODO(),
  846. &v1.Secret{
  847. ObjectMeta: metav1.ObjectMeta{
  848. Name: secretName,
  849. },
  850. Data: map[string][]byte{
  851. string(v1.DockerConfigJsonKey): data,
  852. },
  853. Type: v1.SecretTypeDockerConfigJson,
  854. },
  855. metav1.UpdateOptions{},
  856. )
  857. if err != nil {
  858. return nil, err
  859. }
  860. }
  861. // add secret name to the map
  862. res[key] = secretName
  863. }
  864. return res, nil
  865. }