forked from fabric8io/kubernetes-client
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ServiceOperationsImpl.java
180 lines (151 loc) · 6.75 KB
/
ServiceOperationsImpl.java
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
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* 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
*
* http://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.
*/
package io.fabric8.kubernetes.client.dsl.internal.core.v1;
import io.fabric8.kubernetes.api.model.DoneableService;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.fabric8.kubernetes.api.model.ServiceList;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.*;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.dsl.ServiceResource;
import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation;
import io.fabric8.kubernetes.client.dsl.base.OperationContext;
import io.fabric8.kubernetes.client.utils.URLUtils;
import okhttp3.OkHttpClient;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class ServiceOperationsImpl extends HasMetadataOperation<Service, ServiceList, DoneableService, ServiceResource<Service, DoneableService>> implements ServiceResource<Service, DoneableService> {
public static final String EXTERNAL_NAME = "ExternalName";
public ServiceOperationsImpl(OkHttpClient client, Config config) {
this(client, config, null);
}
public ServiceOperationsImpl(OkHttpClient client, Config config, String namespace) {
this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(DEFAULT_PROPAGATION_POLICY));
}
public ServiceOperationsImpl(OperationContext context) {
super(context.withPlural("services"));
this.type = Service.class;
this.listType = ServiceList.class;
this.doneableType = DoneableService.class;
}
@Override
public ServiceOperationsImpl newInstance(OperationContext context) {
return new ServiceOperationsImpl(context);
}
@Override
public Service replace(Service item) {
return super.replace(patchClusterIpIntoServiceAndReplace(item));
}
@Override
public Service patch(Service item) {
try {
Service old = getMandatory();
return super.patch(new ServiceBuilder(item)
.editSpec()
.withClusterIP(old.getSpec().getClusterIP())
.endSpec()
.build());
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(forOperationType("patch"), e);
}
}
@Override
public Service waitUntilReady(long amount, TimeUnit timeUnit) throws InterruptedException {
long started = System.nanoTime();
super.waitUntilReady(amount, timeUnit);
long alreadySpent = System.nanoTime() - started;
// if awaiting existence took very long, let's give at least 10 seconds to awaiting readiness
long remaining = Math.max(10_000, timeUnit.toNanos(amount) - alreadySpent);
EndpointsOperationsImpl endpointsOperation = new EndpointsOperationsImpl(context);
endpointsOperation.waitUntilReady(remaining, TimeUnit.MILLISECONDS);
return get();
}
public String getURL(String portName) {
String clusterIP = getMandatory().getSpec().getClusterIP();
if("None".equals(clusterIP)) {
throw new IllegalStateException("Service: " + getMandatory().getMetadata().getName() + " in namespace " +
namespace + " is head-less. Search for endpoints instead");
}
return getUrlHelper(portName);
}
private String getUrlHelper(String portName) {
ServiceLoader<ServiceToURLProvider> urlProvider = ServiceLoader.load(ServiceToURLProvider.class, Thread.currentThread().getContextClassLoader());
Iterator<ServiceToURLProvider> iterator = urlProvider.iterator();
List<ServiceToURLProvider> servicesList = new ArrayList<>();
while(iterator.hasNext()) {
servicesList.add(iterator.next());
}
// Sort all loaded implementations according to priority
Collections.sort(servicesList, new ServiceToUrlSortComparator());
for(ServiceToURLProvider serviceToURLProvider : servicesList) {
String url = serviceToURLProvider.getURL(getMandatory(), portName, namespace, new DefaultKubernetesClient(client, getConfig()));
if(url != null && URLUtils.isValidURL(url)) {
return url;
}
}
return null;
}
private Pod matchingPod() {
Service item = fromServer().get();
Map<String, String> labels = item.getSpec().getSelector();
PodList list = new PodOperationsImpl(client, config).inNamespace(item.getMetadata().getNamespace()).withLabels(labels).list();
return list.getItems().stream().findFirst().orElseThrow(() -> new IllegalStateException("Could not find matching pod for service:" + item + "."));
}
@Override
public PortForward portForward(int port, ReadableByteChannel in, WritableByteChannel out) {
Pod m = matchingPod();
return new PodOperationsImpl(client, config).inNamespace(m.getMetadata().getNamespace()).withName(m.getMetadata().getName()).portForward(port, in, out);
}
@Override
public LocalPortForward portForward(int port, int localPort) {
Pod m = matchingPod();
return new PodOperationsImpl(client, config).inNamespace(m.getMetadata().getNamespace()).withName(m.getMetadata().getName()).portForward(port, localPort);
}
@Override
public LocalPortForward portForward(int port) {
Pod m = matchingPod();
return new PodOperationsImpl(client, config).inNamespace(m.getMetadata().getNamespace()).withName(m.getMetadata().getName()).portForward(port);
}
public class ServiceToUrlSortComparator implements Comparator<ServiceToURLProvider> {
public int compare(ServiceToURLProvider first, ServiceToURLProvider second) {
return first.getPriority() - second.getPriority();
}
}
private Service patchClusterIpIntoServiceAndReplace(Service item) {
if (!isExternalNameService(item)) {
try {
Service old = fromServer().get();
return new ServiceBuilder(item)
.editSpec()
.withClusterIP(old.getSpec().getClusterIP())
.endSpec()
.build();
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(forOperationType("replace"), e);
}
}
return item;
}
private boolean isExternalNameService(Service item) {
if (item != null && item.getSpec() != null && item.getSpec().getType() != null) {
return item.getSpec().getType().equals(EXTERNAL_NAME);
}
return false;
}
}