Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json support in painless #60925

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ The following classes are available grouped by their respective packages. Click
<<painless-api-reference-shared-org-elasticsearch-painless-api, Expand details for org.elasticsearch.painless.api>>

* <<painless-api-reference-shared-Debug, Debug>>
* <<painless-api-reference-shared-Json, Json>>

==== org.elasticsearch.script
<<painless-api-reference-shared-org-elasticsearch-script, Expand details for org.elasticsearch.script>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8509,6 +8509,12 @@ See the <<painless-api-reference-shared, Shared API>> for a high-level overview
=== Shared API for package org.elasticsearch.script
See the <<painless-api-reference-shared, Shared API>> for a high-level overview of all packages and classes.

[[painless-api-reference-shared-Json]]
==== Json
* static def load(String)
* static String dump(Object)
* static String dump(Object, boolean)

[[painless-api-reference-shared-JodaCompatibleZonedDateTime]]
==== JodaCompatibleZonedDateTime
* int {java11-javadoc}/java.base/java/time/chrono/ChronoZonedDateTime.html#compareTo(java.time.chrono.ChronoZonedDateTime)[compareTo](ChronoZonedDateTime)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.painless.api;

import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;

import java.io.IOException;

public class Json {
public static Object load(String json) throws IOException{
XContentParser parser = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
json);

switch (parser.nextToken()) {
case START_ARRAY:
return parser.list();
case START_OBJECT:
return parser.map();
case VALUE_NUMBER:
return parser.numberValue();
case VALUE_BOOLEAN:
return parser.booleanValue();
case VALUE_STRING:
return parser.text();
default:
return null;
}
}

public static String dump(Object data) throws IOException {
return dump(data, false);
}

public static String dump(Object data, boolean pretty) throws IOException {
XContentBuilder builder = JsonXContent.contentBuilder();
if (pretty) {
builder.prettyPrint();
}
builder.value(data);
builder.flush();
return builder.getOutputStream().toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.painless;

import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;

public class JsonTests extends ScriptTestCase {
public void testDump() {
// simple object dump
Object output = exec("Json.dump(params.data)", singletonMap("data", singletonMap("hello", "world")), true);
assertEquals("{\"hello\":\"world\"}", output);

output = exec("Json.dump(params.data)", singletonMap("data", singletonList(42)), true);
assertEquals("[42]", output);

// pretty print
output = exec("Json.dump(params.data, true)", singletonMap("data", singletonMap("hello", "world")), true);
assertEquals("{\n \"hello\" : \"world\"\n}", output);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you include a test with multiple keys on the same level to ensure that deterministic order (sorting) is done?

{
  "key_a": "keys must be sorted",
  "key_b": 10,
  "key_c": 1
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ypid-geberit thanks for the comment.

This change exposes internal elasticsearch json utility functions. Determinisitic ordering of output is not a requirement for this change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you'd like to request a feature, please submit an issue so we can discuss and prioritize it.

Copy link

@ypid-geberit ypid-geberit Aug 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requirement together with reasoning is part of #37585 that this PR intends to implement. So in this PR it should be stated if you see this as in scope of this PR or not.

Your comment suggests that you don’t. I see this as bad design. It will break your unit tests in hard to debug ways in the future. Not to mention that I could not use this new feature at all for my watch testing and would need to stick with workarounds as shown in #37585.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not opposed to it, but it's not a requirement for this PR. It can be added here or in a later PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's take the ordering over in a new PR after we get this one in. There's going to be a lot of SPI work here already.

We want two modes:

  1. Preserve ordering. dumps(loads(String)) should be as close to a no-op as possible.
  2. Force ordering. Probably need to add an additional flag.

Thanks.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Json maps are, by design, unordered. Thus adding support for json serialization/deserialization to painless should be unencumbered by a requirement to support it, which is what this PR is about. Tests can be made robust to this, just as tests exist for maps in java which do not guarantee iteration order.

Preserve ordering. dumps(loads(String)) should be as close to a no-op as possible.

I don't think this should be a requirement. That would mean the default is to preserve order, which is (1) outside the requirements of json and (2) brings the cost of a heavier weight data structure (eg linked hash map or tree map). Most users of json do not care about the order, since it is not guaranteed by any tools by default.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests can be made robust to this, just as tests exist for maps in java which do not guarantee iteration order.

That is a view that I can understand. Note that currently, it is not supported for testing watches this way however. If this issue next steps on my toes, I will consider changing the testing design to something where Watches would output valid JSON, and then compare the actual output with the expected output in Python. I will add it to elastic/examples#239 (in case anyone cares 😉).

However, I am still very interested in a sort_keys (ref: https://docs.python.org/3/library/json.html#json.dump) feature. Feel free to ignore this requirement in this PR as discussed above.

Preserve ordering. dumps(loads(String)) should be as close to a no-op as possible.

I don't think this should be a requirement.

Agreed.

}

public void testLoad() {
String json = "{\"hello\":\"world\"}";
Object output = exec("Json.load(params.json)", singletonMap("json", json), true);
assertEquals(singletonMap("hello", "world"), output);

json = "[42]";
output = exec("Json.load(params.json)", singletonMap("json", json), true);
assertEquals(singletonList(42), output);
}

}
3 changes: 2 additions & 1 deletion x-pack/plugin/watcher/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ esplugin {
classname 'org.elasticsearch.xpack.watcher.Watcher'
hasNativeController false
requiresKeystore false
extendedPlugins = ['x-pack-core']
extendedPlugins = ['x-pack-core', 'lang-painless']
}

archivesBaseName = 'x-pack-watcher'
Expand All @@ -21,6 +21,7 @@ tasks.named("dependencyLicenses").configure {

dependencies {
compileOnly project(':server')
compileOnly project(':modules:lang-painless:spi')
compileOnly project(path: xpackModule('core'), configuration: 'default')
compileOnly project(path: ':modules:transport-netty4')
compileOnly project(path: ':plugins:transport-nio')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
"Test for json (de)serialization in painless' watcher context":
- do:
watcher.execute_watch:
body: >
{
"watch": {
"trigger": {
"schedule" : { "cron" : "0 0 0 1 * ? 2099" }
},
"input": {
"simple": {
"foo": "bar"
}
},
"condition": {
"script": {
"source": "Json.dump([1, 2, 3, 4]) == '[1,2,3,4]'"
}
},
"transform": {
"script": {
"source": "return Json.load('{\"hello\": \"world\"}')"
}
},
"actions": {
"indexme" : {
"index" : {
"index" : "my_test_index",
"doc_id": "my-id"
}
}
}
}
}

- match: { watch_record.trigger_event.type: "manual" }
- match: { watch_record.state: "executed" }
- match: { watch_record.status.execution_state: "executed" }
- match: { watch_record.status.state.active: true }
- is_true: watch_record.node
- match: { watch_record.status.actions.indexme.ack.state: "ackable" }
- gt: { watch_record.result.execution_duration: 0 }

- do:
indices.refresh: {}

- do:
get:
index: my_test_index
id: my-id

- match: { found: true }
- match: { _source.hello: world }

Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Clock;
import java.time.Duration;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.watcher;

import org.elasticsearch.painless.spi.PainlessExtension;
import org.elasticsearch.painless.spi.Whitelist;
import org.elasticsearch.painless.spi.WhitelistLoader;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.xpack.watcher.condition.WatcherConditionScript;
import org.elasticsearch.xpack.watcher.transform.script.WatcherTransformScript;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WatcherPainlessExtension implements PainlessExtension {

private static final Whitelist WHITELIST =
WhitelistLoader.loadFromResourceFiles(WatcherPainlessExtension.class, "painless_whitelist.txt");

@Override
public Map<ScriptContext<?>, List<Whitelist>> getContextWhitelists() {
Map<ScriptContext<?>, List<Whitelist>> contextWhiltelists = new HashMap<>();
contextWhiltelists.put(WatcherConditionScript.CONTEXT, Collections.singletonList(WHITELIST));
contextWhiltelists.put(WatcherTransformScript.CONTEXT, Collections.singletonList(WHITELIST));
return Collections.unmodifiableMap(contextWhiltelists);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.elasticsearch.xpack.watcher.WatcherPainlessExtension
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License;
# you may not use this file except in compliance with the Elastic License.
#

class org.elasticsearch.painless.api.Json {
def load(String)
String dump(def)
String dump(def, boolean)
}

static_import {
def load(String) from_class org.elasticsearch.painless.api.Json
}