agent.go 29 KB

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