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

HLRC: Add support for XPack Post Start Basic Licence API #33606

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -22,6 +22,8 @@
import org.apache.http.HttpEntity;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.license.PostStartBasicRequest;
import org.elasticsearch.client.license.PostStartBasicResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.xcontent.DeprecationHandler;
Expand Down Expand Up @@ -121,6 +123,28 @@ public void deleteLicenseAsync(DeleteLicenseRequest request, RequestOptions opti
AcknowledgedResponse::fromXContent, listener, emptySet());
}

/**
* Initiates an indefinite basic license.
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public PostStartBasicResponse startBasic(PostStartBasicRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, LicenseRequestConverters::startBasic, options,
PostStartBasicResponse::fromXContent, emptySet());
}

/**
* Asynchronously initiates an indefinite basic license.
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void startBasicAsync(PostStartBasicRequest request, RequestOptions options,
ActionListener<PostStartBasicResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(request, LicenseRequestConverters::startBasic, options,
PostStartBasicResponse::fromXContent, listener, emptySet());
}

/**
* Converts an entire response into a json string
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@

import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.license.PostStartBasicRequest;
import org.elasticsearch.protocol.xpack.license.DeleteLicenseRequest;
import org.elasticsearch.protocol.xpack.license.GetLicenseRequest;
import org.elasticsearch.protocol.xpack.license.PutLicenseRequest;
Expand Down Expand Up @@ -61,4 +63,20 @@ static Request deleteLicense(DeleteLicenseRequest deleteLicenseRequest) {
parameters.withMasterTimeout(deleteLicenseRequest.masterNodeTimeout());
return request;
}

static Request startBasic(PostStartBasicRequest postStartBasicRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_xpack")
.addPathPartAsIs("license")
.addPathPartAsIs("start_basic")
.build();
Request request = new Request(HttpPost.METHOD_NAME, endpoint);
RequestConverters.Params parameters = new RequestConverters.Params(request);
parameters.withTimeout(postStartBasicRequest.timeout());
parameters.withMasterTimeout(postStartBasicRequest.masterNodeTimeout());
if (postStartBasicRequest.isAcknowledge()) {
parameters.putParam("acknowledge", "true");
}
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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.client.license;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.master.AcknowledgedRequest;

public class PostStartBasicRequest extends AcknowledgedRequest<PostStartBasicRequest> {
private boolean acknowledge = false;
Copy link
Contributor

Choose a reason for hiding this comment

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

pls make this boolean final and remove the setter.


public PostStartBasicRequest() {
}

@Override
public ActionRequestValidationException validate() {
return null;
}

public void setAcknowledge(boolean acknowledge) {
this.acknowledge = acknowledge;
}

public boolean isAcknowledge() {
return acknowledge;
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
/*
* 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.client.license;

import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.protocol.xpack.common.ProtocolUtils;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg;
import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;

public class PostStartBasicResponse extends AcknowledgedResponse {
Copy link
Contributor

Choose a reason for hiding this comment

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

This class looks like it has a lot of extra stuff that is not needed. In general, we do not need from/to transport serialization. Do we need addCustomFields, as its also toXContent related.


private static final ConstructingObjectParser<PostStartBasicResponse, Void> PARSER = new ConstructingObjectParser<>(
"post_start_basic_response", true, (a, v) -> {
boolean basicWasStarted = (Boolean) a[0];
String errorMessage = (String) a[1];

if (basicWasStarted) {
return new PostStartBasicResponse(PostStartBasicResponse.Status.GENERATED_BASIC);
}
PostStartBasicResponse.Status status = PostStartBasicResponse.Status.fromErrorMessage(errorMessage);
@SuppressWarnings("unchecked") Tuple<String, Map<String, String[]>> acknowledgements = (Tuple<String, Map<String, String[]>>) a[2];
return new PostStartBasicResponse(status, acknowledgements.v2(), acknowledgements.v1());
});

private static final ParseField BASIC_WAS_STARTED = new ParseField("basic_was_started");
Copy link
Contributor

Choose a reason for hiding this comment

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

private static final ParseField ERROR_MESSAGE = new ParseField("error_message");
private static final ParseField ACKNOWLEDGE = new ParseField("acknowledge");
private static final ParseField MESSAGE = new ParseField("message");

static {
PARSER.declareBoolean(constructorArg(), BASIC_WAS_STARTED);
PARSER.declareString(optionalConstructorArg(), ERROR_MESSAGE);
PARSER.declareObject(optionalConstructorArg(), (parser, v) -> {
Map<String, String[]> acknowledgeMessages = new HashMap<>();
String message = null;
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if (currentFieldName == null) {
throw new XContentParseException(parser.getTokenLocation(), "expected message header or acknowledgement");
}
if (MESSAGE.getPreferredName().equals(currentFieldName)) {
ensureExpectedToken(XContentParser.Token.VALUE_STRING, token, parser::getTokenLocation);
message = parser.text();
} else {
if (token != XContentParser.Token.START_ARRAY) {
throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement type");
}
List<String> acknowledgeMessagesList = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
ensureExpectedToken(XContentParser.Token.VALUE_STRING, token, parser::getTokenLocation);
acknowledgeMessagesList.add(parser.text());
}
acknowledgeMessages.put(currentFieldName, acknowledgeMessagesList.toArray(new String[0]));
}
}
}
return new Tuple<>(message, acknowledgeMessages);
},
ACKNOWLEDGE);
}

private Map<String, String[]> acknowledgeMessages;
private String acknowledgeMessage;

public enum Status {
Copy link
Contributor

Choose a reason for hiding this comment

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

is this a more common class that can be used elsewhere? if so, lets break it out to its own class, and put it in the same package.

GENERATED_BASIC(true, null, RestStatus.OK),
ALREADY_USING_BASIC(false, "Operation failed: Current license is basic.", RestStatus.FORBIDDEN),
NEED_ACKNOWLEDGEMENT(false, "Operation failed: Needs acknowledgement.", RestStatus.OK);

private final boolean isBasicStarted;
private final String errorMessage;
private final RestStatus restStatus;

Status(boolean isBasicStarted, String errorMessage, RestStatus restStatus) {
this.isBasicStarted = isBasicStarted;
this.errorMessage = errorMessage;
this.restStatus = restStatus;
}

public boolean isBasicStarted() {
return isBasicStarted;
}

public String getErrorMessage() {
return errorMessage;
}

RestStatus getRestStatus() {
return restStatus;
}

static PostStartBasicResponse.Status fromErrorMessage(final String errorMessage) {
final PostStartBasicResponse.Status[] values = PostStartBasicResponse.Status.values();
for (PostStartBasicResponse.Status status : values) {
if (Objects.equals(status.errorMessage, errorMessage)) {
return status;
}
}
throw new IllegalArgumentException("No status for error message ['" + errorMessage + "']");
}
}

private PostStartBasicResponse.Status status;

public PostStartBasicResponse() {
}

public PostStartBasicResponse(PostStartBasicResponse.Status status) {
this(status, Collections.emptyMap(), null);
}

public PostStartBasicResponse(PostStartBasicResponse.Status status,
Map<String, String[]> acknowledgeMessages, String acknowledgeMessage) {
super(status != PostStartBasicResponse.Status.NEED_ACKNOWLEDGEMENT);
this.status = status;
this.acknowledgeMessages = acknowledgeMessages;
this.acknowledgeMessage = acknowledgeMessage;
}

public PostStartBasicResponse.Status getStatus() {
return status;
}

public String acknowledgeMessage() {
return acknowledgeMessage;
}

public Map<String, String[]> acknowledgeMessages() {
return acknowledgeMessages;
}

@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
status = in.readEnum(PostStartBasicResponse.Status.class);
acknowledgeMessage = in.readOptionalString();
int size = in.readVInt();
Map<String, String[]> acknowledgeMessages = new HashMap<>(size);
for (int i = 0; i < size; i++) {
String feature = in.readString();
int nMessages = in.readVInt();
String[] messages = new String[nMessages];
for (int j = 0; j < nMessages; j++) {
messages[j] = in.readString();
}
acknowledgeMessages.put(feature, messages);
}
this.acknowledgeMessages = acknowledgeMessages;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeEnum(status);
out.writeOptionalString(acknowledgeMessage);
out.writeVInt(acknowledgeMessages.size());
for (Map.Entry<String, String[]> entry : acknowledgeMessages.entrySet()) {
out.writeString(entry.getKey());
out.writeVInt(entry.getValue().length);
for (String message : entry.getValue()) {
out.writeString(message);
}
}
}

@Override
protected void addCustomFields(XContentBuilder builder, Params params) throws IOException {
if (status.isBasicStarted()) {
builder.field(BASIC_WAS_STARTED.getPreferredName(), true);
} else {
builder.field(BASIC_WAS_STARTED.getPreferredName(), false);
builder.field(ERROR_MESSAGE.getPreferredName(), status.getErrorMessage());
}
if (acknowledgeMessages.isEmpty() == false) {
builder.startObject(ACKNOWLEDGE.getPreferredName());
builder.field(MESSAGE.getPreferredName(), acknowledgeMessage);
for (Map.Entry<String, String[]> entry : acknowledgeMessages.entrySet()) {
builder.startArray(entry.getKey());
for (String message : entry.getValue()) {
builder.value(message);
}
builder.endArray();
}
builder.endObject();
}
}

public static PostStartBasicResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}

@Override
public String toString() {
return Strings.toString(this, true, true);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if ((o instanceof PostStartBasicResponse) == false || super.equals(o) == false) return false;
PostStartBasicResponse that = (PostStartBasicResponse) o;
return status == that.status
&& Objects.equals(acknowledgeMessage, that.acknowledgeMessage)
&& ProtocolUtils.equals(acknowledgeMessages, that.acknowledgeMessages);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), ProtocolUtils.hashCode(acknowledgeMessages), acknowledgeMessage, status);
}
}
Loading