agent.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  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. }
  479. stopper := make(chan struct{})
  480. errorchan := make(chan error)
  481. defer close(stopper)
  482. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  483. UpdateFunc: func(oldObj, newObj interface{}) {
  484. msg := Message{
  485. EventType: "UPDATE",
  486. Object: newObj,
  487. Kind: strings.ToLower(kind),
  488. }
  489. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  490. errorchan <- writeErr
  491. return
  492. }
  493. },
  494. AddFunc: func(obj interface{}) {
  495. msg := Message{
  496. EventType: "ADD",
  497. Object: obj,
  498. Kind: strings.ToLower(kind),
  499. }
  500. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  501. errorchan <- writeErr
  502. return
  503. }
  504. },
  505. DeleteFunc: func(obj interface{}) {
  506. msg := Message{
  507. EventType: "DELETE",
  508. Object: obj,
  509. Kind: strings.ToLower(kind),
  510. }
  511. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  512. errorchan <- writeErr
  513. return
  514. }
  515. },
  516. })
  517. go func() {
  518. // listens for websocket closing handshake
  519. for {
  520. if _, _, err := conn.ReadMessage(); err != nil {
  521. conn.Close()
  522. errorchan <- nil
  523. return
  524. }
  525. }
  526. }()
  527. go informer.Run(stopper)
  528. for {
  529. select {
  530. case err := <-errorchan:
  531. return err
  532. }
  533. }
  534. }
  535. var b64 = base64.StdEncoding
  536. var magicGzip = []byte{0x1f, 0x8b, 0x08}
  537. func decodeRelease(data string) (*rspb.Release, error) {
  538. // base64 decode string
  539. b, err := b64.DecodeString(data)
  540. if err != nil {
  541. return nil, err
  542. }
  543. // For backwards compatibility with releases that were stored before
  544. // compression was introduced we skip decompression if the
  545. // gzip magic header is not found
  546. if bytes.Equal(b[0:3], magicGzip) {
  547. r, err := gzip.NewReader(bytes.NewReader(b))
  548. if err != nil {
  549. return nil, err
  550. }
  551. defer r.Close()
  552. b2, err := ioutil.ReadAll(r)
  553. if err != nil {
  554. return nil, err
  555. }
  556. b = b2
  557. }
  558. var rls rspb.Release
  559. // unmarshal release object bytes
  560. if err := json.Unmarshal(b, &rls); err != nil {
  561. return nil, err
  562. }
  563. return &rls, nil
  564. }
  565. func contains(s []string, str string) bool {
  566. for _, v := range s {
  567. if v == str {
  568. return true
  569. }
  570. }
  571. return false
  572. }
  573. func parseSecretToHelmRelease(secret v1.Secret, chartList []string) (*rspb.Release, bool, error) {
  574. if secret.Type != "helm.sh/release.v1" {
  575. return nil, true, nil
  576. }
  577. releaseData, ok := secret.Data["release"]
  578. if !ok {
  579. return nil, true, fmt.Errorf("release field not found")
  580. }
  581. helm_object, err := decodeRelease(string(releaseData))
  582. if err != nil {
  583. return nil, true, err
  584. }
  585. if len(chartList) > 0 && !contains(chartList, helm_object.Name) {
  586. return nil, true, nil
  587. }
  588. return helm_object, false, nil
  589. }
  590. func (a *Agent) StreamHelmReleases(conn *websocket.Conn, chartList []string, selectors string) error {
  591. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  592. options.LabelSelector = selectors
  593. }
  594. factory := informers.NewSharedInformerFactoryWithOptions(
  595. a.Clientset,
  596. 0,
  597. informers.WithTweakListOptions(tweakListOptionsFunc),
  598. )
  599. informer := factory.Core().V1().Secrets().Informer()
  600. stopper := make(chan struct{})
  601. errorchan := make(chan error)
  602. defer close(stopper)
  603. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  604. UpdateFunc: func(oldObj, newObj interface{}) {
  605. secretObj, ok := newObj.(*v1.Secret)
  606. if !ok {
  607. errorchan <- fmt.Errorf("could not cast to secret")
  608. return
  609. }
  610. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  611. if isNotHelmRelease && err == nil {
  612. return
  613. }
  614. if err != nil {
  615. errorchan <- err
  616. return
  617. }
  618. msg := Message{
  619. EventType: "UPDATE",
  620. Object: helm_object,
  621. }
  622. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  623. errorchan <- writeErr
  624. return
  625. }
  626. },
  627. AddFunc: func(obj interface{}) {
  628. secretObj, ok := obj.(*v1.Secret)
  629. if !ok {
  630. errorchan <- fmt.Errorf("could not cast to secret")
  631. return
  632. }
  633. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  634. if isNotHelmRelease && err == nil {
  635. return
  636. }
  637. if err != nil {
  638. errorchan <- err
  639. return
  640. }
  641. msg := Message{
  642. EventType: "ADD",
  643. Object: helm_object,
  644. }
  645. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  646. errorchan <- writeErr
  647. return
  648. }
  649. },
  650. DeleteFunc: func(obj interface{}) {
  651. secretObj, ok := obj.(*v1.Secret)
  652. if !ok {
  653. errorchan <- fmt.Errorf("could not cast to secret")
  654. return
  655. }
  656. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  657. if isNotHelmRelease && err == nil {
  658. return
  659. }
  660. if err != nil {
  661. errorchan <- err
  662. return
  663. }
  664. msg := Message{
  665. EventType: "DELETE",
  666. Object: helm_object,
  667. }
  668. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  669. errorchan <- writeErr
  670. return
  671. }
  672. },
  673. })
  674. go func() {
  675. // listens for websocket closing handshake
  676. for {
  677. if _, _, err := conn.ReadMessage(); err != nil {
  678. conn.Close()
  679. errorchan <- nil
  680. return
  681. }
  682. }
  683. }()
  684. go informer.Run(stopper)
  685. for {
  686. select {
  687. case err := <-errorchan:
  688. return err
  689. }
  690. }
  691. }
  692. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  693. func (a *Agent) ProvisionECR(
  694. projectID uint,
  695. awsConf *integrations.AWSIntegration,
  696. ecrName string,
  697. repo repository.Repository,
  698. infra *models.Infra,
  699. operation provisioner.ProvisionerOperation,
  700. pgConf *config.DBConf,
  701. redisConf *config.RedisConf,
  702. provImageTag string,
  703. ) (*batchv1.Job, error) {
  704. id := infra.GetUniqueName()
  705. prov := &provisioner.Conf{
  706. ID: id,
  707. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  708. Kind: provisioner.ECR,
  709. Operation: operation,
  710. Redis: redisConf,
  711. Postgres: pgConf,
  712. ProvisionerImageTag: provImageTag,
  713. LastApplied: infra.LastApplied,
  714. AWS: &aws.Conf{
  715. AWSRegion: awsConf.AWSRegion,
  716. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  717. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  718. },
  719. ECR: &ecr.Conf{
  720. ECRName: ecrName,
  721. },
  722. }
  723. return a.provision(prov, infra, repo)
  724. }
  725. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  726. func (a *Agent) ProvisionEKS(
  727. projectID uint,
  728. awsConf *integrations.AWSIntegration,
  729. eksName, machineType string,
  730. repo repository.Repository,
  731. infra *models.Infra,
  732. operation provisioner.ProvisionerOperation,
  733. pgConf *config.DBConf,
  734. redisConf *config.RedisConf,
  735. provImageTag string,
  736. ) (*batchv1.Job, error) {
  737. id := infra.GetUniqueName()
  738. prov := &provisioner.Conf{
  739. ID: id,
  740. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  741. Kind: provisioner.EKS,
  742. Operation: operation,
  743. Redis: redisConf,
  744. Postgres: pgConf,
  745. ProvisionerImageTag: provImageTag,
  746. LastApplied: infra.LastApplied,
  747. AWS: &aws.Conf{
  748. AWSRegion: awsConf.AWSRegion,
  749. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  750. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  751. },
  752. EKS: &eks.Conf{
  753. ClusterName: eksName,
  754. MachineType: machineType,
  755. },
  756. }
  757. return a.provision(prov, infra, repo)
  758. }
  759. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  760. func (a *Agent) ProvisionGCR(
  761. projectID uint,
  762. gcpConf *integrations.GCPIntegration,
  763. repo repository.Repository,
  764. infra *models.Infra,
  765. operation provisioner.ProvisionerOperation,
  766. pgConf *config.DBConf,
  767. redisConf *config.RedisConf,
  768. provImageTag string,
  769. ) (*batchv1.Job, error) {
  770. id := infra.GetUniqueName()
  771. prov := &provisioner.Conf{
  772. ID: id,
  773. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  774. Kind: provisioner.GCR,
  775. Operation: operation,
  776. Redis: redisConf,
  777. Postgres: pgConf,
  778. ProvisionerImageTag: provImageTag,
  779. LastApplied: infra.LastApplied,
  780. GCP: &gcp.Conf{
  781. GCPRegion: gcpConf.GCPRegion,
  782. GCPProjectID: gcpConf.GCPProjectID,
  783. GCPKeyData: string(gcpConf.GCPKeyData),
  784. },
  785. }
  786. return a.provision(prov, infra, repo)
  787. }
  788. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  789. func (a *Agent) ProvisionGKE(
  790. projectID uint,
  791. gcpConf *integrations.GCPIntegration,
  792. gkeName string,
  793. repo repository.Repository,
  794. infra *models.Infra,
  795. operation provisioner.ProvisionerOperation,
  796. pgConf *config.DBConf,
  797. redisConf *config.RedisConf,
  798. provImageTag string,
  799. ) (*batchv1.Job, error) {
  800. id := infra.GetUniqueName()
  801. prov := &provisioner.Conf{
  802. ID: id,
  803. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  804. Kind: provisioner.GKE,
  805. Operation: operation,
  806. Redis: redisConf,
  807. Postgres: pgConf,
  808. ProvisionerImageTag: provImageTag,
  809. LastApplied: infra.LastApplied,
  810. GCP: &gcp.Conf{
  811. GCPRegion: gcpConf.GCPRegion,
  812. GCPProjectID: gcpConf.GCPProjectID,
  813. GCPKeyData: string(gcpConf.GCPKeyData),
  814. },
  815. GKE: &gke.Conf{
  816. ClusterName: gkeName,
  817. },
  818. }
  819. return a.provision(prov, infra, repo)
  820. }
  821. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  822. func (a *Agent) ProvisionDOCR(
  823. projectID uint,
  824. doConf *integrations.OAuthIntegration,
  825. doAuth *oauth2.Config,
  826. repo repository.Repository,
  827. docrName, docrSubscriptionTier string,
  828. infra *models.Infra,
  829. operation provisioner.ProvisionerOperation,
  830. pgConf *config.DBConf,
  831. redisConf *config.RedisConf,
  832. provImageTag string,
  833. ) (*batchv1.Job, error) {
  834. // get the token
  835. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  836. infra.DOIntegrationID,
  837. )
  838. if err != nil {
  839. return nil, err
  840. }
  841. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  842. if err != nil {
  843. return nil, err
  844. }
  845. id := infra.GetUniqueName()
  846. prov := &provisioner.Conf{
  847. ID: id,
  848. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  849. Kind: provisioner.DOCR,
  850. Operation: operation,
  851. Redis: redisConf,
  852. Postgres: pgConf,
  853. ProvisionerImageTag: provImageTag,
  854. LastApplied: infra.LastApplied,
  855. DO: &do.Conf{
  856. DOToken: tok,
  857. },
  858. DOCR: &docr.Conf{
  859. DOCRName: docrName,
  860. DOCRSubscriptionTier: docrSubscriptionTier,
  861. },
  862. }
  863. return a.provision(prov, infra, repo)
  864. }
  865. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  866. func (a *Agent) ProvisionDOKS(
  867. projectID uint,
  868. doConf *integrations.OAuthIntegration,
  869. doAuth *oauth2.Config,
  870. repo repository.Repository,
  871. doRegion, doksClusterName string,
  872. infra *models.Infra,
  873. operation provisioner.ProvisionerOperation,
  874. pgConf *config.DBConf,
  875. redisConf *config.RedisConf,
  876. provImageTag string,
  877. ) (*batchv1.Job, error) {
  878. // get the token
  879. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  880. infra.DOIntegrationID,
  881. )
  882. if err != nil {
  883. return nil, err
  884. }
  885. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  886. if err != nil {
  887. return nil, err
  888. }
  889. id := infra.GetUniqueName()
  890. prov := &provisioner.Conf{
  891. ID: id,
  892. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  893. Kind: provisioner.DOKS,
  894. Operation: operation,
  895. Redis: redisConf,
  896. Postgres: pgConf,
  897. LastApplied: infra.LastApplied,
  898. ProvisionerImageTag: provImageTag,
  899. DO: &do.Conf{
  900. DOToken: tok,
  901. },
  902. DOKS: &doks.Conf{
  903. DORegion: doRegion,
  904. DOKSClusterName: doksClusterName,
  905. },
  906. }
  907. return a.provision(prov, infra, repo)
  908. }
  909. // ProvisionTest spawns a new provisioning pod that tests provisioning
  910. func (a *Agent) ProvisionTest(
  911. projectID uint,
  912. infra *models.Infra,
  913. repo repository.Repository,
  914. operation provisioner.ProvisionerOperation,
  915. pgConf *config.DBConf,
  916. redisConf *config.RedisConf,
  917. provImageTag string,
  918. ) (*batchv1.Job, error) {
  919. id := infra.GetUniqueName()
  920. prov := &provisioner.Conf{
  921. ID: id,
  922. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  923. Operation: operation,
  924. Kind: provisioner.Test,
  925. Redis: redisConf,
  926. Postgres: pgConf,
  927. ProvisionerImageTag: provImageTag,
  928. }
  929. return a.provision(prov, infra, repo)
  930. }
  931. func (a *Agent) provision(
  932. prov *provisioner.Conf,
  933. infra *models.Infra,
  934. repo repository.Repository,
  935. ) (*batchv1.Job, error) {
  936. prov.Namespace = "default"
  937. job, err := prov.GetProvisionerJobTemplate()
  938. if err != nil {
  939. return nil, err
  940. }
  941. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  942. context.TODO(),
  943. job,
  944. metav1.CreateOptions{},
  945. )
  946. if err != nil {
  947. return nil, err
  948. }
  949. infra.LastApplied = prov.LastApplied
  950. infra, err = repo.Infra.UpdateInfra(infra)
  951. if err != nil {
  952. return nil, err
  953. }
  954. return job, nil
  955. }
  956. // CreateImagePullSecrets will create the required image pull secrets and
  957. // return a map from the registry name to the name of the secret.
  958. func (a *Agent) CreateImagePullSecrets(
  959. repo repository.Repository,
  960. namespace string,
  961. linkedRegs map[string]*models.Registry,
  962. doAuth *oauth2.Config,
  963. ) (map[string]string, error) {
  964. res := make(map[string]string)
  965. for key, val := range linkedRegs {
  966. _reg := registry.Registry(*val)
  967. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  968. if err != nil {
  969. return nil, err
  970. }
  971. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  972. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  973. context.TODO(),
  974. secretName,
  975. metav1.GetOptions{},
  976. )
  977. // if not found, create the secret
  978. if err != nil && errors.IsNotFound(err) {
  979. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  980. context.TODO(),
  981. &v1.Secret{
  982. ObjectMeta: metav1.ObjectMeta{
  983. Name: secretName,
  984. },
  985. Data: map[string][]byte{
  986. string(v1.DockerConfigJsonKey): data,
  987. },
  988. Type: v1.SecretTypeDockerConfigJson,
  989. },
  990. metav1.CreateOptions{},
  991. )
  992. if err != nil {
  993. return nil, err
  994. }
  995. // add secret name to the map
  996. res[key] = secretName
  997. continue
  998. } else if err != nil {
  999. return nil, err
  1000. }
  1001. // otherwise, check that the secret contains the correct data: if
  1002. // if doesn't, update it
  1003. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  1004. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  1005. context.TODO(),
  1006. &v1.Secret{
  1007. ObjectMeta: metav1.ObjectMeta{
  1008. Name: secretName,
  1009. },
  1010. Data: map[string][]byte{
  1011. string(v1.DockerConfigJsonKey): data,
  1012. },
  1013. Type: v1.SecretTypeDockerConfigJson,
  1014. },
  1015. metav1.UpdateOptions{},
  1016. )
  1017. if err != nil {
  1018. return nil, err
  1019. }
  1020. }
  1021. // add secret name to the map
  1022. res[key] = secretName
  1023. }
  1024. return res, nil
  1025. }