agent.go 29 KB

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