Customizing the criteria for triggering Fallback in Hystrix Circuit Breaker - microservices

I would like to trigger a fallback from a #HystrixCommand Method based on my own criteria (checking for a specific response status).
My method basically acts as a client which calls a service in another URL (marked here as URL).
Here is my code:
#HystrixCommand(fallbackMethod="fallbackPerformOperation")
public Future<Object> performOperation(String requestString) throws InterruptedException {
return new AsyncResult<Object>() {
#Override
public Object invoke() {
Client client = null;
WebResource webResource = null;
ClientResponse response =null;
String results = null;
try{
client = Client.create();
webResource = client.resource(URL);
client.setConnectTimeout(10000);
client.setReadTimeout(10000);
response = webResource.type("application/xml")
.post(ClientResponse.class, requestString);
logger.info("RESPONSE STATUS: " + response.getStatus());
if (response.getStatus() != 200) {
webResource = null;
logger.error(" request failed with the HTTP Status: " + response.getStatus());
throw new RuntimeException(" request failed with the HTTP Status: "
+ response.getStatus());
}
results = response.getEntity(String.class);
} finally {
client.destroy();
webResource = null;
}
return results;
}
};
}
This triggers the fallback Method fallbackPerformOperation() when the response status code is not 200 i.e. response.getStatus()!=200.
The fallback method returns a string which tells the user that the Request did not return a status of 200 and so it is falling back.
I want to know if I can trigger the fallback without having to explicitly throw an exception inside my performOperation() Method.
Could I use #HystrixProperty? I know people mostly use it for timeouts and volume thresholds but could I write a custom #HystrixProperty that checks if the response status is 200 or not within my Method?

Related

spring boot DeferredResult onError how to invoke the callback?

Need to perform some asynchronous processing in a Rest service without holding up the server's Http threads .
I think DeferredResult would be a good option.
However when I am trying to ensure my callback on error gets called - am not able to do so .
Here is a naive attempt on my part:
#GetMapping("/getErrorResults")
public DeferredResult<ResponseEntity<?>> getDeferredResultsError(){
final String METHOD_NAME = "getDeferredResultsError";
logger.info("START : {}",METHOD_NAME);
DeferredResult<ResponseEntity<?>> deferredOutput = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
logger.info("processing in separate thread");
int age = 0;
try {
age = age / 0;
}catch(Exception e) {
logger.error("we got some error");
logger.error(e);
throw e;
}
logger.info("after try catch block");
});
deferredOutput.onError((Throwable t) -> {
logger.error("<<< HERE !!! >>>");
deferredOutput.setErrorResult(
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(t.getMessage()));
});
logger.info("done");
return deferredOutput;
}
When I call this Rest endpoint from Postman - I can see in server logs the arithmetic exception by zero but dont see the 'onError' getting invoked.
After some time get a response in Postman as follows:
{
"timestamp": "2019-07-30T09:57:16.854+0000",
"status": 503,
"error": "Service Unavailable",
"message": "No message available",
"path": "/dfr/getErrorResults"
}
So my question is how does the 'onError' get invoked ?
You need to pass the DeferredResult object to the asynchronous operation so you could update it in case of success or failure:
#GetMapping(value = "/getErrorResults")
public DeferredResult<ResponseEntity<String>> getDeferredResultsError() {
DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
System.out.println("Processing...");
int age = 0;
try {
age = age / 0;
deferredResult.setResult(ResponseEntity.ok("completed"));
}catch(Exception e) {
System.out.println("Failed to process: " + e.getMessage());
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(e.getMessage()));
}
});
return deferredResult;
}
In the code you posted, you returned the DeferredResult object without passing it to the asynchronous operation. So after your return it, SpringMVC holds the client connection and wait until the DeferredResult object will be assigned with some kind of result. But in your case, the DeferredResult is not held by the asynchronous operation and will never updated so you get "Service Unavailable".
Here you can find working (light) project example.

Secure Web API Post Method with Username and Password

I have a Web API service hosted in Microsoft Azure. I need a certain POST method to be only accessible with one unique username and password.
I understand the [Authorize] method does a token based authentication but its not tied to a single username and password. In my app, the web api also does the login authentication, so anyone who registers can access this post method if im not mistaken. (Please correct me if im wrong)
I am new to this could you guide me the right way please.
This is my WebAPI Post method i want to secure access to with specific unique username&pass:
[AllowAnonymous]
[HttpPost, Route("send")]
public async Task<NotificationOutcome> Post([FromBody]string message)
{
string hubName = "myHub";
string hubNameDefaultShared = "myHubNameDefaultShared";
NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);
string installationId = string.Empty;
var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};
NotificationOutcome result = null;
if (string.IsNullOrWhiteSpace(installationId))
{
result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
}
else
{
result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
}
return result;
}
And this is how I currently access the POST Method:
var client = new RestClient("myWebApiRouteName");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "46c23eba-8ca6-4ede-b4fe-161473dc063a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", messageBody, ParameterType.RequestBody);
try
{
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

How to Disable zuul filter for specific condition case and not sending to mapped URL

I have zuul filter implementation with route config
related:
path: /api/search/related/**
url: http://abc.xyz.neverhit.this.URl
and run implementation
#Override
public Object run() {
RequestContext context = getCurrentContext();
HttpServletRequest request = context.getRequest();
UriComponents uri = UriComponentsBuilder.fromHttpUrl(recommendationsServiceHostname)
.path("/recommendations/related")
.query(request.getQueryString()).build();
if (shouldRouteToRecommendationsService(request, uri)) {
logger.info("Calling proxy service");
try {
context.setRouteHost(new URL(uri.toString()));
} catch (MalformedURLException ex) {
logger.error("MalformedURLException for URL:" + uri.toString());
}
}
else
{
//Something here or Solution that should handle a request like a filter is not present.
}
return null;
}
Its working fine for if part and sending the request to proxy service. Problem is for else part.
What I am looking for is in else scenario it should behave like filter never existed and it should handle request it was handling early executing API call from local code.
Any hack or proper solution for this one ?

Oracle MCS Custom API call from MAF Application

I have created a custom API in Oracle MCS to get the user information and trying to call it from MAF application... As a response i am getting 200 as success code... but when i try to parse the response it shows a HTML page instead of actual responce....
Custom API
https://mobileportalsetrial1304dev-mcsdem0001.mobileenv.us2.oraclecloud.com:443/mobile/custom/rvs_ekkfetchuserinfo/fetchcontent
and userid=101 as parameter
Calling Method to get User information
#Override
public Response getUserInformation(int userId) {
System.out.println("In loginService");
String restURI = "https://mobileportalsetrial1304dev-mcsdem0001.mobileenv.us2.oraclecloud.com:443/mobile/custom/rvs_ekkfetchuserinfo/fetchcontent?userid=" + userId;
String jsonRequest = "";
Response response = new Response();
response = RestUtil.callGet(restURI, jsonRequest);
return response;
}
callGet Method
public static Response callGet(String restURI, String jsonRequest) {
String responseJson = "";
Response response = new Response();
System.out.println("restURI:" + restURI);
RestServiceAdapter restServiceAdapter = Model.createRestServiceAdapter();
restServiceAdapter.clearRequestProperties();
restServiceAdapter.setConnectionName("MiddlewareAPI");
restServiceAdapter.setRequestType(RestServiceAdapter.REQUEST_TYPE_GET);
restServiceAdapter.addRequestProperty("Content-Type", "application/json");
restServiceAdapter.addRequestProperty("Accept", "application/json; charset=UTF-8");
restServiceAdapter.addRequestProperty("Oracle-Mobile-Backend-Id", "da5c7d86-29c0-43e8-b613-53de55a7ae6c");
restServiceAdapter.addRequestProperty("Authorization", "Basic TUNTREVNMDAwMV9NT0JJTEVQT1JUQUxTRVRSSUFMMTMwNERFVl9NT0JJTEVfQU5PTllNT1VTX0FQUElEOmR5Nm91NW5wX3RnbE5r");//+new String(encodedBytes));
restServiceAdapter.setRequestURI(restURI);
restServiceAdapter.setRetryLimit(0);
try {
responseJson = restServiceAdapter.send(jsonRequest);
System.out.println("response" + responseJson);
int responseCode = restServiceAdapter.getResponseStatus();
System.out.println("responseCode" + responseCode);
response.setResponseCode(responseCode);
response.setResponseMessage(responseJson);
response.setHeader(restServiceAdapter.getResponseHeaders());
} catch (Exception e) {
System.out.println("Error in calling API" + e.getStackTrace());
int responseCode = restServiceAdapter.getResponseStatus();
response.setResponseCode(responseCode);
response.setResponseMessage(responseJson);
}
return response;
}
Json Parsing
JSONObject obj = new JSONObject(response);
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String user_id = arr.getJSONObject(i).getString("UserId");
}
Here what i am getting is JSONObject["items"] is not found... when i print the responce message it gives a HTML Script file
Expected Output
{
"items": [
{
"UserId": "101",
"AgentId": null,
"Category": "Rental",
"Division": "KDR",
"Status": null,
"LocationId": null,
"Operation": "CheckOut",
"Admin": "N",
"createdBy": "mcs-demo_user09#oracleads.com",
"createdOn": "2015-09-25T11:29:10.215564+00:00",
"modifiedBy": "mcs-demo_user09#oracleads.com",
"modifiedOn": "2015-09-25T11:29:10.215564+00:00"
}
]
}
what is the content of the HTML page (it will have some JavaScript I assume but should have a HTML title as well). Anyway, a user Id in MCS is not 101 but an internal ID, so I don't know if you've chosen 101 for simplification in this question.
In MAF, the REST connection is defined through a REST connection with the root URL and the relative URI. In your example, the REST connection is referenced as "MiddlewareAPI". Unless the value of this connection is null, the restURI you provide needs to be reduced to not contain the root URL.
The HTTP 200 you get because the request is answered by the server. However, it appears to be missing either an authorized user (in case of a failed basic authorization for accessing the API) or the authenticated user is not allowed to request the user platform API (by default you can only request information about the user you re authenticated as).
Frank
Hi I got the solution...
I was trying to call customAPI through Oracle-MCS. I replaced RestServiceAdapter with HttpsURLConnection. Then it Works perfectly fine.

Volley retry request

I am currently testing out the volley library. But when request fails (404) it doesn't get executed again or at least there are no errors.However there is data missing. Is this the right way to retry a request if it has been failed ?
Thanks in advance
req.setRetryPolicy(new DefaultRetryPolicy(5000,1,1.0f));
queue.add(req);
Usage :
JsonObjectRequest req = null;
for(int i=0;i<profielen.size();i++){
final int pos = i;
req = new JsonObjectRequest(Request.Method.GET, imageLocUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setImageOnProfile(pos,response.get("thumbnail").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.setRetryPolicy(new DefaultRetryPolicy(5000,1,1.0f));
queue.add(req);
}
No, that is not the right way.
Asides:
HTTP 404 is not a status code I would expect a normally-behaved HTTP
client under normal condition to retry.
You most like are receiving an error via the error listener you
supply to the request, but your error listener is a NOOP so maybe
you're not noticing?
(http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html has OK
descriptions of the status code meanings.)
The request's retry policy only applies to failures due to: open socket timeouts, socket opening timeouts, HTTP 401s and HTTP 403s. All other failures are not automatically retried, AFAIK.
I think that to retry a 404 with Volley you need to retry it by hand in onErrorResponse.
(Ficus: it would be nice if the RetryPolicy was consulted for error status codes. I would like to be able to set a policy that retries on 503s.)

Resources