agent.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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, namespace string, 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. informers.WithNamespace(namespace),
  636. )
  637. informer := factory.Core().V1().Secrets().Informer()
  638. stopper := make(chan struct{})
  639. errorchan := make(chan error)
  640. defer close(stopper)
  641. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  642. UpdateFunc: func(oldObj, newObj interface{}) {
  643. secretObj, ok := newObj.(*v1.Secret)
  644. if !ok {
  645. errorchan <- fmt.Errorf("could not cast to secret")
  646. return
  647. }
  648. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  649. if isNotHelmRelease && err == nil {
  650. return
  651. }
  652. if err != nil {
  653. errorchan <- err
  654. return
  655. }
  656. msg := Message{
  657. EventType: "UPDATE",
  658. Object: helm_object,
  659. }
  660. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  661. errorchan <- writeErr
  662. return
  663. }
  664. },
  665. AddFunc: func(obj interface{}) {
  666. secretObj, ok := obj.(*v1.Secret)
  667. if !ok {
  668. errorchan <- fmt.Errorf("could not cast to secret")
  669. return
  670. }
  671. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  672. if isNotHelmRelease && err == nil {
  673. return
  674. }
  675. if err != nil {
  676. errorchan <- err
  677. return
  678. }
  679. msg := Message{
  680. EventType: "ADD",
  681. Object: helm_object,
  682. }
  683. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  684. errorchan <- writeErr
  685. return
  686. }
  687. },
  688. DeleteFunc: func(obj interface{}) {
  689. secretObj, ok := obj.(*v1.Secret)
  690. if !ok {
  691. errorchan <- fmt.Errorf("could not cast to secret")
  692. return
  693. }
  694. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  695. if isNotHelmRelease && err == nil {
  696. return
  697. }
  698. if err != nil {
  699. errorchan <- err
  700. return
  701. }
  702. msg := Message{
  703. EventType: "DELETE",
  704. Object: helm_object,
  705. }
  706. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  707. errorchan <- writeErr
  708. return
  709. }
  710. },
  711. })
  712. go func() {
  713. // listens for websocket closing handshake
  714. for {
  715. if _, _, err := conn.ReadMessage(); err != nil {
  716. conn.Close()
  717. errorchan <- nil
  718. return
  719. }
  720. }
  721. }()
  722. go informer.Run(stopper)
  723. for {
  724. select {
  725. case err := <-errorchan:
  726. return err
  727. }
  728. }
  729. }
  730. type SharedProvisionOpts struct {
  731. ProjectID uint
  732. Repo repository.Repository
  733. Infra *models.Infra
  734. Operation provisioner.ProvisionerOperation
  735. PGConf *env.DBConf
  736. RedisConf *env.RedisConf
  737. ProvImageTag string
  738. ProvImagePullSecret string
  739. }
  740. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  741. func (a *Agent) ProvisionECR(
  742. opts *SharedProvisionOpts,
  743. awsConf *integrations.AWSIntegration,
  744. ecrName string,
  745. ) (*batchv1.Job, error) {
  746. id := opts.Infra.GetUniqueName()
  747. prov := &provisioner.Conf{
  748. ID: id,
  749. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  750. Kind: provisioner.ECR,
  751. Operation: opts.Operation,
  752. Redis: opts.RedisConf,
  753. Postgres: opts.PGConf,
  754. ProvisionerImageTag: opts.ProvImageTag,
  755. ImagePullSecret: opts.ProvImagePullSecret,
  756. LastApplied: opts.Infra.LastApplied,
  757. AWS: &aws.Conf{
  758. AWSRegion: awsConf.AWSRegion,
  759. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  760. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  761. },
  762. ECR: &ecr.Conf{
  763. ECRName: ecrName,
  764. },
  765. }
  766. return a.provision(prov, opts.Infra, opts.Repo)
  767. }
  768. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  769. func (a *Agent) ProvisionEKS(
  770. opts *SharedProvisionOpts,
  771. awsConf *integrations.AWSIntegration,
  772. eksName, machineType string,
  773. ) (*batchv1.Job, error) {
  774. id := opts.Infra.GetUniqueName()
  775. prov := &provisioner.Conf{
  776. ID: id,
  777. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  778. Kind: provisioner.EKS,
  779. Operation: opts.Operation,
  780. Redis: opts.RedisConf,
  781. Postgres: opts.PGConf,
  782. ProvisionerImageTag: opts.ProvImageTag,
  783. ImagePullSecret: opts.ProvImagePullSecret,
  784. LastApplied: opts.Infra.LastApplied,
  785. AWS: &aws.Conf{
  786. AWSRegion: awsConf.AWSRegion,
  787. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  788. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  789. },
  790. EKS: &eks.Conf{
  791. ClusterName: eksName,
  792. MachineType: machineType,
  793. },
  794. }
  795. return a.provision(prov, opts.Infra, opts.Repo)
  796. }
  797. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  798. func (a *Agent) ProvisionGCR(
  799. opts *SharedProvisionOpts,
  800. gcpConf *integrations.GCPIntegration,
  801. ) (*batchv1.Job, error) {
  802. id := opts.Infra.GetUniqueName()
  803. prov := &provisioner.Conf{
  804. ID: id,
  805. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  806. Kind: provisioner.GCR,
  807. Operation: opts.Operation,
  808. Redis: opts.RedisConf,
  809. Postgres: opts.PGConf,
  810. ProvisionerImageTag: opts.ProvImageTag,
  811. ImagePullSecret: opts.ProvImagePullSecret,
  812. LastApplied: opts.Infra.LastApplied,
  813. GCP: &gcp.Conf{
  814. GCPRegion: gcpConf.GCPRegion,
  815. GCPProjectID: gcpConf.GCPProjectID,
  816. GCPKeyData: string(gcpConf.GCPKeyData),
  817. },
  818. }
  819. return a.provision(prov, opts.Infra, opts.Repo)
  820. }
  821. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  822. func (a *Agent) ProvisionGKE(
  823. opts *SharedProvisionOpts,
  824. gcpConf *integrations.GCPIntegration,
  825. gkeName string,
  826. ) (*batchv1.Job, error) {
  827. id := opts.Infra.GetUniqueName()
  828. prov := &provisioner.Conf{
  829. ID: id,
  830. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  831. Kind: provisioner.GKE,
  832. Operation: opts.Operation,
  833. Redis: opts.RedisConf,
  834. Postgres: opts.PGConf,
  835. ProvisionerImageTag: opts.ProvImageTag,
  836. ImagePullSecret: opts.ProvImagePullSecret,
  837. LastApplied: opts.Infra.LastApplied,
  838. GCP: &gcp.Conf{
  839. GCPRegion: gcpConf.GCPRegion,
  840. GCPProjectID: gcpConf.GCPProjectID,
  841. GCPKeyData: string(gcpConf.GCPKeyData),
  842. },
  843. GKE: &gke.Conf{
  844. ClusterName: gkeName,
  845. },
  846. }
  847. return a.provision(prov, opts.Infra, opts.Repo)
  848. }
  849. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  850. func (a *Agent) ProvisionDOCR(
  851. opts *SharedProvisionOpts,
  852. doConf *integrations.OAuthIntegration,
  853. doAuth *oauth2.Config,
  854. docrName, docrSubscriptionTier string,
  855. ) (*batchv1.Job, error) {
  856. // get the token
  857. oauthInt, err := opts.Repo.OAuthIntegration().ReadOAuthIntegration(
  858. opts.ProjectID,
  859. opts.Infra.DOIntegrationID,
  860. )
  861. if err != nil {
  862. return nil, err
  863. }
  864. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, opts.Repo))
  865. if err != nil {
  866. return nil, err
  867. }
  868. id := opts.Infra.GetUniqueName()
  869. prov := &provisioner.Conf{
  870. ID: id,
  871. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  872. Kind: provisioner.DOCR,
  873. Operation: opts.Operation,
  874. Redis: opts.RedisConf,
  875. Postgres: opts.PGConf,
  876. ProvisionerImageTag: opts.ProvImageTag,
  877. ImagePullSecret: opts.ProvImagePullSecret,
  878. LastApplied: opts.Infra.LastApplied,
  879. DO: &do.Conf{
  880. DOToken: tok,
  881. },
  882. DOCR: &docr.Conf{
  883. DOCRName: docrName,
  884. DOCRSubscriptionTier: docrSubscriptionTier,
  885. },
  886. }
  887. return a.provision(prov, opts.Infra, opts.Repo)
  888. }
  889. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  890. func (a *Agent) ProvisionDOKS(
  891. opts *SharedProvisionOpts,
  892. doConf *integrations.OAuthIntegration,
  893. doAuth *oauth2.Config,
  894. doRegion, doksClusterName string,
  895. ) (*batchv1.Job, error) {
  896. // get the token
  897. oauthInt, err := opts.Repo.OAuthIntegration().ReadOAuthIntegration(
  898. opts.ProjectID,
  899. opts.Infra.DOIntegrationID,
  900. )
  901. if err != nil {
  902. return nil, err
  903. }
  904. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, opts.Repo))
  905. if err != nil {
  906. return nil, err
  907. }
  908. id := opts.Infra.GetUniqueName()
  909. prov := &provisioner.Conf{
  910. ID: id,
  911. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  912. Kind: provisioner.DOKS,
  913. Operation: opts.Operation,
  914. Redis: opts.RedisConf,
  915. Postgres: opts.PGConf,
  916. LastApplied: opts.Infra.LastApplied,
  917. ProvisionerImageTag: opts.ProvImageTag,
  918. ImagePullSecret: opts.ProvImagePullSecret,
  919. DO: &do.Conf{
  920. DOToken: tok,
  921. },
  922. DOKS: &doks.Conf{
  923. DORegion: doRegion,
  924. DOKSClusterName: doksClusterName,
  925. },
  926. }
  927. return a.provision(prov, opts.Infra, opts.Repo)
  928. }
  929. // ProvisionTest spawns a new provisioning pod that tests provisioning
  930. func (a *Agent) ProvisionTest(
  931. opts *SharedProvisionOpts,
  932. ) (*batchv1.Job, error) {
  933. id := opts.Infra.GetUniqueName()
  934. prov := &provisioner.Conf{
  935. ID: id,
  936. Name: fmt.Sprintf("prov-%s-%s", id, string(opts.Operation)),
  937. Operation: opts.Operation,
  938. Kind: provisioner.Test,
  939. Redis: opts.RedisConf,
  940. Postgres: opts.PGConf,
  941. ProvisionerImageTag: opts.ProvImageTag,
  942. ImagePullSecret: opts.ProvImagePullSecret,
  943. }
  944. return a.provision(prov, opts.Infra, opts.Repo)
  945. }
  946. func (a *Agent) provision(
  947. prov *provisioner.Conf,
  948. infra *models.Infra,
  949. repo repository.Repository,
  950. ) (*batchv1.Job, error) {
  951. prov.Namespace = "default"
  952. job, err := prov.GetProvisionerJobTemplate()
  953. if err != nil {
  954. return nil, err
  955. }
  956. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  957. context.TODO(),
  958. job,
  959. metav1.CreateOptions{},
  960. )
  961. if err != nil {
  962. return nil, err
  963. }
  964. infra.LastApplied = prov.LastApplied
  965. infra, err = repo.Infra().UpdateInfra(infra)
  966. if err != nil {
  967. return nil, err
  968. }
  969. return job, nil
  970. }
  971. // CreateImagePullSecrets will create the required image pull secrets and
  972. // return a map from the registry name to the name of the secret.
  973. func (a *Agent) CreateImagePullSecrets(
  974. repo repository.Repository,
  975. namespace string,
  976. linkedRegs map[string]*models.Registry,
  977. doAuth *oauth2.Config,
  978. ) (map[string]string, error) {
  979. res := make(map[string]string)
  980. for key, val := range linkedRegs {
  981. _reg := registry.Registry(*val)
  982. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  983. if err != nil {
  984. return nil, err
  985. }
  986. secretName := fmt.Sprintf("porter-%s-%d", val.ToRegistryType().Service, val.ID)
  987. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  988. context.TODO(),
  989. secretName,
  990. metav1.GetOptions{},
  991. )
  992. // if not found, create the secret
  993. if err != nil && errors.IsNotFound(err) {
  994. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  995. context.TODO(),
  996. &v1.Secret{
  997. ObjectMeta: metav1.ObjectMeta{
  998. Name: secretName,
  999. },
  1000. Data: map[string][]byte{
  1001. string(v1.DockerConfigJsonKey): data,
  1002. },
  1003. Type: v1.SecretTypeDockerConfigJson,
  1004. },
  1005. metav1.CreateOptions{},
  1006. )
  1007. if err != nil {
  1008. return nil, err
  1009. }
  1010. // add secret name to the map
  1011. res[key] = secretName
  1012. continue
  1013. } else if err != nil {
  1014. return nil, err
  1015. }
  1016. // otherwise, check that the secret contains the correct data: if
  1017. // if doesn't, update it
  1018. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  1019. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  1020. context.TODO(),
  1021. &v1.Secret{
  1022. ObjectMeta: metav1.ObjectMeta{
  1023. Name: secretName,
  1024. },
  1025. Data: map[string][]byte{
  1026. string(v1.DockerConfigJsonKey): data,
  1027. },
  1028. Type: v1.SecretTypeDockerConfigJson,
  1029. },
  1030. metav1.UpdateOptions{},
  1031. )
  1032. if err != nil {
  1033. return nil, err
  1034. }
  1035. }
  1036. // add secret name to the map
  1037. res[key] = secretName
  1038. }
  1039. return res, nil
  1040. }