agent.go 29 KB

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