0
# Service Framework
1
2
Service management utilities built on Google Guava's Service interface, providing lifecycle management with timeout handling and error recovery.
3
4
## Capabilities
5
6
### Service Management Utilities
7
8
Core utilities for managing service lifecycles with timeout control and error handling.
9
10
```java { .api }
11
/**
12
* Utilities for service management and coordination
13
*/
14
public class Services {
15
/**
16
* Attempts to start the passed in service with timeout
17
* @param service The service to start
18
* @param timeout The duration to wait for the service to start
19
* @param timeoutUnit The time unit used for the timeout parameter
20
* @throws TimeoutException If the service can not be started before the specified timeout
21
* @throws InterruptedException If the service is interrupted while trying to start
22
* @throws ExecutionException If an exception occurs while trying to start the service
23
*/
24
public static void startAndWait(Service service, long timeout, TimeUnit timeoutUnit)
25
throws TimeoutException, InterruptedException, ExecutionException;
26
27
/**
28
* Attempts to start the passed in service with timeout and custom error message
29
* @param service The service to start
30
* @param timeout The duration to wait for the service to start
31
* @param timeoutUnit The time unit used for the timeout parameter
32
* @param timeoutErrorMessage An optional error message to display if starting the service times out
33
* @throws TimeoutException If the service can not be started before the specified timeout
34
* @throws InterruptedException If the service is interrupted while trying to start
35
* @throws ExecutionException If an exception occurs while trying to start the service
36
*/
37
public static void startAndWait(Service service, long timeout, TimeUnit timeoutUnit,
38
String timeoutErrorMessage)
39
throws TimeoutException, InterruptedException, ExecutionException;
40
}
41
```
42
43
**Usage Examples:**
44
45
```java
46
import io.cdap.cdap.common.service.Services;
47
import com.google.common.util.concurrent.Service;
48
import java.util.concurrent.TimeUnit;
49
import java.util.concurrent.TimeoutException;
50
import java.util.concurrent.InterruptedException;
51
import java.util.concurrent.ExecutionException;
52
53
// Start a service with timeout
54
try {
55
Services.startAndWait(myService, 30, TimeUnit.SECONDS);
56
System.out.println("Service started successfully");
57
} catch (TimeoutException e) {
58
System.err.println("Service failed to start within 30 seconds");
59
} catch (InterruptedException e) {
60
System.err.println("Service start was interrupted");
61
} catch (ExecutionException e) {
62
System.err.println("Service start failed: " + e.getCause().getMessage());
63
}
64
65
// Start service with custom timeout message
66
try {
67
Services.startAndWait(
68
authenticationService,
69
60,
70
TimeUnit.SECONDS,
71
"Authentication service failed to start within expected time"
72
);
73
} catch (TimeoutException e) {
74
// Custom error message will be logged
75
System.err.println("Custom timeout handling");
76
}
77
```
78
79
### Retry Strategies
80
81
Configurable retry strategies for resilient service operations.
82
83
```java { .api }
84
/**
85
* Interface for retry strategies
86
*/
87
public interface RetryStrategy {
88
/**
89
* Returns the next retry delay in milliseconds, or -1 if no more retries
90
* @param failureCount Number of consecutive failures
91
* @param startTime Time when the operation first started (in milliseconds)
92
* @return Delay in milliseconds before next retry, or -1 to stop retrying
93
*/
94
long nextRetry(int failureCount, long startTime);
95
}
96
97
/**
98
* Common retry strategy implementations
99
*/
100
public class RetryStrategies {
101
/**
102
* No retry strategy - fail immediately
103
*/
104
public static RetryStrategy noRetry();
105
106
/**
107
* Fixed delay retry strategy
108
*/
109
public static RetryStrategy fixedDelay(long delay, TimeUnit timeUnit);
110
111
/**
112
* Exponential backoff retry strategy
113
*/
114
public static RetryStrategy exponentialDelay(long initialDelay, long maxDelay, TimeUnit timeUnit);
115
116
/**
117
* Limited retry strategy that stops after max attempts
118
*/
119
public static RetryStrategy limit(RetryStrategy delegate, int maxAttempts);
120
121
/**
122
* Time-limited retry strategy
123
*/
124
public static RetryStrategy timeLimit(RetryStrategy delegate, long maxElapsedTime, TimeUnit timeUnit);
125
}
126
127
/**
128
* Utility class for executing operations with retry logic
129
*/
130
public class Retries {
131
/**
132
* Call a supplier with retry logic
133
*/
134
public static <V> V callWithRetries(Supplier<V> supplier, RetryStrategy retryStrategy)
135
throws Exception;
136
137
/**
138
* Call a callable with retry logic, handling specific exception types
139
*/
140
public static <V> V callWithRetries(Callable<V> callable, RetryStrategy retryStrategy,
141
Class<? extends Exception>... retryableExceptions) throws Exception;
142
143
/**
144
* Run a runnable with retry logic
145
*/
146
public static void runWithRetries(Runnable runnable, RetryStrategy retryStrategy)
147
throws Exception;
148
}
149
```
150
151
### Service Base Classes
152
153
Abstract base classes for implementing common service patterns.
154
155
```java { .api }
156
/**
157
* Abstract base class for services with retry logic on start failure
158
*/
159
public abstract class AbstractRetryableScheduledService extends AbstractScheduledService {
160
protected AbstractRetryableScheduledService(RetryStrategy retryStrategy);
161
162
@Override
163
protected final void startUp() throws Exception;
164
165
/**
166
* Subclasses implement this method for actual startup logic
167
*/
168
protected abstract void doStartUp() throws Exception;
169
}
170
171
/**
172
* Service decorator that retries start failures
173
*/
174
public class RetryOnStartFailureService extends AbstractService {
175
public RetryOnStartFailureService(Service delegate, RetryStrategy retryStrategy);
176
177
@Override
178
protected void doStart();
179
180
@Override
181
protected void doStop();
182
}
183
184
/**
185
* Service with command port support for remote management
186
*/
187
public abstract class CommandPortService extends AbstractService {
188
protected CommandPortService(String serviceName, int commandPort);
189
190
/**
191
* Get the command port for this service
192
*/
193
public int getCommandPort();
194
195
/**
196
* Handle a command received on the command port
197
*/
198
protected abstract String handleCommand(String command);
199
}
200
```
201
202
### Service Discovery Integration
203
204
Integration components for service discovery and registration.
205
206
```java { .api }
207
/**
208
* Service that integrates with service discovery
209
*/
210
public class ServiceDiscoverable extends AbstractService {
211
public ServiceDiscoverable(String serviceName,
212
InetSocketAddress bindAddress,
213
DiscoveryService discoveryService);
214
215
@Override
216
protected void doStart();
217
218
@Override
219
protected void doStop();
220
221
/**
222
* Get the discoverable for this service
223
*/
224
public Discoverable getDiscoverable();
225
}
226
```