forked from micro/micro
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
executable file
·220 lines (191 loc) · 5.9 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Original source: github.com/micro/go-micro/v3/runtime/kubernetes/util.go
package kubernetes
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"github.com/2637309949/micro/v3/service/logger"
"github.com/2637309949/micro/v3/service/runtime"
"github.com/2637309949/micro/v3/service/runtime/kubernetes/api"
"github.com/2637309949/micro/v3/service/runtime/kubernetes/client"
)
// getServices queries kubernetes for services. It gets information from both the pods and the
// deployments
func (k *kubernetes) getServices(opts ...client.GetOption) ([]*runtime.Service, error) {
// get the deployments
depList := new(client.DeploymentList)
d := &client.Resource{
Kind: "deployment",
Value: depList,
}
if err := k.client.Get(d, opts...); err != nil {
return nil, err
}
srvMap := make(map[string]*runtime.Service, len(depList.Items))
// loop through the services and create a deployment for each
for _, kdep := range depList.Items {
srv := &runtime.Service{
Name: kdep.Metadata.Labels["name"],
Version: kdep.Metadata.Labels["version"],
Source: kdep.Metadata.Labels["source"],
Metadata: kdep.Metadata.Annotations,
}
// this metadata was injected by the k8s runtime
delete(srv.Metadata, "name")
delete(srv.Metadata, "version")
delete(srv.Metadata, "source")
// parse out deployment status and inject into service metadata
if len(kdep.Status.Conditions) > 0 {
srv.Status = transformStatus(kdep.Status.Conditions[0].Type)
srv.Metadata["started"] = kdep.Status.Conditions[0].LastUpdateTime
} else {
srv.Status = runtime.Unknown
}
srvMap[resourceName(srv)] = srv
}
// get the pods from k8s
podList := new(client.PodList)
p := &client.Resource{
Kind: "pod",
Value: podList,
}
if err := k.client.Get(p, opts...); err != nil {
logger.Errorf("Error fetching pods: %v", err)
return nil, nil
}
for _, item := range podList.Items {
// skip if we can't get the container
if len(item.Status.Containers) == 0 {
continue
}
// lookup the service in the map
key := resourceName(&runtime.Service{
Name: item.Metadata.Labels["name"],
Version: item.Metadata.Labels["version"],
})
srv, ok := srvMap[key]
if !ok {
continue
}
// use the pod status over the deployment status (contains more details)
srv.Status = transformStatus(item.Status.Phase)
// set start time
state := item.Status.Containers[0].State
if state.Running != nil {
srv.Metadata["started"] = state.Running.Started
}
// set status from waiting
if v := state.Waiting; v != nil {
srv.Status = runtime.Pending
}
}
// turn the map into an array
services := make([]*runtime.Service, 0, len(srvMap))
for _, srv := range srvMap {
services = append(services, srv)
}
return services, nil
}
func (k *kubernetes) createCredentials(service *runtime.Service, options *runtime.CreateOptions) error {
if len(options.Secrets) == 0 {
return nil
}
data := make(map[string]string, len(options.Secrets))
for key, value := range options.Secrets {
data[key] = base64.StdEncoding.EncodeToString([]byte(value))
}
// construct the k8s secret object
secret := &client.Secret{
Type: "Opaque",
Data: data,
Metadata: &client.Metadata{
Name: resourceName(service),
Namespace: options.Namespace,
},
}
// crete the secret in kubernetes
err := k.client.Create(&client.Resource{
Kind: "secret",
Name: resourceName(service),
Value: secret,
}, client.CreateNamespace(options.Namespace))
// ignore the error if the creds already exist
if err == nil || parseError(err).Reason == "AlreadyExists" {
return nil
}
if logger.V(logger.WarnLevel, logger.DefaultLogger) {
logger.Warnf("Error generating auth credentials for service: %v", err)
}
return err
}
func (k *kubernetes) deleteCredentials(service *runtime.Service, options *runtime.CreateOptions) error {
// construct the k8s secret object
secret := &client.Secret{
Type: "Opaque",
Metadata: &client.Metadata{
Name: resourceName(service),
Namespace: options.Namespace,
},
}
// crete the secret in kubernetes
err := k.client.Delete(&client.Resource{
Kind: "secret",
Name: resourceName(service),
Value: secret,
}, client.DeleteNamespace(options.Namespace))
if err != nil && logger.V(logger.WarnLevel, logger.DefaultLogger) {
logger.Warnf("Error deleting auth credentials for service: %v", err)
}
return err
}
func resourceName(srv *runtime.Service) string {
return fmt.Sprintf("%v-%v", client.Format(srv.Name), client.Format(srv.Version))
}
// transformStatus takes a deployment status (deploymentcondition.type) and transforms it into a
// runtime service status, e.g. containercreating => starting
func transformStatus(depStatus string) runtime.ServiceStatus {
switch strings.ToLower(depStatus) {
case "pending":
return runtime.Pending
case "containercreating":
return runtime.Starting
case "imagepullbackoff":
return runtime.Error
case "crashloopbackoff":
return runtime.Error
case "error":
return runtime.Error
case "running":
return runtime.Running
case "available":
return runtime.Running
case "succeeded":
return runtime.Stopped
case "failed":
return runtime.Error
case "waiting":
return runtime.Pending
case "terminated":
return runtime.Stopped
default:
return runtime.Unknown
}
}
func parseError(err error) *api.Status {
status := new(api.Status)
json.Unmarshal([]byte(err.Error()), &status)
return status
}