agent.go 29 KB

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