agent.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. provImagePullSecret string,
  704. ) (*batchv1.Job, error) {
  705. id := infra.GetUniqueName()
  706. prov := &provisioner.Conf{
  707. ID: id,
  708. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  709. Kind: provisioner.ECR,
  710. Operation: operation,
  711. Redis: redisConf,
  712. Postgres: pgConf,
  713. ProvisionerImageTag: provImageTag,
  714. ImagePullSecret: provImagePullSecret,
  715. LastApplied: infra.LastApplied,
  716. AWS: &aws.Conf{
  717. AWSRegion: awsConf.AWSRegion,
  718. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  719. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  720. },
  721. ECR: &ecr.Conf{
  722. ECRName: ecrName,
  723. },
  724. }
  725. return a.provision(prov, infra, repo)
  726. }
  727. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  728. func (a *Agent) ProvisionEKS(
  729. projectID uint,
  730. awsConf *integrations.AWSIntegration,
  731. eksName, machineType string,
  732. repo repository.Repository,
  733. infra *models.Infra,
  734. operation provisioner.ProvisionerOperation,
  735. pgConf *config.DBConf,
  736. redisConf *config.RedisConf,
  737. provImageTag string,
  738. provImagePullSecret string,
  739. ) (*batchv1.Job, error) {
  740. id := infra.GetUniqueName()
  741. prov := &provisioner.Conf{
  742. ID: id,
  743. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  744. Kind: provisioner.EKS,
  745. Operation: operation,
  746. Redis: redisConf,
  747. Postgres: pgConf,
  748. ProvisionerImageTag: provImageTag,
  749. ImagePullSecret: provImagePullSecret,
  750. LastApplied: infra.LastApplied,
  751. AWS: &aws.Conf{
  752. AWSRegion: awsConf.AWSRegion,
  753. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  754. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  755. },
  756. EKS: &eks.Conf{
  757. ClusterName: eksName,
  758. MachineType: machineType,
  759. },
  760. }
  761. return a.provision(prov, infra, repo)
  762. }
  763. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  764. func (a *Agent) ProvisionGCR(
  765. projectID uint,
  766. gcpConf *integrations.GCPIntegration,
  767. repo repository.Repository,
  768. infra *models.Infra,
  769. operation provisioner.ProvisionerOperation,
  770. pgConf *config.DBConf,
  771. redisConf *config.RedisConf,
  772. provImageTag string,
  773. provImagePullSecret string,
  774. ) (*batchv1.Job, error) {
  775. id := infra.GetUniqueName()
  776. prov := &provisioner.Conf{
  777. ID: id,
  778. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  779. Kind: provisioner.GCR,
  780. Operation: operation,
  781. Redis: redisConf,
  782. Postgres: pgConf,
  783. ProvisionerImageTag: provImageTag,
  784. ImagePullSecret: provImagePullSecret,
  785. LastApplied: infra.LastApplied,
  786. GCP: &gcp.Conf{
  787. GCPRegion: gcpConf.GCPRegion,
  788. GCPProjectID: gcpConf.GCPProjectID,
  789. GCPKeyData: string(gcpConf.GCPKeyData),
  790. },
  791. }
  792. return a.provision(prov, infra, repo)
  793. }
  794. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  795. func (a *Agent) ProvisionGKE(
  796. projectID uint,
  797. gcpConf *integrations.GCPIntegration,
  798. gkeName string,
  799. repo repository.Repository,
  800. infra *models.Infra,
  801. operation provisioner.ProvisionerOperation,
  802. pgConf *config.DBConf,
  803. redisConf *config.RedisConf,
  804. provImageTag string,
  805. provImagePullSecret string,
  806. ) (*batchv1.Job, error) {
  807. id := infra.GetUniqueName()
  808. prov := &provisioner.Conf{
  809. ID: id,
  810. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  811. Kind: provisioner.GKE,
  812. Operation: operation,
  813. Redis: redisConf,
  814. Postgres: pgConf,
  815. ProvisionerImageTag: provImageTag,
  816. ImagePullSecret: provImagePullSecret,
  817. LastApplied: infra.LastApplied,
  818. GCP: &gcp.Conf{
  819. GCPRegion: gcpConf.GCPRegion,
  820. GCPProjectID: gcpConf.GCPProjectID,
  821. GCPKeyData: string(gcpConf.GCPKeyData),
  822. },
  823. GKE: &gke.Conf{
  824. ClusterName: gkeName,
  825. },
  826. }
  827. return a.provision(prov, infra, repo)
  828. }
  829. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  830. func (a *Agent) ProvisionDOCR(
  831. projectID uint,
  832. doConf *integrations.OAuthIntegration,
  833. doAuth *oauth2.Config,
  834. repo repository.Repository,
  835. docrName, docrSubscriptionTier string,
  836. infra *models.Infra,
  837. operation provisioner.ProvisionerOperation,
  838. pgConf *config.DBConf,
  839. redisConf *config.RedisConf,
  840. provImageTag string,
  841. provImagePullSecret string,
  842. ) (*batchv1.Job, error) {
  843. // get the token
  844. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  845. infra.DOIntegrationID,
  846. )
  847. if err != nil {
  848. return nil, err
  849. }
  850. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  851. if err != nil {
  852. return nil, err
  853. }
  854. id := infra.GetUniqueName()
  855. prov := &provisioner.Conf{
  856. ID: id,
  857. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  858. Kind: provisioner.DOCR,
  859. Operation: operation,
  860. Redis: redisConf,
  861. Postgres: pgConf,
  862. ProvisionerImageTag: provImageTag,
  863. ImagePullSecret: provImagePullSecret,
  864. LastApplied: infra.LastApplied,
  865. DO: &do.Conf{
  866. DOToken: tok,
  867. },
  868. DOCR: &docr.Conf{
  869. DOCRName: docrName,
  870. DOCRSubscriptionTier: docrSubscriptionTier,
  871. },
  872. }
  873. return a.provision(prov, infra, repo)
  874. }
  875. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  876. func (a *Agent) ProvisionDOKS(
  877. projectID uint,
  878. doConf *integrations.OAuthIntegration,
  879. doAuth *oauth2.Config,
  880. repo repository.Repository,
  881. doRegion, doksClusterName string,
  882. infra *models.Infra,
  883. operation provisioner.ProvisionerOperation,
  884. pgConf *config.DBConf,
  885. redisConf *config.RedisConf,
  886. provImageTag string,
  887. provImagePullSecret string,
  888. ) (*batchv1.Job, error) {
  889. // get the token
  890. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  891. infra.DOIntegrationID,
  892. )
  893. if err != nil {
  894. return nil, err
  895. }
  896. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  897. if err != nil {
  898. return nil, err
  899. }
  900. id := infra.GetUniqueName()
  901. prov := &provisioner.Conf{
  902. ID: id,
  903. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  904. Kind: provisioner.DOKS,
  905. Operation: operation,
  906. Redis: redisConf,
  907. Postgres: pgConf,
  908. LastApplied: infra.LastApplied,
  909. ProvisionerImageTag: provImageTag,
  910. ImagePullSecret: provImagePullSecret,
  911. DO: &do.Conf{
  912. DOToken: tok,
  913. },
  914. DOKS: &doks.Conf{
  915. DORegion: doRegion,
  916. DOKSClusterName: doksClusterName,
  917. },
  918. }
  919. return a.provision(prov, infra, repo)
  920. }
  921. // ProvisionTest spawns a new provisioning pod that tests provisioning
  922. func (a *Agent) ProvisionTest(
  923. projectID uint,
  924. infra *models.Infra,
  925. repo repository.Repository,
  926. operation provisioner.ProvisionerOperation,
  927. pgConf *config.DBConf,
  928. redisConf *config.RedisConf,
  929. provImageTag string,
  930. provImagePullSecret string,
  931. ) (*batchv1.Job, error) {
  932. id := infra.GetUniqueName()
  933. prov := &provisioner.Conf{
  934. ID: id,
  935. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  936. Operation: operation,
  937. Kind: provisioner.Test,
  938. Redis: redisConf,
  939. Postgres: pgConf,
  940. ProvisionerImageTag: provImageTag,
  941. ImagePullSecret: provImagePullSecret,
  942. }
  943. return a.provision(prov, infra, 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. }