agent.go 26 KB

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