Skip to content

Commit 16ad33e

Browse files
committed
add example
1 parent a1b1e80 commit 16ad33e

File tree

2 files changed

+392
-0
lines changed

2 files changed

+392
-0
lines changed

examples/loadbalancer/build.gradle

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
dependencies {
2+
implementation project (':services:loadbalancer')
3+
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
4+
}
5+
6+
ext.mainClassName = 'cloud.stackit.sdk.loadbalancer.examples.LoadBalancerExample'
Lines changed: 386 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,386 @@
1+
package cloud.stackit.sdk.loadbalancer.examples;
2+
3+
import cloud.stackit.sdk.core.exception.ApiException;
4+
import cloud.stackit.sdk.loadbalancer.api.LoadBalancerApi;
5+
import cloud.stackit.sdk.loadbalancer.model.*;
6+
import java.io.IOException;
7+
import java.net.HttpURLConnection;
8+
import java.util.*;
9+
import java.util.concurrent.TimeUnit;
10+
11+
// This examples prerequisite an existing STACKIT network, public ip
12+
// and a server with a network interface
13+
final class LoadBalancerExample {
14+
15+
private LoadBalancerExample() {}
16+
17+
@SuppressWarnings({
18+
"PMD.CognitiveComplexity",
19+
"PMD.CommentSize",
20+
"PMD.CyclomaticComplexity",
21+
"PMD.NPathComplexity",
22+
"PMD.NcssCount",
23+
"PMD.SystemPrintln",
24+
"PMD.AvoidThrowingRawExceptionTypes"
25+
})
26+
public static void main(String[] args) throws IOException {
27+
// Credentials are read from the credentialsFile in `~/.stackit/credentials.json` or the env
28+
// STACKIT_SERVICE_ACCOUNT_KEY_PATH / STACKIT_SERVICE_ACCOUNT_KEY
29+
LoadBalancerApi loadBalancerApi = new LoadBalancerApi();
30+
31+
// the id of your STACKIT project, read from env var for this example
32+
String projectId = System.getenv("STACKIT_PROJECT_ID");
33+
if (projectId == null || projectId.isEmpty()) {
34+
System.err.println("Environment variable 'STACKIT_PROJECT_ID' not found.");
35+
return;
36+
}
37+
38+
@SuppressWarnings("PMD.PrematureDeclaration")
39+
// the region which should be used to interact with load balancer
40+
String region = "eu01";
41+
42+
// the network id where the listeners and targets reside in
43+
String networkIdString = System.getenv("STACKIT_NETWORK_ID");
44+
if (networkIdString == null || networkIdString.isEmpty()) {
45+
System.err.println("Environment variable 'STACKIT_NETWORK_ID' not found.");
46+
return;
47+
}
48+
UUID networkId = UUID.fromString(networkIdString);
49+
50+
// the external load balancer ip address which should be exposed
51+
String externalAddress = System.getenv("STACKIT_EXTERNAL_ADDRESS");
52+
if (externalAddress == null || externalAddress.isEmpty()) {
53+
System.err.println("Environment variable 'STACKIT_EXTERNAL_ADDRESS' not found.");
54+
return;
55+
}
56+
57+
// the listener network interface ipv4 address which will listen to the incoming requests
58+
String nicIpv4 = System.getenv("STACKIT_LISTENER_NETWORK_INTERFACE_IPV4");
59+
if (nicIpv4 == null || nicIpv4.isEmpty()) {
60+
System.err.println(
61+
"Environment variable 'STACKIT_LISTENER_NETWORK_INTERFACE_IPV4' not found.");
62+
return;
63+
}
64+
65+
try {
66+
/*
67+
* ///////////////////////////////////////////////////////
68+
* // S E R V I C E P L A N S //
69+
* ///////////////////////////////////////////////////////
70+
*/
71+
/* list all available service plans */
72+
ListPlansResponse listPlans = loadBalancerApi.listPlans(region);
73+
System.out.println("Listing service plans:");
74+
assert listPlans.getValidPlans() != null;
75+
for (PlanDetails plan : listPlans.getValidPlans()) {
76+
System.out.println("********************");
77+
System.out.println("* Plan name: " + plan.getName());
78+
System.out.println("* Plan ID: " + plan.getPlanId());
79+
System.out.println("* Flavor name: " + plan.getFlavorName());
80+
System.out.println("* Max connections: " + plan.getMaxConnections());
81+
}
82+
83+
/*
84+
* ///////////////////////////////////////////////////////
85+
* // L O A D B A L A N C E R Q U O T A //
86+
* ///////////////////////////////////////////////////////
87+
*/
88+
/* get quota of load balancers in this project */
89+
System.out.println("\nFetching load balancer quota of this project:");
90+
GetQuotaResponse getQuota = loadBalancerApi.getQuota(projectId, region);
91+
System.out.println("* Max load balancer: " + getQuota.getMaxLoadBalancers());
92+
93+
/*
94+
* ///////////////////////////////////////////////////////
95+
* // C R E D E N T I A L S //
96+
* ///////////////////////////////////////////////////////
97+
*/
98+
/* add observability credentials */
99+
System.out.println("\nAdding observability credentials to load balancer service:");
100+
CreateCredentialsResponse newCredentials =
101+
loadBalancerApi.createCredentials(
102+
projectId,
103+
region,
104+
new CreateCredentialsPayload()
105+
.displayName("example-credentials")
106+
.username("valid-username-for-observability-instance")
107+
.password("valid-password-for-observability-instance"),
108+
null);
109+
assert newCredentials.getCredential() != null;
110+
System.out.println(
111+
"* Display name: " + newCredentials.getCredential().getDisplayName());
112+
System.out.println("* Ref: " + newCredentials.getCredential().getCredentialsRef());
113+
System.out.println("* Username: " + newCredentials.getCredential().getUsername());
114+
115+
/* update the created observability credentials*/
116+
System.out.println("\nUpdating the created credentials:");
117+
assert newCredentials.getCredential().getCredentialsRef() != null;
118+
UpdateCredentialsResponse updateCredentials =
119+
loadBalancerApi.updateCredentials(
120+
projectId,
121+
region,
122+
newCredentials.getCredential().getCredentialsRef(),
123+
new UpdateCredentialsPayload()
124+
.displayName("example-credentials-update")
125+
.username("valid-username-for-observability-instance-update")
126+
.password("valid-password-for-observability-instance-update"));
127+
assert updateCredentials.getCredential() != null;
128+
System.out.println(
129+
"* Display name: " + updateCredentials.getCredential().getDisplayName());
130+
System.out.println("* Ref: " + updateCredentials.getCredential().getCredentialsRef());
131+
System.out.println("* Username: " + updateCredentials.getCredential().getUsername());
132+
133+
/* list all credentials in the project */
134+
System.out.println("\nList all credentials:");
135+
ListCredentialsResponse listCredentials =
136+
loadBalancerApi.listCredentials(projectId, region);
137+
assert listCredentials.getCredentials() != null;
138+
for (CredentialsResponse credential : listCredentials.getCredentials()) {
139+
System.out.println("*************************");
140+
System.out.println("* Display name: " + credential.getDisplayName());
141+
System.out.println("* Ref: " + credential.getCredentialsRef());
142+
System.out.println("* Username: " + credential.getUsername());
143+
}
144+
/*
145+
* ///////////////////////////////////////////////////////
146+
* // L O A D B A L A N C E R //
147+
* ///////////////////////////////////////////////////////
148+
*/
149+
150+
/*
151+
* create a new load balancer
152+
*
153+
* NOTE: see the docs for available service plans
154+
* https://docs.stackit.cloud/products/network/load-balancing-and-content-delivery/load-balancer/nlb-basics/basic-concepts/#service-plans
155+
*
156+
* */
157+
System.out.println("\nTrigger creation of load balancer");
158+
LoadBalancer newLoadbalancer =
159+
loadBalancerApi.createLoadBalancer(
160+
projectId,
161+
region,
162+
new CreateLoadBalancerPayload()
163+
.name("java-sdk-example")
164+
.planId("p10")
165+
.addNetworksItem(
166+
new Network()
167+
.networkId(networkId)
168+
.role(
169+
Network.RoleEnum
170+
.ROLE_LISTENERS_AND_TARGETS))
171+
.targetPools(
172+
Collections.singletonList(
173+
new TargetPool()
174+
.name("example-target-pool")
175+
.targetPort(80)
176+
.targets(
177+
Collections.singletonList(
178+
new Target()
179+
.displayName(
180+
"example-server")
181+
.ip(nicIpv4)))
182+
.activeHealthCheck(
183+
new ActiveHealthCheck()
184+
.healthyThreshold(10)
185+
.interval("3s")
186+
.intervalJitter("3s")
187+
.timeout("3s")
188+
.unhealthyThreshold(
189+
10))))
190+
.listeners(
191+
Collections.singletonList(
192+
new Listener()
193+
.displayName("example-listener")
194+
.port(80)
195+
.protocol(
196+
Listener.ProtocolEnum
197+
.PROTOCOL_TCP)
198+
.targetPool("example-target-pool")
199+
.tcp(
200+
new OptionsTCP()
201+
.idleTimeout("90s"))))
202+
.disableTargetSecurityGroupAssignment(false)
203+
.externalAddress(externalAddress)
204+
.options(
205+
new LoadBalancerOptions()
206+
.observability(
207+
new LoadbalancerOptionObservability()
208+
.logs(
209+
new LoadbalancerOptionLogs()
210+
.credentialsRef(
211+
updateCredentials
212+
.getCredential()
213+
.getCredentialsRef())
214+
.pushUrl(
215+
"https://logs.stackit<id>.argus.eu01.stackit.cloud/instances/<instance-id>/loki/api/v1/push"))
216+
.metrics(
217+
new LoadbalancerOptionMetrics()
218+
.credentialsRef(
219+
updateCredentials
220+
.getCredential()
221+
.getCredentialsRef())
222+
.pushUrl(
223+
"https://push.metrics.stackit<id>.argus.eu01.stackit.cloud/instances/<instance-id>/api/v1/receive"))))
224+
.labels(
225+
Collections.singletonMap(
226+
"some-load-balancer-label", "bar")),
227+
null);
228+
229+
assert newLoadbalancer.getName() != null;
230+
/* wait until load balancer creation is completed */
231+
while (Objects.equals(
232+
loadBalancerApi
233+
.getLoadBalancer(projectId, region, newLoadbalancer.getName())
234+
.getStatus(),
235+
LoadBalancer.StatusEnum.STATUS_PENDING)) {
236+
System.out.println("Waiting for load balancer creation to complete ...");
237+
TimeUnit.SECONDS.sleep(5);
238+
}
239+
240+
/* fetch the created load balancer instance */
241+
System.out.println("\nGetting created load balancer instance:");
242+
LoadBalancer fetchedLoadbalancer =
243+
loadBalancerApi.getLoadBalancer(projectId, region, "java-sdk-example");
244+
assert fetchedLoadbalancer.getTargetPools() != null;
245+
assert fetchedLoadbalancer.getListeners() != null;
246+
System.out.println("* Name: " + fetchedLoadbalancer.getName());
247+
System.out.println("* Private address: " + fetchedLoadbalancer.getPrivateAddress());
248+
System.out.println("* External address: " + fetchedLoadbalancer.getExternalAddress());
249+
System.out.println("* Status: " + fetchedLoadbalancer.getStatus());
250+
System.out.println("* Errors: " + fetchedLoadbalancer.getErrors());
251+
System.out.println("* Version: " + fetchedLoadbalancer.getVersion());
252+
System.out.println("* Target pools: " + fetchedLoadbalancer.getTargetPools().size());
253+
System.out.println("* Listeners: " + fetchedLoadbalancer.getListeners().size());
254+
255+
/* update the load balancer we just created */
256+
assert fetchedLoadbalancer.getName() != null;
257+
LoadBalancer updatedLoadbalancer =
258+
loadBalancerApi.updateLoadBalancer(
259+
projectId,
260+
region,
261+
fetchedLoadbalancer.getName(),
262+
new UpdateLoadBalancerPayload()
263+
.name(fetchedLoadbalancer.getName())
264+
.externalAddress(externalAddress)
265+
.version(fetchedLoadbalancer.getVersion())
266+
.addNetworksItem(
267+
new Network()
268+
.networkId(networkId)
269+
.role(
270+
Network.RoleEnum
271+
.ROLE_LISTENERS_AND_TARGETS))
272+
.listeners(
273+
Collections.singletonList(
274+
new Listener()
275+
.displayName("example-listener-update")
276+
.port(443)
277+
.protocol(
278+
Listener.ProtocolEnum
279+
.PROTOCOL_TCP)
280+
.targetPool(
281+
"example-target-pool-update")
282+
.tcp(
283+
new OptionsTCP()
284+
.idleTimeout("300s"))))
285+
.targetPools(
286+
Collections.singletonList(
287+
new TargetPool()
288+
.name("example-target-pool-update")
289+
.targetPort(80)
290+
.targets(
291+
Collections.singletonList(
292+
new Target()
293+
.displayName(
294+
"example-server-update")
295+
.ip(nicIpv4)))
296+
.activeHealthCheck(
297+
new ActiveHealthCheck()
298+
.healthyThreshold(5)
299+
.interval("5s")
300+
.intervalJitter("2s")
301+
.timeout("4s")
302+
.unhealthyThreshold(
303+
5))))
304+
.labels(
305+
Collections.singletonMap(
306+
"some-load-balancer-label", "bar-updated")));
307+
308+
/* wait until load balancer update is completed */
309+
assert updatedLoadbalancer.getName() != null;
310+
while (Objects.equals(
311+
loadBalancerApi
312+
.getLoadBalancer(projectId, region, updatedLoadbalancer.getName())
313+
.getStatus(),
314+
LoadBalancer.StatusEnum.STATUS_PENDING)) {
315+
System.out.println("Waiting for load balancer update to complete ...");
316+
TimeUnit.SECONDS.sleep(5);
317+
}
318+
319+
/* fetch the load balancer we just updated */
320+
System.out.println("\nUpdated load balancer instance:");
321+
fetchedLoadbalancer =
322+
loadBalancerApi.getLoadBalancer(
323+
projectId, region, fetchedLoadbalancer.getName());
324+
assert fetchedLoadbalancer.getTargetPools() != null;
325+
assert fetchedLoadbalancer.getListeners() != null;
326+
System.out.println("* Name: " + fetchedLoadbalancer.getName());
327+
System.out.println("* Private address: " + fetchedLoadbalancer.getPrivateAddress());
328+
System.out.println("* External address: " + fetchedLoadbalancer.getExternalAddress());
329+
System.out.println("* Status: " + fetchedLoadbalancer.getStatus());
330+
System.out.println("* Errors: " + fetchedLoadbalancer.getErrors());
331+
System.out.println("* Version: " + fetchedLoadbalancer.getVersion());
332+
System.out.println("* Target pools: " + fetchedLoadbalancer.getTargetPools().size());
333+
System.out.println("* Listeners: " + fetchedLoadbalancer.getListeners().size());
334+
335+
/* listing all load balancers */
336+
System.out.println("\nList all load balancers:");
337+
ListLoadBalancersResponse listLoadBalancersResponse =
338+
loadBalancerApi.listLoadBalancers(projectId, region, "100", null);
339+
assert listLoadBalancersResponse.getLoadBalancers() != null;
340+
for (LoadBalancer loadBalancer : listLoadBalancersResponse.getLoadBalancers()) {
341+
System.out.println("*****************");
342+
System.out.println("* Name: " + loadBalancer.getName());
343+
System.out.println("* Status: " + loadBalancer.getStatus());
344+
System.out.println("* IP Address: " + loadBalancer.getExternalAddress());
345+
assert loadBalancer.getListeners() != null;
346+
System.out.println("* Listeners: " + loadBalancer.getListeners().size());
347+
assert loadBalancer.getTargetPools() != null;
348+
System.out.println("* Target pools: " + loadBalancer.getTargetPools().size());
349+
}
350+
351+
/*
352+
* ///////////////////////////////////////////////////////
353+
* // D E L E T I O N //
354+
* ///////////////////////////////////////////////////////
355+
*/
356+
/* trigger deletion of the created load balancer instance */
357+
assert fetchedLoadbalancer.getName() != null;
358+
System.out.println("\nTrigger deletion of the created load balancer");
359+
loadBalancerApi.deleteLoadBalancer(projectId, region, fetchedLoadbalancer.getName());
360+
361+
/* wait for load balancer deletion to complete */
362+
while (true) {
363+
try {
364+
loadBalancerApi.getLoadBalancer(
365+
projectId, region, fetchedLoadbalancer.getName());
366+
System.out.println("Waiting for load balancer deletion to complete ...");
367+
TimeUnit.SECONDS.sleep(5);
368+
} catch (ApiException e) {
369+
if (e.getCode() == HttpURLConnection.HTTP_NOT_FOUND) {
370+
break;
371+
}
372+
}
373+
}
374+
System.out.println("* Successfully deleted");
375+
376+
/* deleting the credentials we just added */
377+
assert newCredentials.getCredential().getCredentialsRef() != null;
378+
System.out.println("\nDeleting the added credentials");
379+
loadBalancerApi.deleteCredentials(
380+
projectId, region, newCredentials.getCredential().getCredentialsRef());
381+
System.out.println("* Successfully deleted");
382+
} catch (ApiException | InterruptedException e) {
383+
throw new RuntimeException(e);
384+
}
385+
}
386+
}

0 commit comments

Comments
 (0)