包含算术的内联脚本的观察者条件失败

Watcher condition with inline script containing arithmetic fails

我正在尝试创建一个观察器,它会在我使用超过 80% 的 JVM 堆时触发。

我正在对 elasticsearch v7.5 进行以下查询。

{
    "trigger": {
        "schedule": {
            "interval": "20s"
        }
    },
    "input": {
        "http": {
            "request": {
                "scheme": "https",
                "host": "domain.region.aws",
                "port": 9200,
                "method": "get",
                "path": "/_cluster/stats"
                "params": {},
                "headers": {},
                "auth": {
                    "basic": {
                        "username": "username",
                        "password": "password"
                    }
                }
            }
        }
    },
    "condition": {
        "script": {
            "inline": "return ((ctx.payload.nodes.jvm.mem.heap_used_in_bytes / ctx.payload.nodes.jvm.mem.heap_max_in_bytes) * 100) > 80"
        }
    },
    "actions": {
        "send_email": {
            "email": {
                "to": "some-email@domain.com",
                "subject": "Watcher Notification",
                "body": "{{ctx.payload.nodes.jvm.mem.heap_used_in_bytes}} of the JVM heap memory is currently being used."
            }
        }
    }
}

我的条件似乎返回了错误的结果。

例如:

如果我将脚本更改为:

return ((ctx.payload.nodes.jvm.mem.heap_used_in_bytes / ctx.payload.nodes.jvm.mem.heap_max_in_bytes) * 100) < 1

heap_used_in_bytes = 979683712

heap_max_in_bytes = 2739011584

结果应为:35.767782719(假)

导致响应包含(不正确):

"condition": {
  "type": "script",
  "status": "success",
  "met": true
}

似乎当我尝试使用变量进行简单的查询时它不起作用。例如,将条件更改为 return ctx.payload.nodes.jvm.mem.heap_max_in_bytes > 2739011584 会导致奇怪的编译错误:

{"statusCode":400,"error":"Bad Request","message":"[script_exception] compile error, with { script_stack={ 0=\"... vm.mem.heap_max_in_bytes 2739011584\" & 1=\"                             ^---- HERE\" } & script=\"return ctx.payload.nodes.jvm.mem.heap_max_in_bytes 2739011584\" & lang=\"painless\" }"}

不使用变量的简单比较似乎有效。我能够在 email 操作中的 body 值中打印我在脚本中访问的变量的值。任何人都可以阐明这里发生的事情吗?无论如何,是否可以在电子邮件正文中的某处打印此脚本的结果?

根据该错误消息,这没有使用 Groovy,它使用的是默认 ES 语言,即 painless

根据painless documentation,整数相除会得到一个整数,所以979683712 / 2739011584 == 0

我不是专家,但是 I believe 将您的无痛脚本更改为:

return ((ctx.payload.nodes.jvm.mem.heap_used_in_bytes / (double)ctx.payload.nodes.jvm.mem.heap_max_in_bytes) * 100) < 1

应该修复它(因为它将除法的分母转换为 double

或者,您应该能够做到:

    "condition": {
        "script": {
            "lang": "groovy",
            "inline": "return ((ctx.payload.nodes.jvm.mem.heap_used_in_bytes / ctx.payload.nodes.jvm.mem.heap_max_in_bytes) * 100) > 80"
        }
    },

改为使用 groovy...

希望对您有所帮助...无法轻松测试