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

feat: support task auto manage by server role state machine #2130

Merged
merged 16 commits into from
Mar 8, 2023
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.apache.hugegraph.api.filter;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.masterelection.GlobalMasterInfo;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.Log;
import org.glassfish.hk2.api.IterableProvider;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.jersey.message.internal.HeaderUtils;
import org.slf4j.Logger;

import jakarta.ws.rs.NameBinding;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;

public class RedirectFilter implements ContainerRequestFilter {

private static final Logger LOG = Log.logger(RedirectFilter.class);

private static final String X_HG_REDIRECT = "x-hg-redirect";

private static volatile Client client = null;

@Context
private IterableProvider<GraphManager> managerProvider;

private static final Set<String> MUST_BE_NULL = new HashSet<>();

static {
MUST_BE_NULL.add("DELETE");
MUST_BE_NULL.add("GET");
MUST_BE_NULL.add("HEAD");
MUST_BE_NULL.add("TRACE");
}

@Override
public void filter(ContainerRequestContext context) throws IOException {
ServiceHandle<GraphManager> handle = this.managerProvider.getHandle();
E.checkState(handle != null, "Context GraphManager is absent");
GraphManager manager = handle.getService();
E.checkState(manager != null, "Context GraphManager is absent");
GlobalMasterInfo globalMasterInfo = manager.globalMasterInfo();
if (globalMasterInfo == null || !globalMasterInfo.isFeatureSupport()) {
return;
}

String redirectTag = context.getHeaderString(X_HG_REDIRECT);
if (StringUtils.isNotEmpty(redirectTag)) {
return;
}

String url;
synchronized (globalMasterInfo) {
if (globalMasterInfo.isMaster() || StringUtils.isEmpty(globalMasterInfo.url())) {
return;
}
url = globalMasterInfo.url();
}

URI redirectUri;
try {
URIBuilder redirectURIBuilder = new URIBuilder(context.getUriInfo().getRequestUri());
URI masterURI = URI.create(url);
redirectURIBuilder.setHost(masterURI.getHost());
redirectURIBuilder.setPort(masterURI.getPort());
redirectURIBuilder.setScheme(masterURI.getScheme());

redirectUri = redirectURIBuilder.build();
} catch (URISyntaxException e) {
LOG.error("Redirect request exception occurred", e);
return;
}
this.initClientIfNeeded();
Response response = this.forwardRequest(context, redirectUri);
context.abortWith(response);
}

private Response forwardRequest(ContainerRequestContext requestContext, URI redirectUri) {
MultivaluedMap<String, String> headers = requestContext.getHeaders();
MultivaluedMap<String, Object> newHeaders = HeaderUtils.createOutbound();
if (headers != null) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
for (String value : entry.getValue()) {
newHeaders.add(entry.getKey(), value);
}
}
}
newHeaders.add(X_HG_REDIRECT, new Date().getTime());
Invocation.Builder builder = client.target(redirectUri)
.request()
.headers(newHeaders);
Response response;
if (MUST_BE_NULL.contains(requestContext.getMethod())) {
response = builder.method(requestContext.getMethod());
} else {
response = builder.method(requestContext.getMethod(),
Entity.json(requestContext.getEntityStream()));
}
return response;
}

private void initClientIfNeeded() {
if (client != null) {
return;
}

synchronized (RedirectFilter.class) {
if (client != null) {
return;
}
client = ClientBuilder.newClient();
}
}

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface RedirectMasterRole {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.apache.hugegraph.api.filter;

import jakarta.ws.rs.container.DynamicFeature;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.FeatureContext;
import jakarta.ws.rs.ext.Provider;

@Provider
public class RedirectFilterDynamicFeature implements DynamicFeature {

@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if (resourceInfo.getResourceMethod()
.isAnnotationPresent(RedirectFilter.RedirectMasterRole.class)) {
context.register(RedirectFilter.class);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import jakarta.ws.rs.core.UriInfo;

import org.apache.hugegraph.api.filter.CompressInterceptor.Compress;
import org.apache.hugegraph.api.filter.RedirectFilter;
import org.apache.hugegraph.config.HugeConfig;
import org.apache.hugegraph.metrics.MetricsUtil;
import com.codahale.metrics.Histogram;
Expand All @@ -51,6 +52,7 @@ public class GremlinAPI extends GremlinQueryAPI {
@Compress
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RedirectFilter.RedirectMasterRole
public Response post(@Context HugeConfig conf,
@Context HttpHeaders headers,
String request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,20 @@

import java.util.Map;

import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.server.RestServer;
import org.slf4j.Logger;

import org.apache.hugegraph.HugeGraph;
import org.apache.hugegraph.api.API;
import org.apache.hugegraph.api.filter.RedirectFilter;
import org.apache.hugegraph.api.filter.StatusFilter.Status;
import org.apache.hugegraph.backend.id.Id;
import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.job.AlgorithmJob;
import org.apache.hugegraph.job.JobBuilder;
import org.apache.hugegraph.server.RestServer;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.JsonUtil;
import org.apache.hugegraph.util.Log;
import org.slf4j.Logger;

import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

Expand All @@ -56,6 +57,7 @@ public class AlgorithmAPI extends API {
@Status(Status.CREATED)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RedirectFilter.RedirectMasterRole
public Map<String, Id> post(@Context GraphManager manager,
@PathParam("graph") String graph,
@PathParam("name") String algorithm,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,33 @@

import java.util.Map;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.inject.Singleton;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;

import org.apache.hugegraph.core.GraphManager;
import org.slf4j.Logger;

import org.apache.hugegraph.HugeGraph;
import org.apache.hugegraph.api.API;
import org.apache.hugegraph.api.filter.RedirectFilter;
import org.apache.hugegraph.api.filter.StatusFilter.Status;
import org.apache.hugegraph.backend.id.Id;
import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.job.ComputerJob;
import org.apache.hugegraph.job.JobBuilder;
import org.apache.hugegraph.task.HugeTask;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.JsonUtil;
import org.apache.hugegraph.util.Log;
import org.slf4j.Logger;

import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.inject.Singleton;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;

@Path("graphs/{graph}/jobs/computer")
@Singleton
@Tag(name = "ComputerAPI")
Expand All @@ -58,6 +59,7 @@ public class ComputerAPI extends API {
@Status(Status.CREATED)
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RedirectFilter.RedirectMasterRole
public Map<String, Id> post(@Context GraphManager manager,
@PathParam("graph") String graph,
@PathParam("name") String computer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,36 +25,37 @@
import java.util.HashMap;
import java.util.Map;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Singleton;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;

import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.define.Checkable;
import org.apache.hugegraph.metrics.MetricsUtil;
import org.slf4j.Logger;

import org.apache.hugegraph.HugeException;
import org.apache.hugegraph.HugeGraph;
import org.apache.hugegraph.api.API;
import org.apache.hugegraph.api.filter.RedirectFilter;
import org.apache.hugegraph.api.filter.StatusFilter.Status;
import org.apache.hugegraph.backend.id.Id;
import org.apache.hugegraph.core.GraphManager;
import org.apache.hugegraph.define.Checkable;
import org.apache.hugegraph.job.GremlinJob;
import org.apache.hugegraph.job.JobBuilder;
import org.apache.hugegraph.metrics.MetricsUtil;
import org.apache.hugegraph.util.E;
import org.apache.hugegraph.util.JsonUtil;
import org.apache.hugegraph.util.Log;
import org.slf4j.Logger;

import com.codahale.metrics.Histogram;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Singleton;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;

@Path("graphs/{graph}/jobs/gremlin")
@Singleton
@Tag(name = "GremlinAPI")
Expand All @@ -73,6 +74,7 @@ public class GremlinAPI extends API {
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed({"admin", "$owner=$graph $action=gremlin_execute"})
@RedirectFilter.RedirectMasterRole
public Map<String, Id> post(@Context GraphManager manager,
@PathParam("graph") String graph,
GremlinRequest request) {
Expand Down
Loading