agent.go 30 KB

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