dikhan / pagerduty-client

Simple PagerDuty client with full integration with PagerDuty Events APIs v2
https://dikhan.github.io/pagerduty-client/
MIT License
23 stars 27 forks source link

A JSONArray text must start with '[' at 1 [character 2 line 1] #31

Open tarkal opened 2 years ago

tarkal commented 2 years ago

We are using the client to submit a trigger using the following code:


            Payload payload = Payload.Builder.newBuilder()
                    .setSummary(createSummary(operation))
                    .setSource(operation.getAttribute().getId())
                    .setComponent(IdManager.getAncestorId(IdManager.Service.NODE_NODE, operation.getAttribute().getId()))
                    .setGroup(IdManager.getAncestorId(IdManager.Service.NODE_ECU, operation.getAttribute().getId()))
                    .setSeverity(convertHealthToSeverity(operation.getAttribute().getHealth()))
                    .setTimestamp(OffsetDateTime.ofInstant(Instant.ofEpochSecond(operation.getTimestamp()), ZoneOffset.UTC))
                    .setCustomDetails(Json.writeValueToString(operation.getAttribute()))
                    .build();

            TriggerIncident incident = TriggerIncident.TriggerIncidentBuilder
                    .newBuilder(routingKey, payload)
                    .setDedupKey(operation.getAttribute().getId())
                    .setClient(client)
                    .build();

           this.client.trigger(incident);    

The serialized incident as a json looks like this:

{
    "client":"--removed_for_security--",
    "dedup_key":"cu3fbbe4-ne30773e-nnd17182-na11f804",
    "event_action":"trigger",
    "payload":{
       "component":"cu3fbbe4-ne30773e-nnd17182",
       "custom_details":"{\"ecuId\":\"cu3fbbe4-ne30773e\",\"health\":500,\"id\":\"cu3fbbe4-ne30773e-nnd17182-na11f804\",\"nodeId\":\"cu3fbbe4-ne30773e-nnd17182\",\"projectId\":\"cu3fbbe4-np932c1d\",\"read\":{\"type\":\"STRING\"},\"reference\":\"s1_server_disconnected_on_system_initialisation_alarm!\",\"value\":\"Critical\"}",
       "group":"cu3fbbe4-ne30773e",
       "severity":"critical",
       "source":"cu3fbbe4-ne30773e-nnd17182-na11f804",
       "summary":"The value of 's1_server_disconnected_on_system_initialisation_alarm' changed to Critical",
       "timestamp":"2022-07-29T13:45:32Z"
    },
    "routing_key":"--removed_for_security--"
 }

However, we are unexpectedly getting the following error:

com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException: com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]

Screenshot 2022-07-29 at 16 06 36

Any ideas?

tarkal commented 2 years ago

After digging into the code and following the stack trace I found the error is originating from PagerDutyEventsClient.main(...) on line 80.

This is very random as main seems to be a test class!

public static void main(String[] args) throws NotifyEventException {
        String routingKey = "ROUTING_KEY";
        String dedupKey = "DEDUP_KEY";

        PagerDutyEventsClient pagerDutyEventsClient = create();

        JSONObject customDetails = new JSONObject();
        customDetails.put("field", "value1");
        customDetails.put("field2", "value2");

        Payload payload = Payload.Builder.newBuilder()
                .setSummary("This is an incident test to test PagerDutyEventsClient")
                .setSource("testing host")
                .setSeverity(Severity.INFO)
                .setTimestamp(OffsetDateTime.now())
                .setCustomDetails(customDetails)
                .build();

        List<ImageContext> imageContextList = new ArrayList<>();
        imageContextList.add(new ImageContext("src1"));
        List<LinkContext> linkContextList = new ArrayList<>();
        linkContextList.add(new LinkContext("href", "text"));

        TriggerIncident incident = TriggerIncident.TriggerIncidentBuilder
                .newBuilder(routingKey, payload)
                .setDedupKey(dedupKey)
                .setClient("client")
                .setClientUrl("https://monitoring.example.com")
                .setLinks(linkContextList)
                .setImages(imageContextList)
                .build();

        pagerDutyEventsClient.trigger(incident);

        AcknowledgeIncident ack = AcknowledgeIncident.AcknowledgeIncidentBuilder
                .newBuilder(routingKey, dedupKey)
                .build();
        pagerDutyEventsClient.acknowledge(ack);

        ResolveIncident resolve = ResolveIncident.ResolveIncidentBuilder
                .newBuilder(routingKey, dedupKey)
                .build();
        pagerDutyEventsClient.resolve(resolve);

        ChangeEventPayload changeEventPayload = ChangeEventPayload.Builder.newBuilder()
                .setSummary("This is an change event test to test PagerDutyEventsClient")
                .setSource("testing host")
                .setTimestamp(OffsetDateTime.now())
                .setCustomDetails(customDetails)
                .build();

        ChangeEvent changeEvent = ChangeEvent.ChangeEventBuilder
                .newBuilder(routingKey, changeEventPayload)
                .setLinks(linkContextList)
                .build();

        pagerDutyEventsClient.trackChange(changeEvent);
    }

Line 80 in this is:

ChangeEvent changeEvent = ChangeEvent.ChangeEventBuilder
                .newBuilder(routingKey, changeEventPayload)
                .setLinks(linkContextList)
                .build();

So it appears that the error is caused with this static test class and not even our payload.

tarkal commented 2 years ago

So we updated the version to 3.1.2 which seems to be the latest version on maven. The error persists but it now seems to be originating from the response from pager duty:

 private EventResult notifyEvent(PagerDutyEvent event, String api, int retryCount) throws NotifyEventException {
        try {
            HttpRequestWithBody request = Unirest.post(api)
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json");
            request.body(event);
            HttpResponse<JsonNode> jsonResponse = request.asJson();

            if (log.isDebugEnabled()) {
                log.debug(IOUtils.toString(jsonResponse.getRawBody()));
                // A reset, so we can get the contents from the body that were dumped in the log before
                jsonResponse.getRawBody().reset();
            }

            int responseStatus = jsonResponse.getStatus();
            switch(responseStatus) {
                case HttpStatus.SC_OK:
                case HttpStatus.SC_CREATED:
                case HttpStatus.SC_ACCEPTED:
                    return EventResult.successEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getPropertyValue(jsonResponse, "dedup_key"));
                case HttpStatus.SC_BAD_REQUEST:
                    return EventResult.errorEvent(JsonUtils.getPropertyValue(jsonResponse, "status"), JsonUtils.getPropertyValue(jsonResponse, "message"), JsonUtils.getArrayValue(jsonResponse, "errors"));
                case RATE_LIMIT_STATUS_CODE:
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    if (doRetries) {
                        return handleRetries(event, api, retryCount, jsonResponse, responseStatus);
                    } else {
                        return EventResult.errorEvent(String.valueOf(responseStatus), "", IOUtils.toString(jsonResponse.getRawBody()));
                    }
                default:
                    return EventResult.errorEvent(String.valueOf(responseStatus), "", IOUtils.toString(jsonResponse.getRawBody()));
            }
        } catch (UnirestException | IOException e) {
            throw new NotifyEventException(e);
        }
    }

The stack does not show which line is causing it but i'm guessing its coming from HttpResponse<JsonNode> jsonResponse = request.asJson();

iXingo commented 1 year ago

same here

ColaemmZuo commented 1 year ago

Any update here?

iXingo commented 1 year ago

Any update here?

Version 3.0.8 works for me

salml commented 1 year ago

3.0.8 not working for me 🙁

machajdik commented 1 year ago

Same here, in 3.1.2.

Full trace:

  com.github.dikhan.pagerduty.client.events.exceptions.NotifyEventException: com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.github.dikhan.pagerduty.client.events.HttpApiServiceImpl.notifyEvent(HttpApiServiceImpl.java:106)
    at com.github.dikhan.pagerduty.client.events.HttpApiServiceImpl.notifyEvent(HttpApiServiceImpl.java:70)
    at com.github.dikhan.pagerduty.client.events.PagerDutyEventsClient.sendEvent(PagerDutyEventsClient.java:208)
    at com.github.dikhan.pagerduty.client.events.PagerDutyEventsClient.trigger(PagerDutyEventsClient.java:188)
    [...]
Caused by: com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
    at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
    at com.github.dikhan.pagerduty.client.events.HttpApiServiceImpl.notifyEvent(HttpApiServiceImpl.java:79)
    ... 18 more
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:106)
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:139)
    ... 20 more
Caused by: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:51)
    at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:95)
    ... 21 more
Caused by: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONArray.<init>(JSONArray.java:105)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:48)
    ... 22 more

any idea @dikhan?

machajdik commented 1 year ago

Probably an error in the Unirest HTTP client com.mashape.unirest.unirest-java. Maybe an upgrade to com.konghq.unirest-java is possible @dikhan?

DodoMorph commented 11 months ago

See Pull request https://github.com/dikhan/pagerduty-client/pull/32 issue appears if payload isn't json but an error string

aravind-farmint commented 5 months ago

@machajdik @DodoMorph @salml I am still getting this issue. Can we please publish a new package ?