...
1 package kclient
2
3 import (
4 "context"
5 "fmt"
6
7 corev1 "k8s.io/api/core/v1"
8 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
9
10 odolabels "github.com/redhat-developer/odo/pkg/labels"
11 )
12
13
14
15 func (c *Client) CreateService(svc corev1.Service) (*corev1.Service, error) {
16 service, err := c.KubeClient.CoreV1().Services(c.Namespace).Create(context.TODO(), &svc, metav1.CreateOptions{FieldManager: FieldManager})
17 if err != nil {
18 return nil, fmt.Errorf("unable to create Service for %s: %w", svc.Name, err)
19 }
20 return service, err
21 }
22
23
24 func (c *Client) UpdateService(svc corev1.Service) (*corev1.Service, error) {
25 service, err := c.KubeClient.CoreV1().Services(c.Namespace).Update(context.TODO(), &svc, metav1.UpdateOptions{FieldManager: FieldManager})
26 if err != nil {
27 return nil, fmt.Errorf("unable to update Service for %s: %w", svc.Name, err)
28 }
29 return service, err
30 }
31
32
33
34 func (c *Client) ListServices(selector string) ([]corev1.Service, error) {
35 serviceList, err := c.KubeClient.CoreV1().Services(c.Namespace).List(context.TODO(), metav1.ListOptions{
36 LabelSelector: selector,
37 })
38 if err != nil {
39 return nil, fmt.Errorf("unable to list Services: %w", err)
40 }
41 return serviceList.Items, nil
42 }
43
44
45 func (c *Client) DeleteService(serviceName string) error {
46 err := c.KubeClient.CoreV1().Services(c.Namespace).Delete(context.TODO(), serviceName, metav1.DeleteOptions{})
47 if err != nil {
48 return err
49 }
50 return nil
51 }
52
53
54
55 func (c *Client) GetOneService(componentName, appName string, isPartOfComponent bool) (*corev1.Service, error) {
56 selector := odolabels.GetSelector(componentName, appName, odolabels.ComponentDevMode, isPartOfComponent)
57 return c.GetOneServiceFromSelector(selector)
58 }
59
60
61
62 func (c *Client) GetOneServiceFromSelector(selector string) (*corev1.Service, error) {
63 services, err := c.ListServices(selector)
64 if err != nil {
65 return nil, fmt.Errorf("unable to get services for the selector %q : %w", selector, err)
66 }
67
68 num := len(services)
69 if num == 0 {
70 return nil, &ServiceNotFoundError{Selector: selector}
71 } else if num > 1 {
72 return nil, fmt.Errorf("multiple services exist for the selector: %v. Only one must be present", selector)
73 }
74
75 return &services[0], nil
76 }
77
View as plain text