index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/PublicPushServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.msg.PublicMessageContext; import com.netflix.msl.server.common.PushServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; /** * @author Wesley Miaw <[email protected]> */ public class PublicPushServlet extends PushServlet { private static final long serialVersionUID = 5346709653657304340L; /** * <p>Create a new public push servlet that will echo any received data in * a push message that does not require secrecy.</p> * * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public PublicPushServlet() throws Exception { super(EntityAuthenticationScheme.RSA, TokenFactoryType.ACCEPT_NON_REPLAYABLE_ID, 0, null, null, null, null, null, false, false); } /* (non-Javadoc) * @see com.netflix.msl.server.common.PushServlet#process(com.netflix.msl.msg.MessageInputStream) */ @Override protected List<MessageContext> process(final MessageInputStream mis) throws IOException { // Read the request. final ByteArrayOutputStream data = new ByteArrayOutputStream(); do { final byte[] cbuf = new byte[1024]; final int count = mis.read(cbuf); if (count == -1) break; data.write(cbuf, 0, count); } while (true); final MessageContext msgCtx = new PublicMessageContext() { @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } @Override public String getRemoteEntityIdentity() { return null; } @Override public boolean isRequestingTokens() { return false; } @Override public String getUserId() { return null; } @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { return null; } @Override public MslUser getUser() { return null; } @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { return Collections.emptySet(); } @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } @Override public void write(final MessageOutputStream output) throws IOException { output.write(data.toByteArray()); output.close(); } @Override public MessageDebugContext getDebugContext() { return null; } }; return Arrays.asList(msgCtx); } }
2,100
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/MultiPushServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.msg.PublicMessageContext; import com.netflix.msl.server.common.PushServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; /** * @author Wesley Miaw <[email protected]> */ public class MultiPushServlet extends PushServlet { private static final long serialVersionUID = -584699388668046804L; /** * <p>Create a new secret push servlet that will echo any received data in * multiple push messages that require secrecy.</p> * * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public MultiPushServlet() throws Exception { super(EntityAuthenticationScheme.RSA, TokenFactoryType.ACCEPT_NON_REPLAYABLE_ID, 0, null, null, null, null, null, false, false); } /* (non-Javadoc) * @see com.netflix.msl.server.common.PushServlet#process(com.netflix.msl.msg.MessageInputStream) */ @Override protected List<MessageContext> process(final MessageInputStream mis) throws IOException { // Read the request. final ByteArrayOutputStream data = new ByteArrayOutputStream(); do { final byte[] cbuf = new byte[1024]; final int count = mis.read(cbuf); if (count == -1) break; data.write(cbuf, 0, count); } while (true); final MessageContext msgCtx = new PublicMessageContext() { @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } @Override public String getRemoteEntityIdentity() { return null; } @Override public boolean isRequestingTokens() { return false; } @Override public String getUserId() { return null; } @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { return null; } @Override public MslUser getUser() { return null; } @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { return Collections.emptySet(); } @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } @Override public void write(final MessageOutputStream output) throws IOException { output.write(data.toByteArray()); output.close(); } @Override public MessageDebugContext getDebugContext() { return null; } }; return Arrays.asList(msgCtx, msgCtx, msgCtx); } }
2,101
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/SecretPushServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyRequestData; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MessageOutputStream; import com.netflix.msl.msg.MessageServiceTokenBuilder; import com.netflix.msl.msg.SecretMessageContext; import com.netflix.msl.server.common.PushServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.tokens.MslUser; import com.netflix.msl.userauth.UserAuthenticationData; /** * @author Wesley Miaw <[email protected]> */ public class SecretPushServlet extends PushServlet { private static final long serialVersionUID = 5346709653657304340L; /** * <p>Create a new secret push servlet that will echo any received data in * a push message that requires secrecy.</p> * * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public SecretPushServlet() throws Exception { super(EntityAuthenticationScheme.RSA, TokenFactoryType.ACCEPT_NON_REPLAYABLE_ID, 0, null, null, null, null, null, false, false); } /* (non-Javadoc) * @see com.netflix.msl.server.common.PushServlet#process(com.netflix.msl.msg.MessageInputStream) */ @Override protected List<MessageContext> process(final MessageInputStream mis) throws IOException { // Read the request. final ByteArrayOutputStream data = new ByteArrayOutputStream(); do { final byte[] cbuf = new byte[1024]; final int count = mis.read(cbuf); if (count == -1) break; data.write(cbuf, 0, count); } while (true); final MessageContext msgCtx = new SecretMessageContext() { @Override public Map<String, ICryptoContext> getCryptoContexts() { return Collections.emptyMap(); } @Override public String getRemoteEntityIdentity() { return null; } @Override public boolean isRequestingTokens() { return false; } @Override public String getUserId() { return null; } @Override public UserAuthenticationData getUserAuthData(final ReauthCode reauthCode, final boolean renewable, final boolean required) { return null; } @Override public MslUser getUser() { return null; } @Override public Set<KeyRequestData> getKeyRequestData() throws MslKeyExchangeException { return Collections.emptySet(); } @Override public void updateServiceTokens(final MessageServiceTokenBuilder builder, final boolean handshake) { } @Override public void write(final MessageOutputStream output) throws IOException { output.write(data.toByteArray()); output.close(); } @Override public MessageDebugContext getDebugContext() { return null; } }; return Arrays.asList(msgCtx); } }
2,102
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/LogServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.msg.MessageHeader; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.server.common.ReceiveServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; /** * @author Wesley Miaw <[email protected]> */ public class LogServlet extends ReceiveServlet { private static final long serialVersionUID = 1030383316461016611L; /** Report the log message query string. */ public static final String REPORT = "report"; /** Most recently received log message. */ private static String message = ""; /** * <p>Create a new log servlet that will log any received application data * to stdout.</p> * * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public LogServlet() throws Exception { super(EntityAuthenticationScheme.RSA, TokenFactoryType.ACCEPT_NON_REPLAYABLE_ID, 0, null, null, null, null, null, false, false); } /* (non-Javadoc) * @see com.netflix.msl.server.common.BaseServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String query = request.getQueryString(); if (REPORT.equals(query)) { response.setContentType("text/plain"); final Writer out = response.getWriter(); out.write(message); out.close(); } else { super.doGet(request, response); } } @Override protected void receive(final MessageInputStream mis) { // Ignore error messages. final MessageHeader header = mis.getMessageHeader(); if (header == null) return; try { // Log the application data. final InputStreamReader reader = new InputStreamReader(mis); final StringBuffer sb = new StringBuffer(); final char[] buffer = new char[1 << 16]; while (true) { final int count = reader.read(buffer); if (count == -1) break; sb.append(buffer, 0, count); } message = sb.toString(); System.out.println("LOG: [" + message + "]"); } catch (final IOException e) { if (debug) e.printStackTrace(System.out); } finally { if (mis != null) try { mis.close(); } catch (final IOException e) {} } } }
2,103
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/EchoServlet.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.server.common.RespondServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; /** * User: skommidi * Date: 7/24/14 */ public class EchoServlet extends RespondServlet { private static final long serialVersionUID = 3781170196441547122L; private static final long SEQUENCE_NUMBER = 8L; private static final int NUM_THREADS = 0; public EchoServlet() throws Exception { super(NUM_THREADS, EntityAuthenticationScheme.NONE, TokenFactoryType.NOT_ACCEPT_NON_REPLAYABLE_ID, SEQUENCE_NUMBER, false, false, null, null, null, false, false); System.out.println("======================>> Echo Servlet Initialization Ended <<======================"); } @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final PrintWriter out = response.getWriter(); //Doing raw output of request out.println("<<<<Start>>>>\n" + getBody(request) + "\n<<<<End>>>>"); out.close(); } }
2,104
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/servlet/TestServlet.java
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.servlet; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.server.common.RespondServlet; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; /** * User: skommidi * Date: 7/21/14 */ public class TestServlet extends RespondServlet { private static final long serialVersionUID = 3747351784182184977L; private static final long SEQUENCE_NUMBER = 8L; private static final int NUM_THREADS = 0; public TestServlet() throws Exception { super(NUM_THREADS, EntityAuthenticationScheme.NONE, TokenFactoryType.NOT_ACCEPT_NON_REPLAYABLE_ID, SEQUENCE_NUMBER, false, false, null, null, null, false, false); System.out.println("======================>> Test Servlet Initialization Ended <<======================"); } }
2,105
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/common/PushServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.common; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.MslControl.MslChannel; import com.netflix.msl.msg.ServerReceiveMessageContext; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * <p>A servlet that first receives MSL message via POST, but then sends a push * response instead of a normal response.</p> * * @author Wesley Miaw <[email protected]> */ public abstract class PushServlet extends BaseServlet { private static final long serialVersionUID = 8620410155638929311L; /** * @param entityAuthScheme server entity authentication scheme. * @param type server token factory type. * @param seqno initial master token sequence number. * @param unsupportedEntityAuthSchemes unsupported entity authentication * schemes. May be {@code null}. * @param unsupportedUserAuthSchemes unsupported user authentication * schemes. May be {@code null}. * @param unsupportedKeyxSchemes unsupported key exchange schemes. May be * {@code null}. * @param cryptoContexts service token crypto contexts. * @param dbgCtx optional message debug context. May be {@code null}. * @param nullCryptoContext true if the server MSL crypto context should * not perform encryption or integrity protection. * @param console true message data should be written out to the console. * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public PushServlet(final EntityAuthenticationScheme entityAuthScheme, final TokenFactoryType type, final long seqno, final List<EntityAuthenticationScheme> unsupportedEntityAuthSchemes, final List<UserAuthenticationScheme> unsupportedUserAuthSchemes, final List<KeyExchangeScheme> unsupportedKeyxSchemes, final Map<String,ICryptoContext> cryptoContexts, final MessageDebugContext dbgCtx, final boolean nullCryptoContext, final boolean console) throws Exception { super(0, entityAuthScheme, type, seqno, unsupportedEntityAuthSchemes, unsupportedUserAuthSchemes, unsupportedKeyxSchemes, nullCryptoContext, console); recvMsgCtx = new ServerReceiveMessageContext(cryptoContexts, dbgCtx); } /* (non-Javadoc) * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final InputStream in = req.getInputStream(); final OutputStream out = resp.getOutputStream(); // Receive the message. final Future<MessageInputStream> futureRecv = mslCtrl.receive(mslCtx, recvMsgCtx, in, out, TIMEOUT); final MessageInputStream mis; try { mis = futureRecv.get(); } catch (final ExecutionException | InterruptedException | CancellationException e) { if (debug) e.printStackTrace(System.out); return; } // If the message input stream is null, clean up and return. if (mis == null) { try { in.close(); } catch (final IOException e) {} try { out.close(); } catch (final IOException e) {} return; } // Deliver the message input stream for processing. final List<MessageContext> pushMsgCtxs; try { pushMsgCtxs = process(mis); } catch (final Throwable t) { try { in.close(); } catch (final IOException e) {} try { out.close(); } catch (final IOException e) {} return; } // Push responses. for (final MessageContext pushMsgCtx : pushMsgCtxs) { final Future<MslChannel> futurePush = mslCtrl.push(mslCtx, pushMsgCtx, in, out, mis, TIMEOUT); try { futurePush.get(); } catch (final ExecutionException | InterruptedException | CancellationException e) { if (debug) e.printStackTrace(System.out); return; } } // Clean up. try { in.close(); } catch (final IOException e) {} try { out.close(); } catch (final IOException e) {} } /** * Called when a message input stream is received for further processing. * * @param mis the message input stream. * @return the message contexts used to push replies. */ protected abstract List<MessageContext> process(final MessageInputStream mis) throws Throwable; /** Receive message context. */ protected MessageContext recvMsgCtx; }
2,106
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/common/RespondServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.common; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.server.configuration.msg.ServerMessageContext; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * <p>A servlet that accepts POST requests in order to send a response.</p> * * @author Wesley Miaw <[email protected]> */ public class RespondServlet extends BaseServlet { private static final long serialVersionUID = -167726318549015539L; protected static final String payload = "Hello"; protected static final String error = "Error"; /** * @param numThreads * @param entityAuthScheme * @param tokenFactoryType * @param initialSequenceNum * @param isMessageEncrypted * @param isIntegrityProtected * @param unSupportedEntityAuthFactories * @param unSupportedUserAuthFactories * @param unSupportedKeyxFactories * @param isNullCryptoContext * @param setConsoleFilterStreamFactory * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws MslCryptoException if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws Exception if there is an error configuring the servlet. */ public RespondServlet(final int numThreads, final EntityAuthenticationScheme entityAuthScheme, final TokenFactoryType tokenFactoryType, final long initialSequenceNum, final boolean isMessageEncrypted, final boolean isIntegrityProtected, final List<EntityAuthenticationScheme> unSupportedEntityAuthFactories, final List<UserAuthenticationScheme> unSupportedUserAuthFactories, final List<KeyExchangeScheme> unSupportedKeyxFactories, final boolean isNullCryptoContext, final boolean setConsoleFilterStreamFactory) throws Exception { super(numThreads, entityAuthScheme, tokenFactoryType, initialSequenceNum, unSupportedEntityAuthFactories, unSupportedUserAuthFactories, unSupportedKeyxFactories, isNullCryptoContext, setConsoleFilterStreamFactory); this.encrypted = isMessageEncrypted; this.integrityProtected = isIntegrityProtected; } /** * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws MslCryptoException if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws Exception if there is an error configuring the servlet. */ @Override protected void configure() throws Exception { super.configure(); /** * Message Context Configuration */ msgCtx = new ServerMessageContext(mslCtx, payload.getBytes(MslConstants.DEFAULT_CHARSET), encrypted); msgCtx.setIntegrityProtected(integrityProtected); } @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final InputStream inStream = request.getInputStream(); final OutputStream outStream = response.getOutputStream(); InputStream mslInputStream = null; final byte[] buffer = new byte[5]; try { final Future<MessageInputStream> msgInputStream = mslCtrl.receive(mslCtx, msgCtx, inStream, outStream, TIMEOUT); mslInputStream = msgInputStream.get(); if (mslInputStream == null) return; do { final int bytesRead = mslInputStream.read(buffer); if (bytesRead == -1) break; } while (true); //Checking the the received payload is the same as the one the client sent if (!Arrays.equals(payload.getBytes(MslConstants.DEFAULT_CHARSET), buffer)) { msgCtx.setBuffer(error.getBytes(MslConstants.DEFAULT_CHARSET)); mslCtrl.respond(mslCtx, msgCtx, inStream, outStream, msgInputStream.get(), TIMEOUT); throw new IllegalStateException("PayloadBytes is not as expected: " + Arrays.toString(buffer)); } msgCtx.setBuffer(buffer); mslCtrl.respond(mslCtx, msgCtx, inStream, outStream, msgInputStream.get(), TIMEOUT); } catch (final Exception ex) { if (debug) ex.printStackTrace(System.out); } finally { if (mslInputStream != null) { mslInputStream.close(); } } } @Override protected void setPrivateVariable(final PrintWriter out, final String key, final String[] values) throws Exception { if (key.equals("encrypted")) { this.encrypted = Boolean.parseBoolean(values[0]); out.println(key + ": " + values[0]); } else if (key.equals("intProtected")) { this.integrityProtected = Boolean.parseBoolean(values[0]); out.println(key + ": " + values[0]); } else { super.setPrivateVariable(out, key, values); } } /** Message context. */ protected ServerMessageContext msgCtx; /** Application data encrypted. */ protected boolean encrypted; /** Application data integrity protected. */ protected boolean integrityProtected; }
2,107
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/common/ReceiveServlet.java
/** * Copyright (c) 2017 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.common; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.MslKeyExchangeException; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.MessageContext; import com.netflix.msl.msg.MessageDebugContext; import com.netflix.msl.msg.MessageInputStream; import com.netflix.msl.msg.ServerReceiveMessageContext; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * <p>A servlet that accepts POST requests but does not send a response.</p> * * @author Wesley Miaw <[email protected]> */ public abstract class ReceiveServlet extends BaseServlet { private static final long serialVersionUID = 849604555205123832L; /** * @param entityAuthScheme server entity authentication scheme. * @param type server token factory type. * @param seqno initial master token sequence number. * @param unsupportedEntityAuthSchemes unsupported entity authentication * schemes. May be {@code null}. * @param unsupportedUserAuthSchemes unsupported user authentication * schemes. May be {@code null}. * @param unsupportedKeyxSchemes unsupported key exchange schemes. May be * {@code null}. * @param cryptoContexts service token crypto contexts. * @param dbgCtx optional message debug context. May be {@code null}. * @param nullCryptoContext true if the server MSL crypto context should * not perform encryption or integrity protection. * @param console true message data should be written out to the console. * @throws MslCryptoException if there is an error signing or creating the * entity authentication data or an error creating a key * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws MslKeyExchangeException if there is an error accessing Diffie- * Hellman parameters. * @throws NoSuchAlgorithmException if a key generation algorithm is not * found. * @throws InvalidAlgorithmParameterException if key generation parameters * are invalid. */ public ReceiveServlet(final EntityAuthenticationScheme entityAuthScheme, final TokenFactoryType type, final long seqno, final List<EntityAuthenticationScheme> unsupportedEntityAuthSchemes, final List<UserAuthenticationScheme> unsupportedUserAuthSchemes, final List<KeyExchangeScheme> unsupportedKeyxSchemes, final Map<String,ICryptoContext> cryptoContexts, final MessageDebugContext dbgCtx, final boolean nullCryptoContext, final boolean console) throws Exception { super(0, entityAuthScheme, type, seqno, unsupportedEntityAuthSchemes, unsupportedUserAuthSchemes, unsupportedKeyxSchemes, nullCryptoContext, console); msgCtx = new ServerReceiveMessageContext(cryptoContexts, dbgCtx); } /* (non-Javadoc) * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final InputStream in = req.getInputStream(); final OutputStream out = resp.getOutputStream(); // Receive the message. final Future<MessageInputStream> future = mslCtrl.receive(mslCtx, msgCtx, in, out, TIMEOUT); final MessageInputStream mis; try { mis = future.get(); } catch (final ExecutionException | InterruptedException | CancellationException e) { if (debug) e.printStackTrace(System.out); return; } // If the message input stream is null, clean up and return. if (mis == null) { try { in.close(); } catch (final IOException e) {} try { out.close(); } catch (final IOException e) {} return; } // Deliver the message input stream for processing. receive(mis); // Clean up. try { in.close(); } catch (final IOException e) {} try { out.close(); } catch (final IOException e) {} } /** * Called when a message input stream is received for further processing. * * @param mis the message input stream. */ protected abstract void receive(final MessageInputStream mis); /** Message context. */ protected MessageContext msgCtx; }
2,108
0
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server
Create_ds/msl/integ-tests/src/main/java/com/netflix/msl/server/common/BaseServlet.java
/** * Copyright (c) 2014-2018 Netflix, Inc. All rights reserved. * * Licensed 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 com.netflix.msl.server.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.netflix.msl.MslConstants; import com.netflix.msl.MslCryptoException; import com.netflix.msl.MslEncodingException; import com.netflix.msl.entityauth.EntityAuthenticationScheme; import com.netflix.msl.keyx.KeyExchangeScheme; import com.netflix.msl.msg.ConsoleFilterStreamFactory; import com.netflix.msl.msg.MslControl; import com.netflix.msl.server.configuration.msg.ServerMessageContext; import com.netflix.msl.server.configuration.tokens.TokenFactoryType; import com.netflix.msl.server.configuration.util.ServerMslContext; import com.netflix.msl.userauth.UserAuthenticationScheme; /** * User: skommidi * Date: 7/21/14 */ public class BaseServlet extends HttpServlet { private static final long serialVersionUID = -325218339823577479L; protected static final boolean debug = false; protected static final int TIMEOUT = 25000; private boolean isNullCryptoContext; private boolean setConsoleFilterStreamFactory; private EntityAuthenticationScheme entityAuthScheme; private int numThreads; private TokenFactoryType tokenFactoryType; private long initialSequenceNum; private final List<EntityAuthenticationScheme> unSupportedEntityAuthFactories; private final List<UserAuthenticationScheme> unSupportedUserAuthFactories; private final List<KeyExchangeScheme> unSupportedKeyxFactories; protected ServerMslContext mslCtx; protected ServerMessageContext msgCtx; protected MslControl mslCtrl; /** * @param numThreads * @param entityAuthScheme * @param tokenFactoryType * @param initialSequenceNum * @param unSupportedEntityAuthFactories * @param unSupportedUserAuthFactories * @param unSupportedKeyxFactories * @param isNullCryptoContext * @param setConsoleFilterStreamFactory * @throws MslCryptoException if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws Exception if there is an error configuring the servlet. */ public BaseServlet(final int numThreads, final EntityAuthenticationScheme entityAuthScheme, final TokenFactoryType tokenFactoryType, final long initialSequenceNum, final List<EntityAuthenticationScheme> unSupportedEntityAuthFactories, final List<UserAuthenticationScheme> unSupportedUserAuthFactories, final List<KeyExchangeScheme> unSupportedKeyxFactories, final boolean isNullCryptoContext, final boolean setConsoleFilterStreamFactory) throws Exception { this.numThreads = numThreads; this.entityAuthScheme = entityAuthScheme; this.tokenFactoryType = tokenFactoryType; this.initialSequenceNum = initialSequenceNum; this.unSupportedEntityAuthFactories = unSupportedEntityAuthFactories; this.unSupportedUserAuthFactories = unSupportedUserAuthFactories; this.unSupportedKeyxFactories = unSupportedKeyxFactories; this.isNullCryptoContext = isNullCryptoContext; this.setConsoleFilterStreamFactory = setConsoleFilterStreamFactory; configure(); } /** * @throws MslCryptoException if there is an error signing or creating the * entity authentication data. * @throws MslEncodingException if there is an error creating the entity * authentication data. * @throws Exception if there is an error configuring the servlet. */ protected void configure() throws Exception { /** MSL control configuration. */ mslCtrl = new MslControl(numThreads, null, null); if(setConsoleFilterStreamFactory) { mslCtrl.setFilterFactory(new ConsoleFilterStreamFactory()); } /** MSL context configuration. */ mslCtx = new ServerMslContext(entityAuthScheme, false, tokenFactoryType, initialSequenceNum, unSupportedEntityAuthFactories, unSupportedUserAuthFactories, unSupportedKeyxFactories, isNullCryptoContext); } @Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); super.service(request, response); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); final PrintWriter out = response.getWriter(); @SuppressWarnings("unchecked") final Map<String, String[]> params = request.getParameterMap(); for (final Entry<String,String[]> entry : params.entrySet()) { try { final String key = entry.getKey(); final String[] value = entry.getValue(); setPrivateVariable(out, key, value); } catch (final Exception e) { if (debug) e.printStackTrace(); out.println(e.getMessage()); } } try { configure(); } catch (final Exception e) { if (debug) e.printStackTrace(); out.println(e.getMessage()); } out.println(request.getServletPath()); out.close(); } protected void setPrivateVariable(final PrintWriter out, final String key, final String[] values) throws Exception { if (key.equals("numthreads")) { this.numThreads = Integer.parseInt(values[0]); out.println(key + ": " + values[0]); } else if (key.equals("entityauthscheme")) { this.entityAuthScheme = EntityAuthenticationScheme.getScheme(values[0]); out.println(key + ": " + values[0]); } else if (key.equals("tokenfactorytype")) { this.tokenFactoryType = TokenFactoryType.valueOf(values[0]); out.println(key + ": " + values[0]); } else if (key.equals("initialseqnum")) { this.initialSequenceNum = Long.parseLong(values[0]); out.println(key + ": " + values[0]); } else if(key.equals("consoleFilterStreamFactory")) { this.setConsoleFilterStreamFactory = Boolean.parseBoolean(values[0]); out.println(key + ": " + values[0]); } else if(key.equals("nullCryptoContext")) { this.isNullCryptoContext = Boolean.parseBoolean(values[0]); out.println(key + ":" + values[0]); } else if (key.equals("unsupentityauthfact")) { this.unSupportedEntityAuthFactories.clear(); for (final String entityAuth : values) { this.unSupportedEntityAuthFactories.add(EntityAuthenticationScheme.getScheme(entityAuth)); out.println(key + ": " + entityAuth); } } else if (key.equals("unsupuserauthfact")) { this.unSupportedUserAuthFactories.clear(); for (final String userAuth : values) { this.unSupportedUserAuthFactories.add(UserAuthenticationScheme.getScheme(userAuth)); out.println(key + ": " + userAuth); } } else if (key.equals("unsupkeyexfact")) { this.unSupportedKeyxFactories.clear(); for (final String keyEx : values) { this.unSupportedKeyxFactories.add(KeyExchangeScheme.getScheme(keyEx)); out.println(key + ": " + keyEx); } } else { throw new Exception("Invalid parameter: " + key); } } protected String getBody(final HttpServletRequest request) throws IOException { String body = null; final StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { final InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream, MslConstants.DEFAULT_CHARSET)); bufferedReader.mark(100000); final char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } bufferedReader.reset(); } else { stringBuilder.append(""); } } catch (final IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (final IOException ex) { throw ex; } } } body = stringBuilder.toString(); return body; } }
2,109
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/dtos/JobStatusTest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; /** * Tests for {@link JobStatus}. * * @author tgianos * @since 4.0.0 */ class JobStatusTest { @Test void testIsActive() { Assertions.assertThat(JobStatus.RUNNING.isActive()).isTrue(); Assertions.assertThat(JobStatus.INIT.isActive()).isTrue(); Assertions.assertThat(JobStatus.FAILED.isActive()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isActive()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isActive()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isActive()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isActive()).isTrue(); Assertions.assertThat(JobStatus.RESOLVED.isActive()).isTrue(); Assertions.assertThat(JobStatus.CLAIMED.isActive()).isTrue(); Assertions.assertThat(JobStatus.ACCEPTED.isActive()).isTrue(); } @Test void testIsFinished() { Assertions.assertThat(JobStatus.RUNNING.isFinished()).isFalse(); Assertions.assertThat(JobStatus.INIT.isFinished()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.INVALID.isFinished()).isTrue(); Assertions.assertThat(JobStatus.KILLED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.SUCCEEDED.isFinished()).isTrue(); Assertions.assertThat(JobStatus.RESERVED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.RESOLVED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.CLAIMED.isFinished()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isFinished()).isFalse(); } @Test void testIsResolvable() { Assertions.assertThat(JobStatus.RUNNING.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.INIT.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isResolvable()).isTrue(); Assertions.assertThat(JobStatus.RESOLVED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.CLAIMED.isResolvable()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isResolvable()).isFalse(); } @Test void testIsClaimable() { Assertions.assertThat(JobStatus.RUNNING.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.INIT.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.FAILED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.INVALID.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.KILLED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.SUCCEEDED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.RESERVED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.RESOLVED.isClaimable()).isTrue(); Assertions.assertThat(JobStatus.CLAIMED.isClaimable()).isFalse(); Assertions.assertThat(JobStatus.ACCEPTED.isClaimable()).isTrue(); } @Test void testGetActivesStatuses() { Assertions .assertThat(JobStatus.getActiveStatuses()) .containsExactlyInAnyOrder( JobStatus.INIT, JobStatus.RUNNING, JobStatus.RESERVED, JobStatus.RESOLVED, JobStatus.CLAIMED, JobStatus.ACCEPTED ); } @Test void testGetFinishedStatuses() { Assertions .assertThat(JobStatus.getFinishedStatuses()) .containsExactlyInAnyOrder(JobStatus.INVALID, JobStatus.FAILED, JobStatus.KILLED, JobStatus.SUCCEEDED); } @Test void testGetResolvableStatuses() { Assertions.assertThat(JobStatus.getResolvableStatuses()).containsExactlyInAnyOrder(JobStatus.RESERVED); } @Test void testGetClaimableStatuses() { Assertions .assertThat(JobStatus.getClaimableStatuses()) .containsExactlyInAnyOrder(JobStatus.RESOLVED, JobStatus.ACCEPTED); } @Test void testGetStatusesBeforeClaimed() { Assertions .assertThat(JobStatus.getStatusesBeforeClaimed()) .containsExactlyInAnyOrder(JobStatus.ACCEPTED, JobStatus.RESERVED, JobStatus.RESOLVED); } }
2,110
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/dtos/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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. * */ /** * Tests for this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.dtos; import javax.annotation.ParametersAreNonnullByDefault;
2,111
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/configs/AwsAutoConfigurationTest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.configs; import com.amazonaws.regions.AwsRegionProvider; import com.netflix.genie.common.internal.aws.s3.S3ClientFactory; import com.netflix.genie.common.internal.aws.s3.S3ProtocolResolver; import com.netflix.genie.common.internal.aws.s3.S3ProtocolResolverRegistrar; import com.netflix.genie.common.internal.services.JobArchiver; import com.netflix.genie.common.internal.services.impl.S3JobArchiverImpl; import io.awspring.cloud.autoconfigure.context.ContextCredentialsAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextRegionProviderAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextResourceLoaderAutoConfiguration; import io.awspring.cloud.autoconfigure.context.properties.AwsS3ResourceLoaderProperties; import io.awspring.cloud.context.support.io.SimpleStorageProtocolResolverConfigurer; import io.awspring.cloud.core.io.s3.SimpleStorageProtocolResolver; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.io.ProtocolResolver; import java.util.Collection; /** * Tests for behavior of {@link AwsAutoConfiguration}. * * @author tgianos * @since 4.0.0 */ class AwsAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( ContextCredentialsAutoConfiguration.class, ContextRegionProviderAutoConfiguration.class, ContextResourceLoaderAutoConfiguration.class, AwsAutoConfiguration.class ) ) .withPropertyValues( "cloud.aws.credentials.useDefaultAwsCredentialsChain=true", "cloud.aws.region.auto=false", "cloud.aws.region.static=us-east-1", "cloud.aws.stack.auto=false", "spring.jmx.enabled=false", "spring.main.webApplicationType=none" ); /** * Test expected context. */ @Test void testExpectedContext() { this.contextRunner.run( (context) -> { Assertions.assertThat(context).hasSingleBean(AwsRegionProvider.class); Assertions.assertThat(context).hasSingleBean(S3ClientFactory.class); Assertions.assertThat(context).hasSingleBean(AwsS3ResourceLoaderProperties.class); Assertions.assertThat(context).hasSingleBean(S3ProtocolResolver.class); Assertions.assertThat(context).hasSingleBean(S3ProtocolResolverRegistrar.class); Assertions.assertThat(context).hasSingleBean(S3JobArchiverImpl.class); Assertions.assertThat(context).hasSingleBean(JobArchiver.class); // Verify that Spring Cloud AWS still would try to register their S3 protocol resolver Assertions.assertThat(context).hasSingleBean(SimpleStorageProtocolResolverConfigurer.class); // And Make sure we ripped out the one from Spring Cloud AWS and put ours in instead if (context instanceof AbstractApplicationContext) { final AbstractApplicationContext aac = (AbstractApplicationContext) context; final Collection<ProtocolResolver> protocolResolvers = aac.getProtocolResolvers(); Assertions.assertThat(protocolResolvers).contains(context.getBean(S3ProtocolResolver.class)); Assertions .assertThat(protocolResolvers) .doesNotHaveAnyElementsOfTypes(SimpleStorageProtocolResolver.class); } } ); } }
2,112
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/configs/ProtoConvertersAutoConfigurationIntegrationTest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.configs; import com.netflix.genie.common.internal.dtos.converters.JobDirectoryManifestProtoConverter; import com.netflix.genie.common.internal.dtos.converters.JobServiceProtoConverter; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; /** * Tests for behavior of {@link ProtoConvertersAutoConfiguration}. * * @author mprimi * @since 4.0.0 */ class ProtoConvertersAutoConfigurationIntegrationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( ProtoConvertersAutoConfiguration.class ) ); /** * Test expected context. */ @Test void testExpectedContext() { this.contextRunner.run( (context) -> { Assertions.assertThat(context).hasSingleBean(JobServiceProtoConverter.class); Assertions.assertThat(context).hasSingleBean(JobDirectoryManifestProtoConverter.class); } ); } }
2,113
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/configs/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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. * */ /** * Tests for configs found in this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.configs; import javax.annotation.ParametersAreNonnullByDefault;
2,114
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/configs/CommonServicesAutoConfigurationTest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.configs; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.services.JobArchiveService; import com.netflix.genie.common.internal.services.JobArchiver; import com.netflix.genie.common.internal.services.JobDirectoryManifestCreatorService; import com.netflix.genie.common.internal.services.impl.FileSystemJobArchiverImpl; import com.netflix.genie.common.internal.services.impl.S3JobArchiverImpl; import com.netflix.genie.common.internal.util.PropertiesMapCache; import io.awspring.cloud.autoconfigure.context.ContextCredentialsAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextRegionProviderAutoConfiguration; import io.awspring.cloud.autoconfigure.context.ContextResourceLoaderAutoConfiguration; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; /** * Tests for behavior of {@link CommonServicesAutoConfiguration}. * * @author tgianos * @since 4.0.0 */ class CommonServicesAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( CommonServicesAutoConfiguration.class ) ) .withPropertyValues( "spring.jmx.enabled=false", "spring.main.webApplicationType=none" ); /** * Test expected context. */ @Test void testExpectedContext() { this.contextRunner.run( (context) -> { Assertions.assertThat(context).hasSingleBean(FileSystemJobArchiverImpl.class); Assertions.assertThat(context).hasSingleBean(JobArchiver.class); Assertions.assertThat(context).hasSingleBean(JobArchiveService.class); Assertions.assertThat(context).hasSingleBean(PropertiesMapCache.Factory.class); } ); } /** * Make sure when AWS configuration is involved it gives the right configuration. */ @Test void testExpectedContextWithAws() { this.contextRunner .withPropertyValues( "cloud.aws.credentials.useDefaultAwsCredentialsChain=true", "cloud.aws.region.auto=false", "cloud.aws.region.static=us-east-1", "cloud.aws.stack.auto=false" ) .withConfiguration( AutoConfigurations.of( ContextCredentialsAutoConfiguration.class, ContextRegionProviderAutoConfiguration.class, ContextResourceLoaderAutoConfiguration.class, AwsAutoConfiguration.class ) ) .run( (context) -> { Assertions.assertThat(context).hasSingleBean(FileSystemJobArchiverImpl.class); Assertions.assertThat(context).hasSingleBean(S3JobArchiverImpl.class); Assertions.assertThat(context).hasSingleBean(JobArchiveService.class); Assertions.assertThat(context).hasSingleBean(PropertiesMapCache.Factory.class); // TODO: Find a way to test the order Assertions .assertThat(context) .getBeans(JobArchiver.class) .size() .isEqualTo(2); } ); } /** * Make JobDirectoryManifestService beans is configured as expected. */ @Test void testJobDirectoryManifestService() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(JobDirectoryManifestCreatorService.class) ); } /** * Make JobDirectoryManifest cache bean is configured as expected. */ @Test void testJobDirectoryManifestCache() { this.contextRunner.run( context -> Assertions.assertThat(context).getBean("jobDirectoryManifestCache").isNotNull() ); } /** * Make sure DirectoryManifest.Factory bean is configured as expected. */ @Test void testDirectoryManifestFactory() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Factory.class) ); } /** * Make JobDirectoryManifestService beans are configured as expected. */ @Test void testDirectoryManifestFilter() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Filter.class) ); } }
2,115
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/spring
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/spring/autoconfigure/CommonTracingAutoConfigurationTest.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.spring.autoconfigure; import brave.Tracer; import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter; import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTracingCleanup; import com.netflix.genie.common.internal.tracing.brave.BraveTracingComponents; import com.netflix.genie.common.internal.tracing.brave.impl.DefaultBraveTagAdapterImpl; import com.netflix.genie.common.internal.tracing.brave.impl.EnvVarBraveTracePropagatorImpl; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; /** * Tests for {@link CommonTracingAutoConfiguration}. * * @author tgianos * @since 4.0.0 */ class CommonTracingAutoConfigurationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of( CommonTracingAutoConfiguration.class ) ) .withUserConfiguration(ExternalBeans.class); @Test void expectedBeansExist() { this.contextRunner.run( context -> Assertions .assertThat(context) .hasSingleBean(BraveTracePropagator.class) .hasSingleBean(EnvVarBraveTracePropagatorImpl.class) .hasSingleBean(BraveTracingCleanup.class) .hasSingleBean(BraveTracingComponents.class) .hasSingleBean(BraveTagAdapter.class) .hasSingleBean(DefaultBraveTagAdapterImpl.class) ); } private static class ExternalBeans { @Bean Tracer tracer() { return Mockito.mock(Tracer.class); } } }
2,116
0
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/spring
Create_ds/genie/genie-common-internal/src/test/java/com/netflix/genie/common/internal/spring/autoconfigure/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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. * */ /** * Tests for this package. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.spring.autoconfigure; import javax.annotation.ParametersAreNonnullByDefault;
2,117
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/TagAdapter.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing; /** * An interface for implementations to adapt any tags published by default OSS components for internal conventions. * * @param <U> The type of object which tags should be applied to specific to the implementation * @param <K> The key type for the tags * @param <V> The value type for the tags * @author tgianos * @since 4.0.0 */ public interface TagAdapter<U, K, V> { /** * The method that should be implemented in order to provide tagging. Genie OSS components should call this method * instead of directly tagging. * * @param taggable The instance which tags should be applied to * @param key The original key for the tag * @param value The original value for the tag */ void tag(U taggable, K key, V value); }
2,118
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/TracePropagator.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing; import java.util.Map; import java.util.Optional; /** * This interface exists to provide a shared contract for how trace information is shared between the Genie * server job request handling and the agent process launch. Implementations should be shared across server and agent * versions for compatibility. * <p> * Note: This somewhat copies a pattern from <a href="https://github.com/openzipkin/brave">Brave</a> however it is * purposely decoupled so as to allow other implementations if necessary. * * @param <C> The trace context type that should be used for injection and returned from extraction * @author tgianos * @since 4.0.0 */ public interface TracePropagator<C> { /** * Extract the trace context from the supplied set of key value pairs. * <p> * Implementations should swallow all exceptions as tracing is not critical to the completion of a job on behalf * of the user. * * @param environment Generally this will be the result of {@link System#getenv()} * @return A new instance of {@link C} containing the extracted context or {@link Optional#empty()} if no context * information was found */ Optional<C> extract(Map<String, String> environment); /** * Inject the trace context from {@literal U} into the returned set of key value pairs for propagation to Agent. * <p> * Implementations should swallow all exceptions as tracing is not critical to the completion of a job on behalf * of the user. * * @param traceContext The context for the active unit of work (span in Brave parlance) * @return A set of key value pairs that should be propagated to the agent in some manner to be extracted in * {@link #extract(Map)} */ Map<String, String> injectForAgent(C traceContext); /** * Inject the trace context from {@literal U} into the returned set of key value pairs for propagation to job. * <p> * Implementations should swallow all exceptions as tracing is not critical to the completion of a job on behalf * of the user. * * @param traceContext The context for the active unit of work (span in Brave parlance) * @return A set of key value pairs that should be propagated to the job in some manner which can be extracted * by downstream systems if they so desire */ Map<String, String> injectForJob(C traceContext); }
2,119
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/TracingConstants.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing; /** * Constants used for adding metadata to tracing spans. * * @author tgianos * @since 4.0.0 */ public final class TracingConstants { /** * The root of all tags related to Genie on spans. */ public static final String GLOBAL_TAG_BASE = "genie"; /** * The root for all tags related to spans occurring in the Genie agent. */ public static final String AGENT_TAG_BASE = GLOBAL_TAG_BASE + ".agent"; /** * The command that was entered on the CLI for the agent to execute. */ public static final String AGENT_CLI_COMMAND_NAME_TAG = AGENT_TAG_BASE + "cli.command.name"; /** * The root for all tags related to spans occurring in the Genie server. */ public static final String SERVER_TAG_BASE = GLOBAL_TAG_BASE + ".server"; /** * The root of all tags related to spans operating on a genie job. */ public static final String JOB_TAG_BASE = GLOBAL_TAG_BASE + ".job"; /** * The tag for the unique job id. */ public static final String JOB_ID_TAG = JOB_TAG_BASE + ".id"; /** * The tag to represent that this span contains a new job submission. */ public static final String NEW_JOB_TAG = JOB_TAG_BASE + ".new"; /** * The tag for the job name. */ public static final String JOB_NAME_TAG = JOB_TAG_BASE + ".name"; /** * The tag for the job user. */ public static final String JOB_USER_TAG = JOB_TAG_BASE + ".user"; /** * The tag for the job command id. */ public static final String JOB_CLUSTER_ID_TAG = JOB_TAG_BASE + ".cluster.id"; /** * The tag for the job command id. */ public static final String JOB_CLUSTER_NAME_TAG = JOB_TAG_BASE + ".cluster.name"; /** * The tag for the job command id. */ public static final String JOB_COMMAND_ID_TAG = JOB_TAG_BASE + ".command.id"; /** * The tag for the job command id. */ public static final String JOB_COMMAND_NAME_TAG = JOB_TAG_BASE + ".command.name"; /** * Convenience constant for representing a flag tag with a value of {@literal true}. */ public static final String TRUE_VALUE = "true"; private TracingConstants() { } }
2,120
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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. * */ /** * Components shared between the server and agent related to request tracing. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.tracing; import javax.annotation.ParametersAreNonnullByDefault;
2,121
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/BraveTagAdapter.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave; import brave.SpanCustomizer; import com.netflix.genie.common.internal.tracing.TagAdapter; /** * Extension of {@link TagAdapter} that specifies that tags should be key value pairs of Strings as they are in * Brave instrumentation. * * @author tgianos * @since 4.0.0 */ public interface BraveTagAdapter extends TagAdapter<SpanCustomizer, String, String> { }
2,122
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/BraveTracingComponents.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave; import brave.Tracer; import lombok.AllArgsConstructor; import lombok.Data; /** * Container DTO class for <a href="https://github.com/openzipkin/brave">Brave</a> based components for tracing in * Genie server and agent. * * @author tgianos * @since 4.0.0 */ @Data @AllArgsConstructor public class BraveTracingComponents { private final Tracer tracer; private final BraveTracePropagator tracePropagator; private final BraveTracingCleanup tracingCleaner; private final BraveTagAdapter tagAdapter; }
2,123
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/BraveTracePropagator.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave; import brave.propagation.TraceContext; import com.netflix.genie.common.internal.tracing.TracePropagator; /** * Extension of {@link TracePropagator} based on <a href="https://github.com/openzipkin/brave">Brave</a> and * <a href="https://github.com/openzipkin/b3-propagation">B3 Propagation</a>. * * @author tgianos * @since 4.0.0 */ public interface BraveTracePropagator extends TracePropagator<TraceContext> { }
2,124
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/BraveTracingCleanup.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave; import zipkin2.reporter.AsyncReporter; import java.util.Set; /** * Any cleanup needed at program shutdown for <a href="https://github.com/openzipkin/brave">Brave</a> instrumentation. * * @author tgianos * @since 4.0.0 */ public class BraveTracingCleanup { private final Set<AsyncReporter<?>> reporters; /** * Constructor. * * @param reporters Any {@link AsyncReporter} instance configured for the system */ public BraveTracingCleanup(final Set<AsyncReporter<?>> reporters) { this.reporters = reporters; } /** * Should be called at the end of the program to perform any necessary cleanup that native Brave components don't * already do. Example: flushing asynchronous reporters so that spans are more guaranteed to be reported than if * this wasn't explicitly called and a timeout happened. */ public void cleanup() { this.reporters.forEach(AsyncReporter::flush); } }
2,125
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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. * */ /** * Classes specific to tracing using <a href="https://github.com/openzipkin/brave">Brave</a>. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.tracing.brave; import javax.annotation.ParametersAreNonnullByDefault;
2,126
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/impl/EnvVarBraveTracePropagatorImpl.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave.impl; import brave.propagation.TraceContext; import com.netflix.genie.common.internal.tracing.TracePropagator; import com.netflix.genie.common.internal.tracing.brave.BraveTracePropagator; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Implementation of {@link TracePropagator} based on <a href="https://github.com/openzipkin/brave">Brave</a> and * <a href="https://github.com/openzipkin/b3-propagation">B3 Propagation</a>. This particular implementation leverages * environment variables to pass context between processes. * <p> * Note: This current implementation kind of breaks the contract as we don't propagate all the expected headers. * * @author tgianos * @since 4.0.0 */ public class EnvVarBraveTracePropagatorImpl implements BraveTracePropagator { /** * The key for the active trace id low set of bits. * * @see TraceContext.Builder#traceId(long) */ static final String GENIE_AGENT_B3_TRACE_ID_LOW_KEY = "GENIE_AGENT_B3_TRACE_ID_LOW"; /** * The key for the active trace id high set of bits. * * @see TraceContext.Builder#traceIdHigh(long) */ static final String GENIE_AGENT_B3_TRACE_ID_HIGH_KEY = "GENIE_AGENT_B3_TRACE_ID_HIGH"; /** * The key for the span id. * * @see TraceContext.Builder#spanId(long) */ static final String GENIE_AGENT_B3_SPAN_ID_KEY = "GENIE_AGENT_B3_SPAN_ID"; /** * The key for the parent span. * * @see TraceContext.Builder#parentId(long) */ static final String GENIE_AGENT_B3_PARENT_SPAN_ID_KEY = "GENIE_AGENT_B3_PARENT_SPAN_ID"; /** * The key for whether or not spans should be sampled. * * @see TraceContext.Builder#sampled(Boolean) */ static final String GENIE_AGENT_B3_SAMPLED_KEY = "GENIE_AGENT_B3_SAMPLED"; /** * The key for the active trace id low set of bits. * * @see TraceContext.Builder#traceId(long) */ static final String GENIE_JOB_B3_TRACE_ID_LOW_KEY = "GENIE_B3_TRACE_ID_LOW"; /** * The key for the active trace id high set of bits. * * @see TraceContext.Builder#traceIdHigh(long) */ static final String GENIE_JOB_B3_TRACE_ID_HIGH_KEY = "GENIE_B3_TRACE_ID_HIGH"; /** * The key for the span id. * * @see TraceContext.Builder#spanId(long) */ static final String GENIE_JOB_B3_SPAN_ID_KEY = "GENIE_B3_SPAN_ID"; /** * The key for the parent span of the job. * * @see TraceContext.Builder#parentId(long) */ static final String GENIE_JOB_B3_PARENT_SPAN_ID_KEY = "GENIE_B3_PARENT_SPAN_ID"; /** * The key for whether or not spans should be sampled. * * @see TraceContext.Builder#sampled(Boolean) */ static final String GENIE_JOB_B3_SAMPLED_KEY = "GENIE_B3_SAMPLED"; private static final Logger LOG = LoggerFactory.getLogger(EnvVarBraveTracePropagatorImpl.class); private static final long NO_TRACE_ID_HIGH = 0L; /** * {@inheritDoc} */ @Override public Optional<TraceContext> extract(final Map<String, String> environment) { /* * While use cases for Tracing are potentially important they are not as important as actually running the users * job. For this reason if an exception happens during Trace context creation it will be swallowed and the * system will have to move on either with a new trace completely or some other mechanism to be determined * upstream from this method. */ try { final String traceIdLow = environment.get(GENIE_AGENT_B3_TRACE_ID_LOW_KEY); if (StringUtils.isBlank(traceIdLow)) { LOG.debug("No trace id low found in the supplied set of key value pairs. Can't extract trace context"); return Optional.empty(); } final String spanId = environment.get(GENIE_AGENT_B3_SPAN_ID_KEY); if (StringUtils.isBlank(spanId)) { LOG.debug( "No span id found in the supplied set of key value pairs. Can't extract trace context" ); return Optional.empty(); } final TraceContext.Builder builder = TraceContext.newBuilder(); builder.traceId(Long.parseLong(traceIdLow)); builder.spanId(Long.parseLong(spanId)); final String traceIdHigh = environment.get(GENIE_AGENT_B3_TRACE_ID_HIGH_KEY); if (StringUtils.isNotBlank(traceIdHigh)) { builder.traceIdHigh(Long.parseLong(traceIdHigh)); } final String parentSpanId = environment.get(GENIE_AGENT_B3_PARENT_SPAN_ID_KEY); if (StringUtils.isNotBlank(parentSpanId)) { builder.parentId(Long.parseLong(parentSpanId)); } final String sampled = environment.get(GENIE_AGENT_B3_SAMPLED_KEY); if (StringUtils.isNotBlank(sampled)) { builder.sampled(Boolean.parseBoolean(sampled)); } LOG.debug( "Extracted trace context: " + "Trace Id Low = {}, " + "Trace Id High = {}, " + "Parent Span Id = {}, " + "New Span Id = {}, " + "Sampled = {}", traceIdLow, traceIdHigh, parentSpanId, spanId, sampled ); return Optional.of(builder.build()); } catch (final Throwable t) { LOG.warn( "Unable to extract trace context from supplied key value pairs due to exception: {}", t.getMessage(), t ); return Optional.empty(); } } /** * {@inheritDoc} */ @Override public Map<String, String> injectForAgent(final TraceContext traceContext) { return this.inject(traceContext, true); } /** * {@inheritDoc} */ @Override public Map<String, String> injectForJob(final TraceContext traceContext) { return this.inject(traceContext, false); } private Map<String, String> inject(final TraceContext traceContext, final boolean isForAgent) { try { final Map<String, String> propagationContext = new HashMap<>(); propagationContext.put( isForAgent ? GENIE_AGENT_B3_TRACE_ID_LOW_KEY : GENIE_JOB_B3_TRACE_ID_LOW_KEY, Long.toString(traceContext.traceId()) ); propagationContext.put( isForAgent ? GENIE_AGENT_B3_SPAN_ID_KEY : GENIE_JOB_B3_SPAN_ID_KEY, Long.toString(traceContext.spanId()) ); propagationContext.put( isForAgent ? GENIE_AGENT_B3_SAMPLED_KEY : GENIE_JOB_B3_SAMPLED_KEY, traceContext.sampled().toString() ); // only propagate high bits of trace id if they're non-zero final long traceIdHigh = traceContext.traceIdHigh(); if (traceIdHigh != NO_TRACE_ID_HIGH) { propagationContext.put( isForAgent ? GENIE_AGENT_B3_TRACE_ID_HIGH_KEY : GENIE_JOB_B3_TRACE_ID_HIGH_KEY, Long.toString(traceIdHigh) ); } final Long parentSpanId = traceContext.parentId(); if (parentSpanId != null) { propagationContext.put( isForAgent ? GENIE_AGENT_B3_PARENT_SPAN_ID_KEY : GENIE_JOB_B3_PARENT_SPAN_ID_KEY, Long.toString(parentSpanId) ); } return propagationContext; } catch (final Throwable t) { LOG.warn( "Unable to inject trace context for propagation to {} due to {}", isForAgent ? "agent" : "job", t.getMessage(), t ); // Since we don't know what has been injected and what hasn't for now just punt and return // empty so that downstream starts fresh return new HashMap<>(); } } }
2,127
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/impl/DefaultBraveTagAdapterImpl.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.tracing.brave.impl; import brave.SpanCustomizer; import com.netflix.genie.common.internal.tracing.brave.BraveTagAdapter; /** * Default implementation of {@link BraveTagAdapter} which is just a proxy for the actual call. * * @author tgianos * @since 4.0.0 */ public class DefaultBraveTagAdapterImpl implements BraveTagAdapter { /** * Directly proxy the call. * <p> * {@inheritDoc} */ @Override public void tag(final SpanCustomizer taggable, final String key, final String value) { taggable.tag(key, value); } }
2,128
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/tracing/brave/impl/package-info.java
/* * * Copyright 2021 Netflix, Inc. * * Licensed 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. * */ /** * Implementations of any interfaces found in {@link com.netflix.genie.common.internal.tracing.brave}. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.tracing.brave.impl; import javax.annotation.ParametersAreNonnullByDefault;
2,129
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/RegexRuleSet.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.google.common.collect.Lists; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; /** * Utility class to match a string against an ordered set of regexes and obtain an accept/reject response. * * @author mprimi * @since 4.0.0 */ public final class RegexRuleSet { private final Response defaultResponse; private final List<Rule> rules; private RegexRuleSet( final List<Rule> rules, final Response defaultResponse ) { this.rules = Lists.newArrayList(rules); this.defaultResponse = defaultResponse; } /** * Factory method to build a whitelist ruleset. * (Whitelist rejects everything except for the given patterns). * * @param patternStrings a set of pattern strings that constitute the whitelist * @return the ruleset */ public static RegexRuleSet buildWhitelist(final String... patternStrings) { return buildWhitelist(compilePatternStrings(patternStrings)); } /** * Factory method to build a whitelist ruleset. * (Whitelist rejects everything except for the given patterns). * * @param patterns a set of patterns that constitute the whitelist * @return the ruleset */ public static RegexRuleSet buildWhitelist(final Pattern... patterns) { final Builder builder = new Builder(Response.REJECT); for (final Pattern pattern : patterns) { builder.addRule(pattern, Response.ACCEPT); } return builder.build(); } /** * Factory method to build a whitelist ruleset. * (Blacklist accepts everything except for the given patterns). * * @param patternStrings a set of pattern strings that constitute the blacklist * @return the ruleset */ public static RegexRuleSet buildBlacklist(final String... patternStrings) { return buildBlacklist(compilePatternStrings(patternStrings)); } /** * Factory method to build a whitelist ruleset. * (Blacklist accepts everything except for the given patterns). * * @param patterns a set of patterns that constitute the blacklist * @return the ruleset */ public static RegexRuleSet buildBlacklist(final Pattern... patterns) { final Builder builder = new Builder(Response.ACCEPT); for (final Pattern pattern : patterns) { builder.addRule(pattern, Response.REJECT); } return builder.build(); } private static Pattern[] compilePatternStrings(final String[] patternStrings) { final Pattern[] patterns = new Pattern[patternStrings.length]; for (int i = 0; i < patternStrings.length; i++) { patterns[i] = Pattern.compile(patternStrings[i]); } return patterns; } /** * Evaluate an input string against the rule set. * * @param input an input string * @return a response */ public Response evaluate(final String input) { for (final Rule rule : rules) { if (rule.pattern.matcher(input).matches()) { return rule.response; } } return defaultResponse; } /** * Evaluate an input string against the ruleset for acceptance. * * @param input an input string * @return true if the response for this input is ACCEPT, false otherwise */ public boolean accept(final String input) { return evaluate(input) == Response.ACCEPT; } /** * Evaluate an input string against the ruleset for rejection. * * @param input an input string * @return true if the response for this input is REJECT, false otherwise */ public boolean reject(final String input) { return !accept(input); } /** * The two responses to an input. */ public enum Response { /** * Accept the input. */ ACCEPT, /** * Reject the input. */ REJECT, } /** * An individual rule in a ruleset. * Consists of a regular expression, and a response to return if the given input matches it. */ public static final class Rule { private final Pattern pattern; private final Response response; private Rule(final Pattern pattern, final Response response) { this.pattern = pattern; this.response = response; } } /** * Ruleset builder. */ public static class Builder { private final LinkedList<Rule> rules = Lists.newLinkedList(); private final Response defaultResponse; /** * Constructor. * * @param defaultResponse the response to return if no rule is matched */ public Builder(final Response defaultResponse) { this.defaultResponse = defaultResponse; } /** * Add a rule by compiling the given string into a regular expression. * * @param regexString a regex string * @param response the response this rule returns if matched * @return the builder */ public Builder addRule(final String regexString, final Response response) { return addRule(Pattern.compile(regexString), response); } /** * Add a rule by with the given pre-compiled regular expression. * * @param pattern a pattern * @param response the response this rule returns if matched * @return the builder */ public Builder addRule(final Pattern pattern, final Response response) { rules.add(new Rule(pattern, response)); return this; } /** * Build the ruleset. * * @return a RegexRuleSet */ public RegexRuleSet build() { return new RegexRuleSet(rules, defaultResponse); } } }
2,130
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/RegexDirectoryManifestFilter.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.properties.RegexDirectoryManifestProperties; import lombok.extern.slf4j.Slf4j; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Implementation of DirectoryManifestFilter that filters manifest entries base on a list of regular expressions * provided via properties class. * * @author mprimi * @since 4.0.0 */ @Slf4j public class RegexDirectoryManifestFilter implements DirectoryManifest.Filter { private final List<Pattern> filePathPatterns; private final List<Pattern> directoryPathPatterns; private final List<Pattern> directoryContentPathPatterns; /** * Constructor. * * @param properties the regex properties */ public RegexDirectoryManifestFilter(final RegexDirectoryManifestProperties properties) { int flags = 0; if (!properties.isCaseSensitiveMatching()) { flags += Pattern.CASE_INSENSITIVE; } this.filePathPatterns = compileRegexList(properties.getFileRejectPatterns(), flags); this.directoryPathPatterns = compileRegexList(properties.getDirectoryRejectPatterns(), flags); this.directoryContentPathPatterns = compileRegexList(properties.getDirectoryTraversalRejectPatterns(), flags); } /** * {@inheritDoc} */ @Override public boolean includeFile(final Path path, final BasicFileAttributes attrs) { final String pathString = path.toString(); return this.filePathPatterns.stream().noneMatch(p -> p.matcher(pathString).matches()); } /** * {@inheritDoc} */ @Override public boolean includeDirectory(final Path path, final BasicFileAttributes attrs) { final String pathString = path.toString(); return this.directoryPathPatterns.stream().noneMatch(p -> p.matcher(pathString).matches()); } /** * {@inheritDoc} */ @Override public boolean walkDirectory(final Path path, final BasicFileAttributes attrs) { final String pathString = path.toString(); return this.directoryContentPathPatterns.stream().noneMatch(p -> p.matcher(pathString).matches()); } private List<Pattern> compileRegexList(final Collection<String> patterns, final int flags) { return patterns.stream() .map(p -> Pattern.compile(p, flags)) .collect(Collectors.toList()); } }
2,131
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/HostnameUtil.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.amazonaws.util.EC2MetadataUtils; import io.awspring.cloud.context.support.env.AwsCloudEnvironmentCheckUtils; import org.apache.commons.lang3.StringUtils; import java.net.InetAddress; import java.net.UnknownHostException; /** * Static utility class to determine the local hostname. * * @author mprimi * @since 4.0.0 */ public final class HostnameUtil { private HostnameUtil() { } /** * Get the local hostname string. * This implementation actually return an IP address string. * * @return a hostname string * @throws UnknownHostException if hostname resolution fails */ public static String getHostname() throws UnknownHostException { final String hostname; if (AwsCloudEnvironmentCheckUtils.isRunningOnCloudEnvironment()) { hostname = EC2MetadataUtils.getPrivateIpAddress(); } else { // Fallback if not on AWS hostname = InetAddress.getLocalHost().getCanonicalHostName(); } if (StringUtils.isBlank(hostname)) { throw new IllegalStateException("Unable to create a Genie Host Info instance as hostname is blank"); } return hostname; } }
2,132
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/ExponentialBackOffTrigger.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.netflix.genie.common.internal.properties.ExponentialBackOffTriggerProperties; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import javax.annotation.concurrent.ThreadSafe; import java.util.Date; /** * Trigger implementation whose scheduling delay grows exponentially based on a given factor. * The delay is bound between some minimum and maximum. * The delay can be relative to the previous task scheduling/execution/completion. * * @author mprimi * @since 3.3.9 */ @ThreadSafe public class ExponentialBackOffTrigger implements Trigger { private static final float POSITIVE_NUMBER = 1; private final DelayType delayType; private final long minDelay; private final long maxDelay; private final float factor; private long currentDelay; /** * Constructor with properties. * Loads all values during construction. I.e. does not respond to subsequent changes to property values dynamically. * * @param properties the properties */ public ExponentialBackOffTrigger( final ExponentialBackOffTriggerProperties properties ) { this( properties.getDelayType(), properties.getMinDelay().toMillis(), properties.getMaxDelay().toMillis(), properties.getFactor() ); } /** * Constructor. * * @param delayType type of delay * @param minDelay minimum delay in milliseconds * @param maxDelay maximum delay in milliseconds * @param factor multiplier factor to grow the delay * @throws IllegalArgumentException if the minimum delay is smaller than 1, the max delay is smaller than the * minimum, or the factor is not positive. */ public ExponentialBackOffTrigger( final DelayType delayType, final long minDelay, final long maxDelay, final float factor ) { this.delayType = delayType; this.minDelay = minDelay; this.maxDelay = maxDelay; this.factor = factor; if (Math.signum(minDelay) != POSITIVE_NUMBER) { throw new IllegalArgumentException("Minimum delay must be a positive number"); } if (maxDelay < minDelay) { throw new IllegalArgumentException("Maximum delay must be larger than minimum"); } if (Math.signum(factor) != POSITIVE_NUMBER) { throw new IllegalArgumentException("Factor must be a positive number"); } reset(); } /** * {@inheritDoc} */ @Override public Date nextExecutionTime(final TriggerContext triggerContext) { Date baseTimeOffset = null; switch (delayType) { case FROM_PREVIOUS_SCHEDULING: baseTimeOffset = triggerContext.lastScheduledExecutionTime(); break; case FROM_PREVIOUS_EXECUTION_BEGIN: baseTimeOffset = triggerContext.lastActualExecutionTime(); break; case FROM_PREVIOUS_EXECUTION_COMPLETION: baseTimeOffset = triggerContext.lastCompletionTime(); break; default: throw new RuntimeException("Unhandled delay type: " + delayType); } if (baseTimeOffset == null) { baseTimeOffset = new Date(); } return new Date(baseTimeOffset.toInstant().toEpochMilli() + getAndIncrementDelay()); } /** * Reset the delay to the minimum given at construction time. * Example usage: if the trigger is used to slow down attempt to contact a remote service in case of error, then * a successful request can invoke reset, ensuring the next attempt will not be delayed. */ public synchronized void reset() { currentDelay = minDelay; } private synchronized long getAndIncrementDelay() { final long delay = currentDelay; currentDelay = Math.min( maxDelay, (long) (factor * currentDelay) ); return delay; } /** * How the delay is calculated. */ public enum DelayType { /** * Calculate delay from the previous time the task was scheduled. */ FROM_PREVIOUS_SCHEDULING, /** * Calculate delay from the start of the previous execution. */ FROM_PREVIOUS_EXECUTION_BEGIN, /** * Calculate delay from the completion of the previous execution. */ FROM_PREVIOUS_EXECUTION_COMPLETION, } }
2,133
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/GenieHostInfo.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * Container for information about the host a Genie process (web server or agent) is running on. * * @author tgianos * @since 4.0.0 */ @RequiredArgsConstructor @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class GenieHostInfo { private final String hostname; }
2,134
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/PropertiesMapCache.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import lombok.extern.slf4j.Slf4j; import org.springframework.core.env.Environment; import javax.validation.constraints.NotBlank; import java.time.Duration; import java.util.Map; /** * Utility class that produces a map of properties and their values if they match a given prefix. * The prefix is stripped. * The map is cached for a fixed amount of time to avoid re-computing for each call. * * @author mprimi * @since 4.0.0 */ @Slf4j public class PropertiesMapCache { private static final String CACHE_KEY = "properties-map"; private final Environment environment; private final String prefix; private final LoadingCache<String, Map<String, String>> cache; /** * Constructor. * * @param refreshInterval the properties snapshot refresh interval * @param environment the environment * @param prefix the properties prefix to match and strip */ public PropertiesMapCache( final Duration refreshInterval, final Environment environment, @NotBlank final String prefix ) { this.environment = environment; this.prefix = prefix; this.cache = Caffeine .newBuilder() .refreshAfterWrite(refreshInterval) .initialCapacity(1) .build(this::loadProperties); } /** * Get the current map of properties and their values. * * @return an immutable map of property name and property value, for any property that matches the pattern that has * a non-blank value */ public Map<String, String> get() { return this.cache.get(CACHE_KEY); } private Map<String, String> loadProperties(final String propertiesKey) { // There's only 1 item in this cache, so key is redundant return PropertySourceUtils.createPropertiesSnapshot( this.environment, this.prefix ); } /** * Factory class that produces {@link PropertiesMapCache} instances. */ public static class Factory { private final Environment environment; /** * Constructor. * * @param environment the environment */ public Factory(final Environment environment) { this.environment = environment; } /** * Create a {@link PropertiesMapCache} with the given refresh interval and filter pattern. * * @param refreshInterval the refresh interval * @param prefix the prefix to match and strip * @return a {@link PropertiesMapCache} */ public PropertiesMapCache get(final Duration refreshInterval, @NotBlank final String prefix) { return new PropertiesMapCache(refreshInterval, environment, prefix); } } }
2,135
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/PropertySourceUtils.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.util; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySources; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.Resource; import java.io.IOException; import java.util.Map; import java.util.Set; /** * Utilities for working with Spring {@link PropertySource}. * * @author tgianos * @since 4.0.0 */ @Slf4j public final class PropertySourceUtils { private static final YamlPropertySourceLoader YAML_PROPERTY_SOURCE_LOADER = new YamlPropertySourceLoader(); private PropertySourceUtils() { } /** * Load a YAML {@link PropertySource} from the given {@code resource}. * * @param propertySourceName The name of the this property source * @param resource The resource. Must exist and be YAML. * @return A {@link PropertySource} representing this set of properties */ public static PropertySource<?> loadYamlPropertySource(final String propertySourceName, final Resource resource) { if (!resource.exists()) { throw new IllegalArgumentException("Resource " + resource + " does not exist"); } try { return YAML_PROPERTY_SOURCE_LOADER.load(propertySourceName, resource).get(0); } catch (final IOException ex) { throw new IllegalStateException("Failed to load yaml configuration from " + resource, ex); } } /** * Takes a snapshot of the properties that match a given prefix. * The prefix is stripped from the property name. * Properties with empty and null values are not included. * * @param environment the environment * @param prefix the prefix to match * @return an immutable map of property name and property value in string form */ public static Map<String, String> createPropertiesSnapshot( final Environment environment, final String prefix ) { // Obtain properties sources from environment final PropertySources propertySources; if (environment instanceof ConfigurableEnvironment) { propertySources = ((ConfigurableEnvironment) environment).getPropertySources(); } else { propertySources = new StandardEnvironment().getPropertySources(); } // Create set of all properties that match the filter pattern final Set<String> filteredPropertyNames = Sets.newHashSet(); for (final PropertySource<?> propertySource : propertySources) { if (propertySource instanceof EnumerablePropertySource) { for (final String propertyName : ((EnumerablePropertySource<?>) propertySource).getPropertyNames()) { if (propertyName.startsWith(prefix)) { log.debug("Adding matching property: {}", propertyName); filteredPropertyNames.add(propertyName); } else { log.debug("Ignoring property: {}", propertyName); } } } } // Create immutable properties map final ImmutableMap.Builder<String, String> propertiesMapBuilder = ImmutableMap.builder(); for (final String propertyName : filteredPropertyNames) { final String propertyValue = environment.getProperty(propertyName); final String strippedPropertyName = StringUtils.removeStart(propertyName, prefix); if (StringUtils.isBlank(strippedPropertyName) || StringUtils.isBlank(propertyValue)) { log.debug("Skipping blank value property: {}", propertyName); } else { propertiesMapBuilder.put(strippedPropertyName, propertyValue); } } return propertiesMapBuilder.build(); } }
2,136
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/util/package-info.java
/* * * Copyright 2015 Netflix, Inc. * * Licensed 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. * */ /** * Internal utilities shared by client and server components. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.util; import javax.annotation.ParametersAreNonnullByDefault;
2,137
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/package-info.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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. * */ /** * All checked exceptions internal to Genie. * * @author mprimi * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.exceptions; import javax.annotation.ParametersAreNonnullByDefault;
2,138
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieApplicationNotFoundException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where an application was expected to exist (e.g. saving a job specification for a * job) but it didn't. * * @author tgianos * @since 4.0.0 */ public class GenieApplicationNotFoundException extends GenieRuntimeException { /** * Constructor. */ public GenieApplicationNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieApplicationNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieApplicationNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieApplicationNotFoundException(final Throwable cause) { super(cause); } }
2,139
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieJobResolutionRuntimeException.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * When resolution fails with a runtime error, such as the selector timing out. * * @author mprimi * @since 4.0.0 */ public class GenieJobResolutionRuntimeException extends GenieRuntimeException { /** * Constructor. */ public GenieJobResolutionRuntimeException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieJobResolutionRuntimeException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieJobResolutionRuntimeException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieJobResolutionRuntimeException(final Throwable cause) { super(cause); } }
2,140
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieJobNotFoundException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where a job was expected to exist (e.g. saving a job specification for a job) but * it didn't. * * @author tgianos * @since 4.0.0 */ public class GenieJobNotFoundException extends GenieRuntimeException { /** * Constructor. */ public GenieJobNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieJobNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieJobNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieJobNotFoundException(final Throwable cause) { super(cause); } }
2,141
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieInvalidStatusException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * Exception thrown when a status supplied by a client for as their known previous status doesn't match what the system * has in the database. * * @author tgianos * @since 4.0.0 */ public class GenieInvalidStatusException extends GenieRuntimeException { /** * Constructor. */ public GenieInvalidStatusException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieInvalidStatusException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieInvalidStatusException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieInvalidStatusException(final Throwable cause) { super(cause); } }
2,142
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieAgentRejectedException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where an Agent was rejected by the server. * * @author mprimi * @since 4.0.0 */ public class GenieAgentRejectedException extends GenieRuntimeException { /** * Constructor. */ public GenieAgentRejectedException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieAgentRejectedException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieAgentRejectedException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieAgentRejectedException(final Throwable cause) { super(cause); } }
2,143
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieJobAlreadyClaimedException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * Exception thrown when a job is already claimed in the system and another agent tries to claim it. * * @author tgianos * @since 4.0.0 */ public class GenieJobAlreadyClaimedException extends GenieRuntimeException { /** * Constructor. */ public GenieJobAlreadyClaimedException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieJobAlreadyClaimedException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieJobAlreadyClaimedException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieJobAlreadyClaimedException(final Throwable cause) { super(cause); } }
2,144
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieRuntimeException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; import com.fasterxml.jackson.annotation.JsonFilter; import com.netflix.genie.common.external.util.GenieObjectMapper; /** * Base class for Genie runtime exceptions. * * @author tgianos * @since 4.0.0 */ @JsonFilter(GenieObjectMapper.EXCEPTIONS_FILTER_NAME) public class GenieRuntimeException extends RuntimeException { /** * Constructor. */ public GenieRuntimeException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieRuntimeException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieRuntimeException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieRuntimeException(final Throwable cause) { super(cause); } }
2,145
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieCommandNotFoundException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where a command was expected to exist (e.g. saving a job specification for a job) * but it didn't. * * @author tgianos * @since 4.0.0 */ public class GenieCommandNotFoundException extends GenieRuntimeException { /** * Constructor. */ public GenieCommandNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieCommandNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieCommandNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieCommandNotFoundException(final Throwable cause) { super(cause); } }
2,146
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieIdAlreadyExistsException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * Exception thrown when an id is attempting to be saved that already exists in the system. * * @author tgianos * @since 4.0.0 */ public class GenieIdAlreadyExistsException extends GenieRuntimeException { /** * Constructor. */ public GenieIdAlreadyExistsException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieIdAlreadyExistsException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieIdAlreadyExistsException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieIdAlreadyExistsException(final Throwable cause) { super(cause); } }
2,147
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieJobSpecificationNotFoundException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where a job specification was expected to exist but it doesn't. * * @author tgianos * @since 4.0.0 */ public class GenieJobSpecificationNotFoundException extends GenieRuntimeException { /** * Constructor. */ public GenieJobSpecificationNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieJobSpecificationNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieJobSpecificationNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieJobSpecificationNotFoundException(final Throwable cause) { super(cause); } }
2,148
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/GenieClusterNotFoundException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.unchecked; /** * An exception to represent the case where a cluster was expected to exist (e.g. saving a job specification for a job) * but it didn't. * * @author tgianos * @since 4.0.0 */ public class GenieClusterNotFoundException extends GenieRuntimeException { /** * Constructor. */ public GenieClusterNotFoundException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieClusterNotFoundException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieClusterNotFoundException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieClusterNotFoundException(final Throwable cause) { super(cause); } }
2,149
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/unchecked/package-info.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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. * */ /** * All unchecked (Runtime) exceptions for Genie. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.exceptions.unchecked; import javax.annotation.ParametersAreNonnullByDefault;
2,150
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/checked/GenieJobResolutionException.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.checked; /** * When a request for resolving a job can't be completed for some reason. * * @author tgianos * @since 4.0.0 */ public class GenieJobResolutionException extends GenieCheckedException { /** * Constructor. */ public GenieJobResolutionException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieJobResolutionException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieJobResolutionException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieJobResolutionException(final Throwable cause) { super(cause); } }
2,151
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/checked/GenieConversionException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.checked; /** * Failure to convert objects into wire format or vice versa. * * @author mprimi * @since 4.0.0 */ public class GenieConversionException extends GenieCheckedException { /** * Constructor. */ public GenieConversionException() { super(); } /** * Constructor with message. * * @param message message */ public GenieConversionException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message message * @param cause cause */ public GenieConversionException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieConversionException(final Throwable cause) { super(cause); } }
2,152
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/checked/GenieCheckedException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.checked; import com.fasterxml.jackson.annotation.JsonFilter; import com.netflix.genie.common.external.util.GenieObjectMapper; /** * Base class for Genie checked exceptions. * * @author tgianos * @since 4.0.0 */ @JsonFilter(GenieObjectMapper.EXCEPTIONS_FILTER_NAME) public class GenieCheckedException extends Exception { /** * Constructor. */ public GenieCheckedException() { super(); } /** * Constructor. * * @param message The detail message */ public GenieCheckedException(final String message) { super(message); } /** * Constructor. * * @param message The detail message * @param cause The root cause of this exception */ public GenieCheckedException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public GenieCheckedException(final Throwable cause) { super(cause); } }
2,153
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/checked/JobArchiveException.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.exceptions.checked; /** * Exception thrown in case there is a problem with archiving files. * * @author standon * @since 4.0.0 */ public class JobArchiveException extends GenieCheckedException { /** * Constructor. */ public JobArchiveException() { super(); } /** * Constructor with message. * * @param message a message */ public JobArchiveException(final String message) { super(message); } /** * Constructor with message and cause. * * @param message a message * @param cause a cause */ public JobArchiveException(final String message, final Throwable cause) { super(message, cause); } /** * Constructor. * * @param cause The root cause of this exception */ public JobArchiveException(final Throwable cause) { super(cause); } }
2,154
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/exceptions/checked/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 to contain exceptions that are checked but only used internally within Genie web or agent projects. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.exceptions.checked; import javax.annotation.ParametersAreNonnullByDefault;
2,155
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommandMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.validation.constraints.NotNull; /** * Metadata supplied by a user for a Command resource. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = CommandMetadata.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class CommandMetadata extends CommonMetadata { @NotNull(message = "A command status is required") private final CommandStatus status; private CommandMetadata(final Builder builder) { super(builder); this.status = builder.bStatus; } /** * A builder to create command user metadata instances. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonMetadata.Builder<Builder> { private final CommandStatus bStatus; /** * Constructor which has required fields. * * @param name The name to use for the command * @param user The user who owns the command * @param version The version of the command * @param status The status of the command */ @JsonCreator public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final CommandStatus status ) { super(name, user, version); this.bStatus = status; } /** * Build the command metadata instance. * * @return Create the final read-only commandMetadata instance */ public CommandMetadata build() { return new CommandMetadata(this); } } }
2,156
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommonMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableSet; import com.netflix.genie.common.external.util.GenieObjectMapper; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.IOException; import java.io.Serializable; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Metadata fields common to all Genie resources (Jobs, clusters, etc). * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public abstract class CommonMetadata implements Serializable { private static final long serialVersionUID = 7789443514882247655L; @NotBlank(message = "A name is required and must be at most 255 characters") @Size(max = 255, message = "The name can be no longer than 255 characters") private final String name; @NotBlank(message = "A user is required and must be at most 255 characters") @Size(max = 255, message = "The user can be no longer than 255 characters") private final String user; @NotBlank(message = "A version is required and must be at most 255 characters") @Size(max = 255, message = "The version can be no longer than 255 characters") private final String version; @Size(max = 1000, message = "The description can be no longer than 1000 characters") private final String description; private final JsonNode metadata; private final ImmutableSet< @NotEmpty(message = "A tag can't be an empty string") @Size(max = 255, message = "A tag can't be longer than 255 characters") String> tags; /** * Constructor. * * @param builder The builder containing the values to use. */ @SuppressWarnings("unchecked") protected CommonMetadata(final Builder builder) { this.name = builder.bName; this.user = builder.bUser; this.version = builder.bVersion; this.description = builder.bDescription; this.metadata = builder.bMetadata; this.tags = builder.bTags == null ? ImmutableSet.of() : ImmutableSet.copyOf(builder.bTags); } /** * Get the description. * * @return The description as an {@link Optional} */ public Optional<String> getDescription() { return Optional.ofNullable(this.description); } /** * Get the metadata of this resource as a JSON Node. * * @return {@link Optional} of the metadata if it exists */ public Optional<JsonNode> getMetadata() { return Optional.ofNullable(this.metadata); } /** * Get the tags associated with this resource. Will be returned as an immutable set and any attempt to modify will * result in an exception being thrown. * * @return The tags */ public Set<String> getTags() { return this.tags; } /** * Builder for common fields. * * @param <T> Type of builder that extends this * @author tgianos * @since 4.0.0 */ // NOTE: These abstract class builders are marked public not protected due to a JDK bug from 1999 which caused // issues with Clojure clients which use reflection to make the Java API calls. // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4283544 // Setting them to public seems to have solved the issue at the expense of "proper" code design @SuppressWarnings("unchecked") public static class Builder<T extends Builder> { private final String bName; private final String bUser; private final String bVersion; private String bDescription; private JsonNode bMetadata; private ImmutableSet<String> bTags; /** * Constructor with required fields. * * @param name The name of the resource * @param user The user owning the resource * @param version The version of hte resource */ protected Builder( final String name, final String user, final String version ) { this.bName = name; this.bUser = user; this.bVersion = version; } /** * Set the description for the resource. * * @param description The description to use * @return The builder */ public T withDescription(@Nullable final String description) { this.bDescription = StringUtils.isBlank(description) ? null : description; return (T) this; } /** * Set the tags to use for the resource. * * @param tags The tags to use. Blanks will be removed * @return The builder */ public T withTags(@Nullable final Set<String> tags) { this.bTags = tags == null ? ImmutableSet.of() : ImmutableSet.copyOf( tags .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toSet()) ); return (T) this; } /** * With the metadata to set for the job as a JsonNode. * * @param metadata The metadata to set * @return The builder */ @JsonSetter public T withMetadata(@Nullable final JsonNode metadata) { this.bMetadata = metadata; return (T) this; } /** * With the ad-hoc metadata to set for the resource as a string of valid JSON. * * @param metadata The metadata to set. Must be valid JSON * @return The builder * @throws IllegalArgumentException On invalid JSON */ public T withMetadata(@Nullable final String metadata) throws IllegalArgumentException { if (metadata == null) { this.bMetadata = null; } else { try { this.bMetadata = GenieObjectMapper.getMapper().readTree(metadata); } catch (final IOException ioe) { throw new IllegalArgumentException("Invalid metadata JSON string passed in " + metadata, ioe); } } return (T) this; } } }
2,157
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ClusterStatus.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; /** * The possible statuses for a cluster. * * @author tgianos * @since 4.0.0 */ public enum ClusterStatus { /** * Cluster is UP, and accepting jobs. */ UP, /** * Cluster may be running, but not accepting job submissions. */ OUT_OF_SERVICE, /** * Cluster is no-longer running, and is terminated. */ TERMINATED }
2,158
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommonRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import java.util.Optional; /** * Common fields for Resource requests (clusters, commands, jobs, etc). * * @author tgianos * @since 4.0.0 */ public interface CommonRequest { /** * Get the ID the user has requested for this resource if one was added. * * @return The ID wrapped in an {@link Optional} */ Optional<String> getRequestedId(); /** * Get the resources the user requested for the job during execution if any. * * @return The execution resources */ ExecutionEnvironment getResources(); }
2,159
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobSpecification.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.io.File; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; /** * This DTO represents all the information needed to execute a job by the Genie Agent. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class JobSpecification implements Serializable { private static final long serialVersionUID = 4741981587685457902L; private final ImmutableList<String> executableArgs; private final ImmutableList<String> jobArgs; private final ExecutionResource job; private final ExecutionResource cluster; private final ExecutionResource command; private final ImmutableList<ExecutionResource> applications; private final ImmutableMap<String, String> environmentVariables; private final boolean interactive; private final File jobDirectoryLocation; private final String archiveLocation; private final Integer timeout; /** * Constructor. * * @param executableArgs Executable and its fixed argument provided by the Command * @param jobArgs Job arguments provided by the user for this job * @param job The execution resources for a specific job * @param cluster The execution resources for a specific cluster used for a job * @param command The execution resources for a specific command used for a job * @param applications The execution resources of all applications used for a job. Optional * @param environmentVariables The environment variables the agent should set when running the job. Optional * @param interactive Whether the job is interactive or not * @param jobDirectoryLocation Location on disk where the job directory will be created * @param archiveLocation Location where job folder is archived by the agent when job finishes. Optional * @param timeout The number of seconds after a job starts that it should be killed due to timeout. * Optional */ @JsonCreator public JobSpecification( @JsonProperty("executableArgs") @Nullable final List<String> executableArgs, @JsonProperty("jobArgs") @Nullable final List<String> jobArgs, @JsonProperty(value = "job", required = true) final ExecutionResource job, @JsonProperty(value = "cluster", required = true) final ExecutionResource cluster, @JsonProperty(value = "command", required = true) final ExecutionResource command, @JsonProperty("applications") @Nullable final List<ExecutionResource> applications, @JsonProperty("environmentVariables") @Nullable final Map<String, String> environmentVariables, @JsonProperty(value = "interactive", required = true) final boolean interactive, @JsonProperty(value = "jobDirectoryLocation", required = true) final File jobDirectoryLocation, @JsonProperty(value = "archiveLocation") @Nullable final String archiveLocation, @JsonProperty(value = "timeout") @Nullable final Integer timeout ) { this.executableArgs = executableArgs == null ? ImmutableList.of() : ImmutableList.copyOf(executableArgs); this.jobArgs = jobArgs == null ? ImmutableList.of() : ImmutableList.copyOf(jobArgs); this.job = job; this.cluster = cluster; this.command = command; this.applications = applications == null ? ImmutableList.of() : ImmutableList.copyOf(applications); this.environmentVariables = environmentVariables == null ? ImmutableMap.of() : ImmutableMap.copyOf(environmentVariables); this.interactive = interactive; this.jobDirectoryLocation = jobDirectoryLocation; this.archiveLocation = archiveLocation; this.timeout = timeout; } /** * Returns an unmodifiable list of executable and arguments provided by the Command resolved to. * * @return A list of executable and arguments that will throw exception if modifications are attempted */ public List<String> getExecutableArgs() { return executableArgs; } /** * Returns an unmodifiable list of arguments provided by the user for this job. * * @return A list of arguments that will throw exception if modifications are attempted */ public List<String> getJobArgs() { return jobArgs; } /** * Returns an unmodifiable list of applications. * * @return A list of Applications that will throw exception if modifications are attempted */ public List<ExecutionResource> getApplications() { return this.applications; } /** * Get the environment variables dictated by the server that should be set in the job execution environment. * * @return The variable name to value pairs that should be set in the execution environment of the job. This map * will be immutable and any attempt to modify will result in an exception */ public Map<String, String> getEnvironmentVariables() { return this.environmentVariables; } /** * Get the archive location for the job folder. * * @return archive location for the job folder wrapped in an {@link Optional} */ public Optional<String> getArchiveLocation() { return Optional.ofNullable(this.archiveLocation); } /** * Get the job timeout. * * @return The number of seconds after a job launch that this job should be killed by the agent due to timeout. * Wrapped in {@link Optional} as it's not required. {@link Optional#empty()} means there is no timeout and the job * can run indefinitely. */ public Optional<Integer> getTimeout() { return Optional.ofNullable(this.timeout); } /** * Common representation of resources used for job execution e.g. a Cluster, Command, Application. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public static class ExecutionResource implements Serializable { private static final long serialVersionUID = -444882678226048086L; private final String id; private final ExecutionEnvironment executionEnvironment; /** * Constructor. * * @param id The unique identifier of this execution resource * @param executionEnvironment The environment that should be setup for this resource */ @JsonCreator public ExecutionResource( @JsonProperty(value = "id", required = true) final String id, @JsonProperty( value = "executionEnvironment", required = true ) final ExecutionEnvironment executionEnvironment ) { this.id = id; this.executionEnvironment = executionEnvironment; } } }
2,160
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ApplicationMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Optional; /** * Metadata supplied by a user for an Application resource. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = ApplicationMetadata.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class ApplicationMetadata extends CommonMetadata { @Size(max = 255, message = "Max length of an application type is 255 characters") private final String type; @NotNull(message = "An application status is required") private final ApplicationStatus status; private ApplicationMetadata(final Builder builder) { super(builder); this.status = builder.bStatus; this.type = builder.bType; } /** * Get the type of this application. * * @return The type wrapped in an {@link Optional} */ public Optional<String> getType() { return Optional.ofNullable(this.type); } /** * A builder to create application user metadata instances. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonMetadata.Builder<Builder> { private final ApplicationStatus bStatus; private String bType; /** * Constructor which has required fields. * * @param name The name to use for the application * @param user The user who owns the application * @param version The version of the application * @param status The status of the application */ @JsonCreator public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final ApplicationStatus status ) { super(name, user, version); this.bStatus = status; } /** * Set the type of this application resource. * * @param type The type (e.g. Hadoop, Spark, etc) for grouping applications * @return The builder */ public Builder withType(@Nullable final String type) { this.bType = StringUtils.isBlank(type) ? null : type; return this; } /** * Build the application metadata instance. * * @return Create the final read-only ApplicationMetadata instance */ public ApplicationMetadata build() { return new ApplicationMetadata(this); } } }
2,161
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommandStatus.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; /** * The available statuses for Commands. * * @author tgianos * @since 4.0.0 */ public enum CommandStatus { /** * Command is active, and in-use. */ ACTIVE, /** * Command is deprecated, and will be made inactive in the future. */ DEPRECATED, /** * Command is inactive, and not in-use. */ INACTIVE }
2,162
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/Image.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import javax.annotation.Nullable; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; /** * Representation of metadata corresponding to the container image (docker, etc.) that the job should be launched in. * * @author tgianos * @since 4.3.0 */ @JsonDeserialize(builder = Image.Builder.class) public class Image implements Serializable { private final String name; private final String tag; private final List<String> arguments; private Image(final Builder builder) { this.name = builder.bName; this.tag = builder.bTag; this.arguments = Collections.unmodifiableList(new ArrayList<>(builder.bArguments)); } /** * Get the name of the image to use for the job if one was specified. * * @return The name or {@link Optional#empty()} */ public Optional<String> getName() { return Optional.ofNullable(this.name); } /** * Get the tag of the image to use for the job if one was specified. * * @return The tag or {@link Optional#empty()} */ public Optional<String> getTag() { return Optional.ofNullable(this.tag); } /** * Get the image arguments if any. * * @return An unmodifiable list of arguments. Any attempt to modify will throw an exception */ public List<String> getArguments() { return this.arguments; } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.name, this.tag, this.arguments); } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Image)) { return false; } final Image image = (Image) o; return Objects.equals(this.name, image.name) && Objects.equals(this.tag, image.tag) && Objects.equals(this.arguments, image.arguments); } /** * {@inheritDoc} */ @Override public String toString() { return "Image{" + "name='" + this.name + '\'' + ", tag='" + this.tag + '\'' + ", arguments='" + this.arguments + '\'' + '}'; } /** * Builder for immutable instances of {@link Image}. * * @author tgianos * @since 4.3.0 */ public static class Builder { private String bName; private String bTag; private final List<String> bArguments; /** * Constructor. */ public Builder() { this.bArguments = new ArrayList<>(); } /** * Set the name of the image to use. * * @param name The name or {@literal null} * @return This {@link Builder} instance */ public Builder withName(@Nullable final String name) { this.bName = name; return this; } /** * Set the tag of the image to use. * * @param tag The tag or {@literal null} * @return This {@link Builder} instance */ public Builder withTag(@Nullable final String tag) { this.bTag = tag; return this; } /** * Set the arguments for the image. * * @param arguments The arguments. {@literal null} will clear any currently set arguments, as will empty list. * Any other value with replace. * @return This {@link Builder} instance */ public Builder withArguments(@Nullable final List<String> arguments) { this.bArguments.clear(); if (arguments != null) { this.bArguments.addAll(arguments); } return this; } /** * Create an immutable instance of {@link Image} based on the current contents of this builder instance. * * @return A new {@link Image} instance */ public Image build() { return new Image(this); } } }
2,163
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/Application.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.Valid; import java.time.Instant; /** * An immutable V4 Application resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) public class Application extends CommonResource { @Valid private final ApplicationMetadata metadata; /** * Constructor. * * @param id The unique identifier of this application * @param created The time this application was created in the system * @param updated The last time this application was updated in the system * @param resources The execution resources associated with this application * @param metadata The metadata associated with this application */ @JsonCreator public Application( @JsonProperty(value = "id", required = true) final String id, @JsonProperty(value = "created", required = true) final Instant created, @JsonProperty(value = "updated", required = true) final Instant updated, @JsonProperty(value = "resources") @Nullable final ExecutionEnvironment resources, @JsonProperty(value = "metadata", required = true) final ApplicationMetadata metadata ) { super(id, created, updated, resources); this.metadata = metadata; } }
2,164
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ApiJobRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.Lists; import lombok.AccessLevel; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.List; /** * The builder and methods available for a request generated by a REST API request. * * @author tgianos * @since 4.0.0 */ @JsonDeserialize(builder = ApiJobRequest.Builder.class) public interface ApiJobRequest extends CommonRequest { /** * Get the command arguments a user has requested be appended to a command executable for their job. * * @return The command arguments as an immutable list. Any attempt to modify will throw exception */ List<String> getCommandArgs(); /** * Get the metadata a user has supplied for the job including things like name, tags, etc. * * @return The metadata */ JobMetadata getMetadata(); /** * The resource criteria that was supplied for the job. * * @return The criteria used to select the cluster, command and optionally applications for the job */ ExecutionResourceCriteria getCriteria(); /** * Get the environment parameters the user requested to be associated with the Agent. * * @return The requested agent environment */ JobEnvironmentRequest getRequestedJobEnvironment(); /** * Get the requested agent configuration. * * @return The requested agent configuration parameters */ AgentConfigRequest getRequestedAgentConfig(); /** * Builder for a V4 Job Request. * * @author tgianos * @since 4.0.0 */ @Getter(AccessLevel.PACKAGE) class Builder extends CommonRequestImpl.Builder<ApiJobRequest.Builder> { private final JobMetadata bMetadata; private final ExecutionResourceCriteria bCriteria; private final List<String> bCommandArgs = Lists.newArrayList(); private JobEnvironmentRequest bRequestedJobEnvironment; private AgentConfigRequest bRequestedAgentConfig; /** * Constructor with required parameters. * * @param metadata All user supplied metadata * @param criteria All user supplied execution criteria */ @JsonCreator public Builder( @JsonProperty(value = "metadata", required = true) final JobMetadata metadata, @JsonProperty(value = "criteria", required = true) final ExecutionResourceCriteria criteria ) { super(); this.bMetadata = metadata; this.bCriteria = criteria; } /** * Set the ordered list of command line arguments to append to the command executable at runtime. * * @param commandArgs The arguments in the order they should be placed on the command line. Maximum of 10,000 * characters per argument. Any blanks will be removed * @return The builder */ public Builder withCommandArgs(@Nullable final List<String> commandArgs) { this.bCommandArgs.clear(); if (commandArgs != null) { commandArgs.stream().filter(StringUtils::isNotBlank).forEach(this.bCommandArgs::add); } return this; } /** * Set the information provided by a user for the Agent execution environment. * * @param requestedJobEnvironment the requested Genie job environment parameters * @return The builder */ public Builder withRequestedAgentEnvironment( @Nullable final JobEnvironmentRequest requestedJobEnvironment ) { this.bRequestedJobEnvironment = requestedJobEnvironment; return this; } /** * Set the configuration requested for the agent when this job is executed. * * @param requestedAgentConfig The requested configuration * @return The builder */ public Builder withRequestedAgentConfig(@Nullable final AgentConfigRequest requestedAgentConfig) { this.bRequestedAgentConfig = requestedAgentConfig; return this; } /** * Build an immutable job request instance. * * @return An immutable representation of the user supplied information for a job request */ public ApiJobRequest build() { return new JobRequest(this); } } }
2,165
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobEnvironment.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Final values for settings of the Genie job execution environment. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @JsonDeserialize(builder = JobEnvironment.Builder.class) public class JobEnvironment implements Serializable { private static final long serialVersionUID = 8478136461571895069L; private final Map< @NotBlank(message = "Environment variable key can't be blank") @Size(max = 255, message = "Max environment variable name length is 255 characters") String, @NotNull(message = "Environment variable value can't be null") @Size(max = 1024, message = "Max environment variable value length is 1024 characters") String> environmentVariables; private final JsonNode ext; private final ComputeResources computeResources; private final Map<String, Image> images; private JobEnvironment(final Builder builder) { this.environmentVariables = Collections.unmodifiableMap(new HashMap<>(builder.bEnvironmentVariables)); this.ext = builder.bExt; this.computeResources = builder.bComputeResources; this.images = Collections.unmodifiableMap(new HashMap<>(builder.bImages)); } /** * Get the environment variables requested by the user to be added to the job runtime. * * @return The environment variables backed by an immutable map. Any attempt to modify with throw exception */ public Map<String, String> getEnvironmentVariables() { return this.environmentVariables; } /** * Get the extension variables to the agent configuration as a JSON blob. * * @return The extension variables wrapped in an {@link Optional} */ public Optional<JsonNode> getExt() { return Optional.ofNullable(this.ext); } /** * Get the computation resources for the job if any were defined. * * @return The {@link ComputeResources} */ public ComputeResources getComputeResources() { return this.computeResources; } /** * Get the images for the job if any were defined. * * @return The {@link Image} */ public Map<String, Image> getImages() { return this.images; } /** * Builder to create an immutable {@link JobEnvironment} instance. * * @author tgianos * @since 4.0.0 */ public static class Builder { private final Map<String, String> bEnvironmentVariables; private JsonNode bExt; private ComputeResources bComputeResources; private final Map<String, Image> bImages; /** * Constructor. */ public Builder() { this.bEnvironmentVariables = new HashMap<>(); this.bComputeResources = new ComputeResources.Builder().build(); this.bImages = new HashMap<>(); } /** * Set any environment variables that the agent should add to the job runtime. * * @param environmentVariables Additional environment variables * @return The builder */ public Builder withEnvironmentVariables(@Nullable final Map<String, String> environmentVariables) { this.bEnvironmentVariables.clear(); if (environmentVariables != null) { this.bEnvironmentVariables.putAll(environmentVariables); } return this; } /** * Set the extension configuration for the agent. This is generally used for specific implementations of the * job launcher e.g. on Titus or local docker etc. * * @param ext The extension configuration which is effectively a DSL per job launch implementation * @return The builder */ public Builder withExt(@Nullable final JsonNode ext) { this.bExt = ext; return this; } /** * Set the computation resources for the job. * * @param computeResources The {@link ComputeResources} * @return This {@link Builder} instance */ public Builder withComputeResources(final ComputeResources computeResources) { this.bComputeResources = computeResources; return this; } /** * Set the images the job should use. * * @param images The {@link Image} set to use * @return This {@link Builder} instance */ public Builder withImages(final Map<String, Image> images) { this.bImages.clear(); this.bImages.putAll(images); return this; } /** * Build a new immutable instance of an {@link JobEnvironment}. * * @return An instance containing the fields set in this builder */ public JobEnvironment build() { return new JobEnvironment(this); } } }
2,166
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommonRequestImpl.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Optional; /** * Common fields for all Genie 4 resource creation requests (JobRequest, ClusterRequest, etc). * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) abstract class CommonRequestImpl implements CommonRequest, Serializable { private static final long serialVersionUID = 2373945787894868377L; @Size(max = 255, message = "Max length for the ID is 255 characters") private final String requestedId; @Valid private final ExecutionEnvironment resources; /** * Constructor. * * @param builder The builder to get values from */ CommonRequestImpl(final Builder builder) { this(builder.bRequestedId, builder.bResources); } /** * Constructor. * * @param requestedId The id requested by the user. Optional. * @param resources The execution environment resources requested by the user. Optional. */ CommonRequestImpl(@Nullable final String requestedId, @Nullable final ExecutionEnvironment resources) { this.requestedId = requestedId; this.resources = resources == null ? new ExecutionEnvironment(null, null, null) : resources; } /** * {@inheritDoc} */ @Override public Optional<String> getRequestedId() { return Optional.ofNullable(this.requestedId); } /** * Builder for common request fields. * * @param <T> Type of builder that extends this * @author tgianos * @since 4.0.0 */ // NOTE: These abstract class builders are marked public not protected due to a JDK bug from 1999 which caused // issues with Clojure clients which use reflection to make the Java API calls. // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4283544 // Setting them to public seems to have solved the issue at the expense of "proper" code design @SuppressWarnings("unchecked") @Getter(AccessLevel.PACKAGE) public abstract static class Builder<T extends Builder> { private String bRequestedId; private ExecutionEnvironment bResources; /** * Constructor. */ Builder() { } /** * Set the id being requested for the resource. Will be rejected if the ID is already used by another resource * of the same type. If not included a GUID will be supplied. * * @param requestedId The requested id. Max of 255 characters. * @return The builder */ public T withRequestedId(@Nullable final String requestedId) { this.bRequestedId = StringUtils.isBlank(requestedId) ? null : requestedId; return (T) this; } /** * Set the execution resources for this resource. e.g. setup file or configuration files etc * * @param resources The resources to use * @return The builder */ public T withResources(@Nullable final ExecutionEnvironment resources) { this.bResources = resources; return (T) this; } } }
2,167
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/Criterion.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Representation of various criterion options available. Used for determining which cluster and command are used to * execute a job. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @JsonDeserialize(builder = Criterion.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class Criterion implements Serializable { private static final long serialVersionUID = -8382495858646428806L; private final String id; private final String name; private final String version; private final String status; private final ImmutableSet< @NotEmpty(message = "A tag can't be an empty string") @Size(max = 255, message = "A tag can't be longer than 255 characters") String> tags; /** * Copy the contents of the given {@link Criterion} but use the supplied status. * * @param criterion The {@link Criterion} to copy * @param status The status to use */ public Criterion(final Criterion criterion, final String status) { this.id = criterion.id; this.name = criterion.name; this.version = criterion.version; this.status = status; this.tags = ImmutableSet.copyOf(criterion.getTags()); } private Criterion(final Builder builder) throws IllegalArgumentException { this.id = builder.bId; this.name = builder.bName; this.version = builder.bVersion; this.status = builder.bStatus; this.tags = builder.bTags == null ? ImmutableSet.of() : ImmutableSet.copyOf(builder.bTags); if ( StringUtils.isBlank(this.id) && StringUtils.isBlank(this.name) && StringUtils.isBlank(this.version) && StringUtils.isBlank(this.status) && this.tags.isEmpty() ) { throw new IllegalArgumentException("Invalid criterion. One of the fields must have a valid value"); } } /** * Get the id of the resource desired if it exists. * * @return {@link Optional} wrapping the id */ public Optional<String> getId() { return Optional.ofNullable(this.id); } /** * Get the name of the resource desired if it exists. * * @return {@link Optional} wrapping the name */ public Optional<String> getName() { return Optional.ofNullable(this.name); } /** * Get the version of the resource desired if it exists. * * @return {@link Optional} wrapping the version */ public Optional<String> getVersion() { return Optional.ofNullable(this.version); } /** * Get the desired status of the resource if it has been set by the creator. * * @return {@link Optional} wrapping the status */ public Optional<String> getStatus() { return Optional.ofNullable(this.status); } /** * Get the set of tags the creator desires the resource to have if any were set. * * @return An immutable set of strings. Any attempt at modification will throw an exception. */ public Set<String> getTags() { return this.tags; } /** * Builder for creating a Criterion instance. * * @author tgianos * @since 4.0.0 */ public static class Builder { private String bId; private String bName; private String bVersion; private String bStatus; private ImmutableSet<String> bTags; /** * Set the id of the resource (cluster, command, etc) to use. * * @param id The id * @return The builder */ public Builder withId(@Nullable final String id) { this.bId = StringUtils.isBlank(id) ? null : id; return this; } /** * Set the name of the resource (cluster, command, etc) to search for. * * @param name The name of the resource * @return The builder */ public Builder withName(@Nullable final String name) { this.bName = StringUtils.isBlank(name) ? null : name; return this; } /** * Set the version of the resource (cluster, command, etc) to search for. * * @param version The version of the resource * @return The builder */ public Builder withVersion(@Nullable final String version) { this.bVersion = StringUtils.isBlank(version) ? null : version; return this; } /** * Set the status to search for. Overrides default status of resource in search algorithm. * * @param status The status to override the default with * @return The builder */ public Builder withStatus(@Nullable final String status) { this.bStatus = StringUtils.isBlank(status) ? null : status; return this; } /** * Set the tags to use in the search. * * @param tags The tags. Any blanks will be removed * @return The builder */ public Builder withTags(@Nullable final Set<String> tags) { this.bTags = tags == null ? ImmutableSet.of() : ImmutableSet.copyOf( tags .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toSet())); return this; } /** * Build an immutable Criterion. A precondition exception will be thrown if all of the fields are empty. * * @return A criterion which is completely immutable. * @throws IllegalArgumentException A valid Criterion must have at least one field populated */ public Criterion build() throws IllegalArgumentException { return new Criterion(this); } } }
2,168
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ComputeResources.java
/* * * Copyright 2022 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import javax.annotation.Nullable; import javax.validation.constraints.Min; import java.io.Serializable; import java.util.Objects; import java.util.Optional; /** * A representation of compute resources that a Genie entity (job/command/etc.) may request or use. * * @author tgianos * @since 4.3.0 */ public class ComputeResources implements Serializable { @Min(value = 1, message = "Must have at least one CPU") private final Integer cpu; @Min(value = 1, message = "Must have at least one GPU") private final Integer gpu; @Min(value = 1, message = "Must have at least 1 MB of memory") private final Long memoryMb; @Min(value = 1, message = "Must have at least 1 MB of disk space") private final Long diskMb; @Min(value = 1, message = "Must have at least 1 Mbps of network bandwidth") private final Long networkMbps; private ComputeResources(final Builder builder) { this.cpu = builder.bCpu; this.gpu = builder.bGpu; this.memoryMb = builder.bMemoryMb; this.diskMb = builder.bDiskMb; this.networkMbps = builder.bNetworkMbps; } /** * Get the number of CPUs. * * @return The amount or {@link Optional#empty()} */ public Optional<Integer> getCpu() { return Optional.ofNullable(this.cpu); } /** * Get the number of GPUs. * * @return The amount or {@link Optional#empty()} */ public Optional<Integer> getGpu() { return Optional.ofNullable(this.gpu); } /** * Get the amount of memory. * * @return The amount or {@link Optional#empty()} */ public Optional<Long> getMemoryMb() { return Optional.ofNullable(this.memoryMb); } /** * Get the amount of disk space. * * @return The amount or {@link Optional#empty()} */ public Optional<Long> getDiskMb() { return Optional.ofNullable(this.diskMb); } /** * Get the network bandwidth size. * * @return The size or {@link Optional#empty()} */ public Optional<Long> getNetworkMbps() { return Optional.ofNullable(this.networkMbps); } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(this.cpu, this.gpu, this.memoryMb, this.diskMb, this.networkMbps); } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ComputeResources)) { return false; } final ComputeResources that = (ComputeResources) o; return Objects.equals(this.cpu, that.cpu) && Objects.equals(this.gpu, that.gpu) && Objects.equals(this.memoryMb, that.memoryMb) && Objects.equals(this.diskMb, that.diskMb) && Objects.equals(this.networkMbps, that.networkMbps); } /** * {@inheritDoc} */ @Override public String toString() { return "ComputeResources{" + "cpu=" + this.cpu + ", gpu=" + this.gpu + ", memoryMb=" + this.memoryMb + ", diskMb=" + this.diskMb + ", networkMbps=" + this.networkMbps + '}'; } /** * Builder for generating immutable {@link ComputeResources} instances. * * @author tgianos * @since 4.3.0 */ public static class Builder { private Integer bCpu; private Integer bGpu; private Long bMemoryMb; private Long bDiskMb; private Long bNetworkMbps; /** * Set the number of CPUs. * * @param cpu The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withCpu(@Nullable final Integer cpu) { this.bCpu = cpu; return this; } /** * Set the number of GPUs. * * @param gpu The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withGpu(@Nullable final Integer gpu) { this.bGpu = gpu; return this; } /** * Set amount of memory in MB. * * @param memoryMb The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withMemoryMb(@Nullable final Long memoryMb) { this.bMemoryMb = memoryMb; return this; } /** * Set amount of disk space in MB. * * @param diskMb The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withDiskMb(@Nullable final Long diskMb) { this.bDiskMb = diskMb; return this; } /** * Set amount of network bandwidth in Mbps. * * @param networkMbps The number must be at least 1 or {@literal null} * @return The {@link Builder} */ public Builder withNetworkMbps(@Nullable final Long networkMbps) { this.bNetworkMbps = networkMbps; return this; } /** * Create a new immutable {@link ComputeResources} instance based on the current state of this builder instance. * * @return A {@link ComputeResources} instance */ public ComputeResources build() { return new ComputeResources(this); } } }
2,169
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/AgentClientMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.Optional; /** * Metadata for a Genie Agent client. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class AgentClientMetadata extends ClientMetadata { private final String version; private final Integer pid; /** * Constructor. * * @param hostname The hostname of the computer the agent is running on * @param version The version of the agent that sent the request * @param pid The PID of the agent that sent the request */ public AgentClientMetadata( @Nullable final String hostname, @Nullable final String version, @Nullable final Integer pid ) { super(hostname); this.version = version; this.pid = pid; } /** * Get the running version of the agent if it was set. * * @return The version wrapped in an {@link Optional} */ public Optional<String> getVersion() { return Optional.ofNullable(this.version); } /** * Get the process id of the Agent on the host it is running on. * * @return The pid if it was set wrapped in an {@link Optional} */ public Optional<Integer> getPid() { return Optional.ofNullable(this.pid); } }
2,170
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ClientMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Optional; /** * Common base for API and Agent client metadata. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(doNotUseGetters = true) @EqualsAndHashCode(doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class ClientMetadata implements Serializable { private static final long serialVersionUID = 7973228050794689900L; @Size(max = 255, message = "The client hostname can't be longer than 255 characters") private final String hostname; /** * Constructor. * * @param hostname The hostname of the client to the Genie server */ public ClientMetadata(@Nullable final String hostname) { this.hostname = hostname; } /** * Get the hostname of the client. * * @return The hostname if there is one wrapped in an {@link Optional} */ public Optional<String> getHostname() { return Optional.ofNullable(this.hostname); } }
2,171
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/Command.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * An immutable V4 Command resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) public class Command extends CommonResource { @Valid private final CommandMetadata metadata; @NotEmpty(message = "At least one executable entry is required") private final List< @NotEmpty(message = "A default executable element shouldn't be an empty string") @Size(max = 1024, message = "Executable elements can only be 1024 characters") String> executable; private final List<Criterion> clusterCriteria; private final ComputeResources computeResources; private final Map<String, Image> images; /** * Constructor. * * @param id The unique identifier of this command * @param created The time this command was created in the system * @param updated The last time this command was updated in the system * @param resources The execution resources associated with this command * @param metadata The metadata associated with this command * @param executable The executable command that will be used when a job is run with this command. Generally * this will start with the binary and be followed optionally by default arguments. Must * have at least one. Blanks will be removed * @param clusterCriteria The ordered list of cluster {@link Criterion} that should be used to resolve which * clusters this command can run on at job execution time * @param computeResources The default computational resources a job should have if this command is selected * @param images The default images the job should launch with if this command is selected */ @JsonCreator public Command( @JsonProperty(value = "id", required = true) final String id, @JsonProperty(value = "created", required = true) final Instant created, @JsonProperty(value = "updated", required = true) final Instant updated, @JsonProperty(value = "resources") @Nullable final ExecutionEnvironment resources, @JsonProperty(value = "metadata", required = true) final CommandMetadata metadata, @JsonProperty(value = "executable", required = true) final List<String> executable, @JsonProperty(value = "clusterCriteria") @Nullable final List<Criterion> clusterCriteria, @JsonProperty(value = "computeResources") @Nullable final ComputeResources computeResources, @JsonProperty(value = "images") @Nullable final Map<String, Image> images ) { super(id, created, updated, resources); this.metadata = metadata; this.executable = Collections.unmodifiableList( executable .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()) ); this.clusterCriteria = Collections.unmodifiableList( clusterCriteria != null ? new ArrayList<>(clusterCriteria) : new ArrayList<>() ); this.computeResources = computeResources != null ? computeResources : new ComputeResources.Builder().build(); this.images = Collections.unmodifiableMap(images != null ? new HashMap<>(images) : new HashMap<>()); } /** * Get the executable elements (generally a binary followed optionally by default arguments) that should be used * with this command when executing a job. * * @return The executable arguments as an immutable list. Any attempt to modify will throw an exception */ public List<String> getExecutable() { return this.executable; } /** * Get the ordered list of {@link Criterion} for this command to resolve clusters are runtime. * * @return The ordered list of {@link Criterion} as an immutable list. Any attempt to modify will throw an exception */ public List<Criterion> getClusterCriteria() { return this.clusterCriteria; } /** * Get any default compute resources that were requested for this command. * * @return The {@link ComputeResources} or {@link Optional#empty()} */ public ComputeResources getComputeResources() { return this.computeResources; } /** * Get any image information associated by default with this command. * * @return The {@link Image} metadata as unmodifiable map. Any attempt to modify will throw an exception */ public Map<String, Image> getImages() { return this.images; } }
2,172
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommandRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * Fields representing all the values users can set when creating a new Command resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = CommandRequest.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class CommandRequest extends CommonRequestImpl { @Valid private final CommandMetadata metadata; @NotEmpty(message = "At least one executable entry is required") private final List<@Size(max = 255, message = "Executable elements can only be 255 characters") String> executable; private final List<Criterion> clusterCriteria; private final ComputeResources computeResources; private final Map<String, Image> images; private CommandRequest(final Builder builder) { super(builder); this.metadata = builder.bMetadata; this.executable = Collections.unmodifiableList(new ArrayList<>(builder.bExecutable)); this.clusterCriteria = Collections.unmodifiableList(new ArrayList<>(builder.bClusterCriteria)); this.computeResources = builder.bComputeResources; this.images = Collections.unmodifiableMap(new HashMap<>(builder.bImages)); } /** * Get the executable elements (generally a binary followed optionally by default arguments) that should be used * with this command when executing a job. * * @return The executable arguments as an immutable list. Any attempt to modify will throw an exception */ public List<String> getExecutable() { return this.executable; } /** * Get the ordered list of {@link Criterion} for this command to resolve clusters are runtime. * * @return The ordered list of {@link Criterion} as an immutable list. Any attempt to modify will throw an exception */ public List<Criterion> getClusterCriteria() { return this.clusterCriteria; } /** * Get any default compute resources that were requested for this command. * * @return The {@link ComputeResources} or {@link Optional#empty()} */ public Optional<ComputeResources> getComputeResources() { return Optional.ofNullable(this.computeResources); } /** * Get any image information associated by default with this command. * * @return The map of image domain name to {@link Image} metadata as unmodifiable map. Any attempt to modify * will throw an exception */ public Map<String, Image> getImages() { return this.images; } /** * Builder for a V4 Command Request. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonRequestImpl.Builder<Builder> { private final CommandMetadata bMetadata; private final List<String> bExecutable; private final List<Criterion> bClusterCriteria; private ComputeResources bComputeResources; private Map<String, Image> bImages; /** * Constructor which has required fields. * * @param metadata The user supplied metadata about a command resource * @param executable The executable arguments to use on job process launch. Typically the binary path followed * by optional default parameters for that given binary. Must have at least one. Blanks will * be removed */ @JsonCreator public Builder( @JsonProperty(value = "metadata", required = true) final CommandMetadata metadata, @JsonProperty(value = "executable", required = true) final List<String> executable ) { super(); this.bClusterCriteria = new ArrayList<>(); this.bMetadata = metadata; this.bExecutable = executable .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()); this.bImages = new HashMap<>(); } /** * Set the ordered list of {@link Criterion} that should be used to resolve which clusters this command * can run on at any given time. * * @param clusterCriteria The {@link Criterion} in priority order * @return The builder */ public Builder withClusterCriteria(@Nullable final List<Criterion> clusterCriteria) { this.bClusterCriteria.clear(); if (clusterCriteria != null) { this.bClusterCriteria.addAll(clusterCriteria); } return this; } /** * Set any default compute resources that should be used if this command is selected. * * @param computeResources The {@link ComputeResources} or {@link Optional#empty()} * @return This {@link Builder} instance */ public Builder withComputeResources(@Nullable final ComputeResources computeResources) { this.bComputeResources = computeResources; return this; } /** * Set any default image metadata that should be used if this command is selected. * * @param images The {@link Image}'s or {@literal null} * @return This {@link Builder} instance */ public Builder withImages(@Nullable final Map<String, Image> images) { this.bImages.clear(); if (images != null) { this.bImages.putAll(images); } return this; } /** * Build a new CommandRequest instance. * * @return The immutable command request */ public CommandRequest build() { return new CommandRequest(this); } } }
2,173
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/Cluster.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.Valid; import java.time.Instant; /** * An immutable V4 Cluster resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) public class Cluster extends CommonResource { @Valid private final ClusterMetadata metadata; /** * Constructor. * * @param id The unique identifier of this cluster * @param created The time this cluster was created in the system * @param updated The last time this cluster was updated in the system * @param resources The execution resources associated with this cluster * @param metadata The metadata associated with this cluster */ @JsonCreator public Cluster( @JsonProperty(value = "id", required = true) final String id, @JsonProperty(value = "created", required = true) final Instant created, @JsonProperty(value = "updated", required = true) final Instant updated, @JsonProperty(value = "resources") @Nullable final ExecutionEnvironment resources, @JsonProperty(value = "metadata", required = true) final ClusterMetadata metadata ) { super(id, created, updated, resources); this.metadata = metadata; } }
2,174
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobRequestMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.google.common.collect.ImmutableMap; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Map; import java.util.Optional; /** * Metadata gathered by the system as part of any {@link JobRequest}. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(doNotUseGetters = true) @EqualsAndHashCode(doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class JobRequestMetadata implements Serializable { private static final long serialVersionUID = -8265590545951599460L; private final boolean api; private final ApiClientMetadata apiClientMetadata; private final AgentClientMetadata agentClientMetadata; @Min(0) private final int numAttachments; @Min(0) private final long totalSizeOfAttachments; @NotNull private final Map<String, String> requestHeaders; /** * Constructor. One of {@literal apiClientMetadata} or {@literal agentClientMetadata} is required. Both cannot be * present. * * @param apiClientMetadata The metadata about the client if this request was received via API * @param agentClientMetadata The metadata about the client if this request was received from the Agent * @param numAttachments The number of attachments that came with this job request * @param totalSizeOfAttachments The total size of the attachments that came with this job request * @param requestHeaders The map of HTTP headers (filtered upstream) if this request was received via API * @throws IllegalArgumentException If both {@literal apiClientMetadata} and {@literal agentClientMetadata} are * missing or both are present */ public JobRequestMetadata( @Nullable final ApiClientMetadata apiClientMetadata, @Nullable final AgentClientMetadata agentClientMetadata, final int numAttachments, final long totalSizeOfAttachments, @Nullable final Map<String, String> requestHeaders ) throws IllegalArgumentException { if (apiClientMetadata == null && agentClientMetadata == null) { throw new IllegalArgumentException( "Both apiClientMetadata and agentClientMetadata are missing. One is required." ); } if (apiClientMetadata != null && agentClientMetadata != null) { throw new IllegalArgumentException( "Both apiClientMetadata and agentClientMetadata are present. Only one should be present" ); } this.api = apiClientMetadata != null; this.apiClientMetadata = apiClientMetadata; this.agentClientMetadata = agentClientMetadata; this.numAttachments = Math.max(numAttachments, 0); this.totalSizeOfAttachments = Math.max(totalSizeOfAttachments, 0L); this.requestHeaders = requestHeaders != null ? ImmutableMap.copyOf(requestHeaders) : ImmutableMap.of(); } /** * If the job request was sent via API this field will be populated. * * @return The API client metadata wrapped in an {@link Optional} */ public Optional<ApiClientMetadata> getApiClientMetadata() { return Optional.ofNullable(this.apiClientMetadata); } /** * If the job request was sent via the Agent this field will be populated. * * @return The Agent client metadata wrapped in an {@link Optional} */ public Optional<AgentClientMetadata> getAgentClientMetadata() { return Optional.ofNullable(this.agentClientMetadata); } }
2,175
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobEnvironmentRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Fields that allow manipulation of the Genie job execution container environment. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) @JsonDeserialize(builder = JobEnvironmentRequest.Builder.class) public class JobEnvironmentRequest implements Serializable { private static final long serialVersionUID = -1782447793634908168L; private final Map< @NotBlank(message = "Environment variable key can't be blank") @Size(max = 255, message = "Max environment variable name length is 255 characters") String, @NotNull(message = "Environment variable value can't be null") @Size(max = 1024, message = "Max environment variable value length is 1024 characters") String> requestedEnvironmentVariables; private final JsonNode ext; private final ComputeResources requestedComputeResources; private final Map<String, Image> requestedImages; private JobEnvironmentRequest(final Builder builder) { this.requestedEnvironmentVariables = Collections.unmodifiableMap( new HashMap<>(builder.bRequestedEnvironmentVariables) ); this.ext = builder.bExt; this.requestedComputeResources = builder.bRequestedComputeResources; this.requestedImages = Collections.unmodifiableMap(new HashMap<>(builder.bRequestedImages)); } /** * Get the environment variables requested by the user to be added to the job runtime. * * @return The environment variables backed by an immutable map. Any attempt to modify with throw exception */ public Map<String, String> getRequestedEnvironmentVariables() { return this.requestedEnvironmentVariables; } /** * Get the extension variables to the agent configuration as a JSON blob. * * @return The extension variables wrapped in an {@link Optional} */ public Optional<JsonNode> getExt() { return Optional.ofNullable(this.ext); } /** * Get the execution environment the user requested. * * @return The {@link ComputeResources} that were requested or {@link Optional#empty()} */ public ComputeResources getRequestedComputeResources() { return this.requestedComputeResources; } /** * Get the requested image metadata the user entered. * * @return The {@link Image} data in an immutable map. */ public Map<String, Image> getRequestedImages() { return this.requestedImages; } /** * Builder to create an immutable {@link JobEnvironmentRequest} instance. * * @author tgianos * @since 4.0.0 */ public static class Builder { private final Map<String, String> bRequestedEnvironmentVariables; private JsonNode bExt; private ComputeResources bRequestedComputeResources; private Map<String, Image> bRequestedImages; /** * Constructor. */ public Builder() { this.bRequestedEnvironmentVariables = new HashMap<>(); this.bRequestedComputeResources = new ComputeResources.Builder().build(); this.bRequestedImages = new HashMap<>(); } /** * Set any environment variables that the agent should add to the job runtime. * * @param requestedEnvironmentVariables Additional environment variables * @return The builder */ public Builder withRequestedEnvironmentVariables( @Nullable final Map<String, String> requestedEnvironmentVariables ) { this.bRequestedEnvironmentVariables.clear(); if (requestedEnvironmentVariables != null) { this.bRequestedEnvironmentVariables.putAll(requestedEnvironmentVariables); } return this; } /** * Set the extension configuration for the agent. This is generally used for specific implementations of the * job launcher e.g. on Titus or local docker etc. * * @param ext The extension configuration which is effectively a DSL per job launch implementation * @return The builder */ public Builder withExt(@Nullable final JsonNode ext) { this.bExt = ext; return this; } /** * Set the computation resources the job should run with. * * @param requestedComputeResources The {@link ComputeResources} * @return This {@link Builder} instance */ public Builder withRequestedComputeResources(final ComputeResources requestedComputeResources) { this.bRequestedComputeResources = requestedComputeResources; return this; } /** * Set the images the job should run with. * * @param requestedImages The {@link Image} map * @return This {@link Builder} instance */ public Builder withRequestedImages(final Map<String, Image> requestedImages) { this.bRequestedImages.clear(); this.bRequestedImages.putAll(requestedImages); return this; } /** * Build a new immutable instance of an {@link JobEnvironmentRequest}. * * @return An instance containing the fields set in this builder */ public JobEnvironmentRequest build() { return new JobEnvironmentRequest(this); } } }
2,176
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.google.common.collect.ImmutableList; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.List; import java.util.stream.Collectors; /** * All details a user will provide to Genie in order to run a job. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class JobRequest extends CommonRequestImpl implements AgentJobRequest, ApiJobRequest { private final ImmutableList< @NotBlank(message = "A command argument shouldn't be a blank string") @Size( max = 10_000, message = "Max length of an individual command line argument is 10,000 characters" ) String> commandArgs; @Valid private final JobMetadata metadata; @Valid private final ExecutionResourceCriteria criteria; @Valid private final JobEnvironmentRequest requestedJobEnvironment; @Valid private final AgentConfigRequest requestedAgentConfig; JobRequest(final AgentJobRequest.Builder builder) { this( builder.getBRequestedId(), builder.getBResources(), builder.getBCommandArgs(), builder.getBMetadata(), builder.getBCriteria(), null, builder.getBRequestedAgentConfig() ); } JobRequest(final ApiJobRequest.Builder builder) { this( builder.getBRequestedId(), builder.getBResources(), builder.getBCommandArgs(), builder.getBMetadata(), builder.getBCriteria(), builder.getBRequestedJobEnvironment(), builder.getBRequestedAgentConfig() ); } /** * Constructor. * * @param requestedId The requested id of the job if one was provided by the user * @param resources The execution resources (if any) provided by the user * @param commandArgs Any command args provided by the user * @param metadata Any metadata related to the job provided by the user * @param criteria The criteria used by the server to determine execution resources * (cluster, command, etc) * @param requestedJobEnvironment The optional job environment request parameters * @param requestedAgentConfig The optional configuration options for the Genie Agent */ public JobRequest( @Nullable final String requestedId, @Nullable final ExecutionEnvironment resources, @Nullable final List<String> commandArgs, final JobMetadata metadata, final ExecutionResourceCriteria criteria, @Nullable final JobEnvironmentRequest requestedJobEnvironment, @Nullable final AgentConfigRequest requestedAgentConfig ) { super(requestedId, resources); this.commandArgs = commandArgs == null ? ImmutableList.of() : ImmutableList.copyOf( commandArgs .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()) ); this.metadata = metadata; this.criteria = criteria; this.requestedJobEnvironment = requestedJobEnvironment == null ? new JobEnvironmentRequest.Builder().build() : requestedJobEnvironment; this.requestedAgentConfig = requestedAgentConfig == null ? new AgentConfigRequest.Builder().build() : requestedAgentConfig; } /** * {@inheritDoc} */ @Override public List<String> getCommandArgs() { return this.commandArgs; } }
2,177
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ApplicationRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.validation.Valid; /** * Fields representing all the values users can set when creating a new Application resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = ApplicationRequest.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class ApplicationRequest extends CommonRequestImpl { @Valid private final ApplicationMetadata metadata; private ApplicationRequest(final Builder builder) { super(builder); this.metadata = builder.bMetadata; } /** * Builder for a V4 Application Request. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonRequestImpl.Builder<Builder> { private final ApplicationMetadata bMetadata; /** * Constructor which has required fields. * * @param metadata The user supplied metadata about an application resource */ @JsonCreator public Builder(@JsonProperty(value = "metadata", required = true) final ApplicationMetadata metadata) { super(); this.bMetadata = metadata; } /** * Build a new ApplicationRequest instance. * * @return The immutable application request */ public ApplicationRequest build() { return new ApplicationRequest(this); } } }
2,178
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ExecutionEnvironment.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Elements that should be brought into an execution environment for a given resource (job, cluster, etc). * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ExecutionEnvironment implements Serializable { private static final long serialVersionUID = 4614789276383154791L; private final ImmutableSet< @NotEmpty(message = "The config file name can't be empty") @Size(max = 1024, message = "Config file name is longer than 1024 characters") String> configs; private final ImmutableSet< @NotEmpty(message = "The dependency file name can't be empty") @Size(max = 1024, message = "Dependency file is longer than 1024 characters") String> dependencies; @Size(max = 1024, message = "Max length of the setup file name is 1024 characters") private final String setupFile; /** * Constructor. * * @param configs Any configuration files needed for a resource at execution time. 1024 characters max for * each. Optional. Any blanks will be removed * @param dependencies Any dependency files needed for a resource at execution time. 1024 characters max for each. * Optional. Any blanks will be removed * @param setupFile Any file that should be run to setup a resource at execution time. 1024 characters max. * Optional */ @JsonCreator public ExecutionEnvironment( @JsonProperty("configs") @Nullable final Set<String> configs, @JsonProperty("dependencies") @Nullable final Set<String> dependencies, @JsonProperty("setupFile") @Nullable final String setupFile ) { this.configs = configs == null ? ImmutableSet.of() : ImmutableSet.copyOf( configs .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toSet()) ); this.dependencies = dependencies == null ? ImmutableSet.of() : ImmutableSet.copyOf( dependencies .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toSet()) ); this.setupFile = StringUtils.isBlank(setupFile) ? null : setupFile; } /** * Get the configuration files needed at runtime. The returned set will be immutable and any attempt to modify will * throw an exception. * * @return The set of setup file locations. */ public Set<String> getConfigs() { return this.configs; } /** * Get the dependency files needed at runtime. The returned set will be immutable and any attempt to modify will * throw an exception. * * @return The set of dependency file locations. */ public Set<String> getDependencies() { return this.dependencies; } /** * Get the setup file location if there is one. * * @return Setup file location wrapped in an {@link Optional} */ public Optional<String> getSetupFile() { return Optional.ofNullable(this.setupFile); } }
2,179
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobStatus.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.google.common.collect.Sets; import lombok.Getter; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; /** * Possible statuses for a Job. * * @author tgianos * @since 4.0.0 */ @Getter public enum JobStatus { /** * The id of the job has been reserved. */ RESERVED(true, true, false), /** * The job specification has been resolved. */ RESOLVED(true, false, true), /** * The job has been accepted by the system via the REST API. */ ACCEPTED(true, false, true), /** * The job has been claimed by a running agent. */ CLAIMED(true, false, false), /** * Job has been initialized, but not running yet. */ INIT(true, false, false), /** * Job is now running. */ RUNNING(true, false, false), /** * Job has finished executing, and is successful. */ SUCCEEDED(false, false, false), /** * Job has been killed. */ KILLED(false, false, false), /** * Job failed. */ FAILED(false, false, false), /** * Job cannot be run due to invalid criteria. */ INVALID(false, false, false); private static final Set<JobStatus> ACTIVE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isActive).collect(Collectors.toSet()) ); private static final Set<JobStatus> FINISHED_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isFinished).collect(Collectors.toSet()) ); private static final Set<JobStatus> RESOLVABLE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isResolvable).collect(Collectors.toSet()) ); private static final Set<JobStatus> CLAIMABLE_STATUSES = Collections.unmodifiableSet( Arrays.stream(JobStatus.values()).filter(JobStatus::isClaimable).collect(Collectors.toSet()) ); private static final Set<JobStatus> BEFORE_CLAIMED_STATUSES = Collections.unmodifiableSet( Sets.newHashSet(RESERVED, RESOLVED, ACCEPTED) ); private final boolean active; private final boolean resolvable; private final boolean claimable; /** * Constructor. * * @param active whether this status should be considered active or not * @param resolvable whether this status should be considered as a job that is valid to have a job specification * resolved or not * @param claimable Whether this status should be considered as a job that is valid to be claimed by an agent or * not */ JobStatus(final boolean active, final boolean resolvable, final boolean claimable) { this.active = active; this.resolvable = resolvable; this.claimable = claimable; } /** * Get an unmodifiable set of all the statuses that make up a job being considered active. * * @return Unmodifiable set of all active statuses */ public static Set<JobStatus> getActiveStatuses() { return ACTIVE_STATUSES; } /** * Get an unmodifiable set of all the statuses that come before CLAIMED. * * @return Unmodifiable set of all statuses */ public static Set<JobStatus> getStatusesBeforeClaimed() { return BEFORE_CLAIMED_STATUSES; } /** * Get an unmodifiable set of all the statuses that make up a job being considered finished. * * @return Unmodifiable set of all finished statuses */ public static Set<JobStatus> getFinishedStatuses() { return FINISHED_STATUSES; } /** * Get an unmodifiable set of all the statuses from which a job can be marked resolved. * * @return Unmodifiable set of all resolvable statuses */ public static Set<JobStatus> getResolvableStatuses() { return RESOLVABLE_STATUSES; } /** * Get an unmodifiable set of all the statuses from which a job can be marked claimed. * * @return Unmodifiable set of all claimable statuses */ public static Set<JobStatus> getClaimableStatuses() { return CLAIMABLE_STATUSES; } /** * Check whether the job is no longer running. * * @return True if the job is no longer processing for one reason or another. */ public boolean isFinished() { return !this.active; } }
2,180
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/JobMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.Email; import javax.validation.constraints.Size; import java.util.Optional; /** * Metadata supplied by a user for a job. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = JobMetadata.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class JobMetadata extends CommonMetadata { static final String DEFAULT_VERSION = "0.1"; @Size(max = 255, message = "Max length of the group is 255 characters") private final String group; @Size(max = 255, message = "Max length of the email 255 characters") @Email(message = "Must be a valid email address") private final String email; private final String grouping; private final String groupingInstance; private JobMetadata(final Builder builder) { super(builder); this.group = builder.bGroup; this.email = builder.bEmail; this.grouping = builder.bGrouping; this.groupingInstance = builder.bGroupingInstance; } /** * Get the group the user should is a member of as an {@link Optional}. * * @return The group as an optional */ public Optional<String> getGroup() { return Optional.ofNullable(this.group); } /** * Get the email for the user if there is one as an {@link Optional}. * * @return The email address as an Optional */ public Optional<String> getEmail() { return Optional.ofNullable(this.email); } /** * Get the grouping for this job if there currently is one as an {@link Optional}. * * @return The grouping */ public Optional<String> getGrouping() { return Optional.ofNullable(this.grouping); } /** * Get the grouping instance for this job if there currently is one as an {@link Optional}. * * @return The grouping instance */ public Optional<String> getGroupingInstance() { return Optional.ofNullable(this.groupingInstance); } /** * A builder to create job user metadata instances. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonMetadata.Builder<Builder> { private String bGroup; private String bEmail; private String bGrouping; private String bGroupingInstance; /** * Constructor which has required fields. * * @param name The name to use for the job * @param user The user to use for the Job * @param version The version of the job */ @JsonCreator public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version ) { super(name, user, version); } /** * Constructor which will set a default version of 0.1. * * @param name The name to use for the job * @param user The user to use for the job */ public Builder(final String name, final String user) { this(name, user, DEFAULT_VERSION); } /** * Set the group for the job. * * @param group The group * @return The builder */ public Builder withGroup(@Nullable final String group) { this.bGroup = StringUtils.isBlank(group) ? null : group; return this; } /** * Set the email to use for alerting of job completion. If no alert desired leave blank. * * @param email the email address to use * @return The builder */ public Builder withEmail(@Nullable final String email) { this.bEmail = StringUtils.isBlank(email) ? null : email; return this; } /** * Set the grouping to use for this job. * * @param grouping The grouping * @return The builder * @since 3.3.0 */ public Builder withGrouping(@Nullable final String grouping) { this.bGrouping = StringUtils.isBlank(grouping) ? null : grouping; return this; } /** * Set the grouping instance to use for this job. * * @param groupingInstance The grouping instance * @return The builder * @since 3.3.0 */ public Builder withGroupingInstance(@Nullable final String groupingInstance) { this.bGroupingInstance = StringUtils.isBlank(groupingInstance) ? null : groupingInstance; return this; } /** * Build the job user metadata instance. * * @return Create the final read-only JobMetadata instance */ public JobMetadata build() { return new JobMetadata(this); } } }
2,181
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/AgentJobRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.Lists; import lombok.AccessLevel; import lombok.Getter; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import java.util.List; /** * The builder and methods available for a request generated by a Genie agent typically from the command arguments. * * @author tgianos * @since 4.0.0 */ @JsonDeserialize(builder = AgentJobRequest.Builder.class) public interface AgentJobRequest extends CommonRequest { /** * Get the command arguments a user has requested be appended to a command executable for their job. * * @return The command arguments as an immutable list. Any attempt to modify will throw exception */ List<String> getCommandArgs(); /** * Get the metadata a user has supplied for the job including things like name, tags, etc. * * @return The metadata */ JobMetadata getMetadata(); /** * The resource criteria that was supplied for the job. * * @return The criteria used to select the cluster, command and optionally applications for the job */ ExecutionResourceCriteria getCriteria(); /** * Get the requested agent configuration. * * @return The requested agent configuration parameters */ AgentConfigRequest getRequestedAgentConfig(); /** * Builder for a V4 Job Request. * * @author tgianos * @since 4.0.0 */ @Getter(AccessLevel.PACKAGE) class Builder extends CommonRequestImpl.Builder<AgentJobRequest.Builder> { private final JobMetadata bMetadata; private final ExecutionResourceCriteria bCriteria; private final AgentConfigRequest bRequestedAgentConfig; private final List<String> bCommandArgs = Lists.newArrayList(); /** * Constructor with required parameters. * * @param metadata All user supplied metadata * @param criteria All user supplied execution criteria * @param requestedAgentConfig The requested configuration of the Genie agent */ @JsonCreator public Builder( @JsonProperty(value = "metadata", required = true) final JobMetadata metadata, @JsonProperty(value = "criteria", required = true) final ExecutionResourceCriteria criteria, @JsonProperty( value = "requestedAgentConfig", required = true ) final AgentConfigRequest requestedAgentConfig ) { super(); this.bMetadata = metadata; this.bCriteria = criteria; this.bRequestedAgentConfig = requestedAgentConfig; } /** * Set the ordered list of command line arguments to append to the command executable at runtime. * * @param commandArgs The arguments in the order they should be placed on the command line. Maximum of 10,000 * characters per argument. Blank strings are removed * @return The builder */ public Builder withCommandArgs(@Nullable final List<String> commandArgs) { this.bCommandArgs.clear(); if (commandArgs != null) { commandArgs.stream().filter(StringUtils::isNotBlank).forEach(this.bCommandArgs::add); } return this; } /** * Build an immutable job request instance. * * @return An immutable representation of the user supplied information for a job request */ public AgentJobRequest build() { return new JobRequest(this); } } }
2,182
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ApplicationStatus.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; /** * The available statuses for applications. * * @author tgianos * @since 4.0.0 */ public enum ApplicationStatus { /** * Application is active, and in-use. */ ACTIVE, /** * Application is deprecated, and will be made inactive in the future. */ DEPRECATED, /** * Application is inactive, and not in-use. */ INACTIVE }
2,183
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ArchiveStatus.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; /** * Possible archival statuses for a Job. * * @author mprimi * @since 4.0.0 */ public enum ArchiveStatus { /** * Files will be uploaded after the job finishes. */ PENDING, /** * Files were archived successfully. */ ARCHIVED, /** * Archival of files failed, files are not archived. */ FAILED, /** * Archiving was disabled, files are not archived. */ DISABLED, /** * No files were archived because no files were created. * i.e., job never reached the point where a directory is created. */ NO_FILES, /** * Archive status is unknown. */ UNKNOWN, }
2,184
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/FinishedJob.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.google.common.collect.ImmutableList; import com.netflix.genie.common.internal.exceptions.unchecked.GenieInvalidStatusException; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.Size; import java.time.Instant; import java.util.List; import java.util.Optional; /** * DTO for a job that reached a final state. * * @author mprimi * @since 4.0.0 */ @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class FinishedJob extends CommonMetadata { @Getter @Size(max = 255, message = "Max length for the ID is 255 characters") private final String uniqueId; @Getter private final Instant created; @Getter private final JobStatus status; @Getter private final List<String> commandArgs; @Getter @Valid private final Criterion commandCriterion; @Getter private final List<@Valid Criterion> clusterCriteria; private final Instant started; private final Instant finished; private final String grouping; private final String groupingInstance; private final String statusMessage; private final Long requestedMemory; private final String requestApiClientHostname; private final String requestApiClientUserAgent; private final String requestAgentClientHostname; private final String requestAgentClientVersion; private final Integer numAttachments; private final Integer exitCode; private final String archiveLocation; private final Long memoryUsed; private final Command command; private final Cluster cluster; @Getter private final List<Application> applications; /** * Constructor. * * @param builder The builder containing the values to use. */ FinishedJob(final Builder builder) { super(builder); this.uniqueId = builder.bUniqueId; this.created = builder.bCreated; this.status = builder.bStatus; this.commandArgs = builder.bCommandArgs; this.commandCriterion = builder.bCommandCriterion; this.clusterCriteria = builder.bClusterCriteria; this.started = builder.bStarted; this.finished = builder.bFinished; this.grouping = builder.bGrouping; this.groupingInstance = builder.bGroupingInstance; this.statusMessage = builder.bStatusMessage; this.requestedMemory = builder.bRequestedMemory; this.requestApiClientHostname = builder.bRequestApiClientHostname; this.requestApiClientUserAgent = builder.bRequestApiClientUserAgent; this.requestAgentClientHostname = builder.bRequestAgentClientHostname; this.requestAgentClientVersion = builder.bRequestAgentClientVersion; this.numAttachments = builder.bNumAttachments; this.exitCode = builder.bExitCode; this.archiveLocation = builder.bArchiveLocation; this.memoryUsed = builder.bMemoryUsed; this.command = builder.bCommand; this.cluster = builder.bCluster; this.applications = builder.bApplications; } /** * Getter for optional field. * * @return the job start timestamp, if present */ public Optional<Instant> getStarted() { return Optional.ofNullable(started); } /** * Getter for optional field. * * @return the job completion timestamp, if present */ public Optional<Instant> getFinished() { return Optional.ofNullable(finished); } /** * Getter for optional field. * * @return the job grouping, if present */ public Optional<String> getGrouping() { return Optional.ofNullable(grouping); } /** * Getter for optional field. * * @return the job grouping instance, if present */ public Optional<String> getGroupingInstance() { return Optional.ofNullable(groupingInstance); } /** * Getter for optional field. * * @return the job final status message, if present */ public Optional<String> getStatusMessage() { return Optional.ofNullable(statusMessage); } /** * Getter for optional field. * * @return the job requested memory, if present */ public Optional<Long> getRequestedMemory() { return Optional.ofNullable(requestedMemory); } /** * Getter for optional field. * * @return the requesting client hostname, if present */ public Optional<String> getRequestApiClientHostname() { return Optional.ofNullable(requestApiClientHostname); } /** * Getter for optional field. * * @return the requesting client user-agent, if present */ public Optional<String> getRequestApiClientUserAgent() { return Optional.ofNullable(requestApiClientUserAgent); } /** * Getter for optional field. * * @return the executing agent hostname, if present */ public Optional<String> getRequestAgentClientHostname() { return Optional.ofNullable(requestAgentClientHostname); } /** * Getter for optional field. * * @return the executing agent version, if present */ public Optional<String> getRequestAgentClientVersion() { return Optional.ofNullable(requestAgentClientVersion); } /** * Getter for optional field. * * @return the number of job attachments, if present */ public Optional<Integer> getNumAttachments() { return Optional.ofNullable(numAttachments); } /** * Getter for optional field. * * @return the job process exit code, if present */ public Optional<Integer> getExitCode() { return Optional.ofNullable(exitCode); } /** * Getter for optional field. * * @return the job outputs archive location, if present */ public Optional<String> getArchiveLocation() { return Optional.ofNullable(archiveLocation); } /** * Getter for optional field. * * @return the job used memory, if present */ public Optional<Long> getMemoryUsed() { return Optional.ofNullable(memoryUsed); } /** * Getter for optional field. * * @return the job resolved command, if present */ public Optional<Command> getCommand() { return Optional.ofNullable(command); } /** * Getter for optional field. * * @return the job resolved cluster, if present */ public Optional<Cluster> getCluster() { return Optional.ofNullable(cluster); } /** * Builder. */ public static class Builder extends CommonMetadata.Builder<Builder> { private final String bUniqueId; private final Instant bCreated; private final JobStatus bStatus; private final List<String> bCommandArgs; private final Criterion bCommandCriterion; private final List<Criterion> bClusterCriteria; private Instant bStarted; private Instant bFinished; private String bGrouping; private String bGroupingInstance; private String bStatusMessage; private Long bRequestedMemory; private String bRequestApiClientHostname; private String bRequestApiClientUserAgent; private String bRequestAgentClientHostname; private String bRequestAgentClientVersion; private Integer bNumAttachments; private Integer bExitCode; private String bArchiveLocation; private Long bMemoryUsed; private Command bCommand; private Cluster bCluster; private List<Application> bApplications; /** * Constructor with required fields. * * @param uniqueId job id * @param name job name * @param user job user * @param version job version * @param created job creation timestamp * @param status job status * @param commandArgs job command arguments * @param commandCriterion job command criterion * @param clusterCriteria job cluster criteria */ public Builder( final String uniqueId, final String name, final String user, final String version, final Instant created, final JobStatus status, final List<String> commandArgs, final Criterion commandCriterion, final List<Criterion> clusterCriteria ) { super(name, user, version); this.bUniqueId = uniqueId; this.bCreated = created; this.bStatus = status; this.bCommandArgs = ImmutableList.copyOf(commandArgs); this.bCommandCriterion = commandCriterion; this.bClusterCriteria = ImmutableList.copyOf(clusterCriteria); } /** * Build the DTO. * * @return Create the final read-only FinishedJob instance. * @throws GenieInvalidStatusException if the status is not final */ public FinishedJob build() { if (!this.bStatus.isFinished()) { throw new GenieInvalidStatusException("Status is not final: " + bStatus.name()); } return new FinishedJob(this); } /** * Setter for optional field. * * @param started start timestamp * @return the builder */ public Builder withStarted(@Nullable final Instant started) { this.bStarted = started; return this; } /** * Setter for optional field. * * @param finished the finish timestamp * @return the builder */ public Builder withFinished(@Nullable final Instant finished) { this.bFinished = finished; return this; } /** * Setter for optional field. * * @param grouping the job grouping * @return the builder */ public Builder withGrouping(@Nullable final String grouping) { this.bGrouping = grouping; return this; } /** * Setter for optional field. * * @param groupingInstance the job grouping instance * @return the builder */ public Builder withGroupingInstance(@Nullable final String groupingInstance) { this.bGroupingInstance = groupingInstance; return this; } /** * Setter for optional field. * * @param statusMessage the job final status message * @return the builder */ public Builder withStatusMessage(@Nullable final String statusMessage) { this.bStatusMessage = statusMessage; return this; } /** * Setter for optional field. * * @param requestedMemory the amount of memory requested * @return the builder */ public Builder withRequestedMemory(@Nullable final Long requestedMemory) { this.bRequestedMemory = requestedMemory; return this; } /** * Setter for optional field. * * @param requestApiClientHostname the hostname of the client submitting the job via API * @return the builder */ public Builder withRequestApiClientHostname(@Nullable final String requestApiClientHostname) { this.bRequestApiClientHostname = requestApiClientHostname; return this; } /** * Setter for optional field. * * @param requestApiClientUserAgent the user-agent string of the client submitting the job via API * @return the builder */ public Builder withRequestApiClientUserAgent(@Nullable final String requestApiClientUserAgent) { this.bRequestApiClientUserAgent = requestApiClientUserAgent; return this; } /** * Setter for optional field. * * @param requestAgentClientHostname the hostname where the agent executing the job is running * @return the builder */ public Builder withRequestAgentClientHostname(@Nullable final String requestAgentClientHostname) { this.bRequestAgentClientHostname = requestAgentClientHostname; return this; } /** * Setter for optional field. * * @param requestAgentClientVersion the version of the agent executing the job * @return the builder */ public Builder withRequestAgentClientVersion(@Nullable final String requestAgentClientVersion) { this.bRequestAgentClientVersion = requestAgentClientVersion; return this; } /** * Setter for optional field. * * @param numAttachments the number of attachments * @return the builder */ public Builder withNumAttachments(@Nullable final Integer numAttachments) { this.bNumAttachments = numAttachments; return this; } /** * Setter for optional field. * * @param exitCode the exit code * @return the builder */ public Builder withExitCode(@Nullable final Integer exitCode) { this.bExitCode = exitCode; return this; } /** * Setter for optional field. * * @param archiveLocation the archive location * @return the builder */ public Builder withArchiveLocation(@Nullable final String archiveLocation) { this.bArchiveLocation = archiveLocation; return this; } /** * Setter for optional field. * * @param memoryUsed the memory allocated to the job * @return the builder */ public Builder withMemoryUsed(@Nullable final Long memoryUsed) { this.bMemoryUsed = memoryUsed; return this; } /** * Setter for optional field. * * @param command the resolved command for this job * @return the builder */ public Builder withCommand(@Nullable final Command command) { this.bCommand = command; return this; } /** * Setter for optional field. * * @param cluster the resolved cluster for this job * @return the builder */ public Builder withCluster(@Nullable final Cluster cluster) { this.bCluster = cluster; return this; } /** * Setter for optional field. * * @param applications the resolved list of applications for this command * @return the builder */ public Builder withApplications(@Nullable final List<Application> applications) { this.bApplications = applications == null ? ImmutableList.of() : ImmutableList.copyOf(applications); return this; } } }
2,185
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ClusterRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.validation.Valid; /** * Fields representing all the values users can set when creating a new Cluster resource. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @ToString(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = ClusterRequest.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class ClusterRequest extends CommonRequestImpl { @Valid private final ClusterMetadata metadata; private ClusterRequest(final Builder builder) { super(builder); this.metadata = builder.bMetadata; } /** * Builder for a V4 Cluster Request. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonRequestImpl.Builder<Builder> { private final ClusterMetadata bMetadata; /** * Constructor which has required fields. * * @param metadata The user supplied metadata about a cluster resource */ @JsonCreator public Builder(@JsonProperty(value = "metadata", required = true) final ClusterMetadata metadata) { super(); this.bMetadata = metadata; } /** * Build a new ClusterRequest instance. * * @return The immutable cluster request */ public ClusterRequest build() { return new ClusterRequest(this); } } }
2,186
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ApiClientMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import java.util.Optional; /** * Data class to hold information about a Genie client whether it is an API client or an Agent. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class ApiClientMetadata extends ClientMetadata { private final String userAgent; /** * Constructor. * * @param hostname The hostname of the client that sent the API request * @param userAgent The user agent string */ public ApiClientMetadata(@Nullable final String hostname, @Nullable final String userAgent) { super(hostname); this.userAgent = userAgent; } /** * Get the user agent string for the client. * * @return The user agent string if there is one wrapped in an {@link Optional} */ public Optional<String> getUserAgent() { return Optional.ofNullable(this.userAgent); } }
2,187
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/CommonResource.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.time.Instant; /** * Fields common to every Genie v4 resource (cluster, command, etc). * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public abstract class CommonResource implements Serializable { private static final long serialVersionUID = -2939351280830204953L; @NotEmpty(message = "An id is required") @Size(max = 255, message = "Max length for the ID is 255 characters") private final String id; private final Instant created; private final Instant updated; private final ExecutionEnvironment resources; CommonResource( final String id, final Instant created, final Instant updated, @Nullable final ExecutionEnvironment resources ) { this.id = id; this.created = created; this.updated = updated; this.resources = resources == null ? new ExecutionEnvironment(null, null, null) : resources; } }
2,188
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/AgentConfigRequest.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.databind.JsonNode; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.annotation.Nullable; import javax.validation.constraints.Min; import java.io.File; import java.io.Serializable; import java.util.Optional; /** * Configuration options for the Genie agent. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(doNotUseGetters = true) @EqualsAndHashCode(doNotUseGetters = true) @SuppressWarnings("checkstyle:finalclass") public class AgentConfigRequest implements Serializable { private static final long serialVersionUID = 8222386837109375937L; private final boolean archivingDisabled; @Min(value = 1, message = "The timeout must be at least 1 second, preferably much more.") private final Integer timeoutRequested; private final boolean interactive; // TODO: Switch to Path private final File requestedJobDirectoryLocation; private final JsonNode ext; private AgentConfigRequest(final Builder builder) { this.archivingDisabled = builder.bArchivingDisabled; this.timeoutRequested = builder.bTimeoutRequested; this.interactive = builder.bInteractive; this.requestedJobDirectoryLocation = builder.bRequestedJobDirectoryLocation; this.ext = builder.bExt; } /** * Get the amount of time (in seconds) after the job starts that the agent should timeout and kill the job. * * @return The time in seconds if one was requested wrapped in an {@link Optional} */ public Optional<Integer> getTimeoutRequested() { return Optional.ofNullable(this.timeoutRequested); } /** * Get the location where the Agent should place the job directory when it runs. * * @return The directory location wrapped in an {@link Optional} */ public Optional<File> getRequestedJobDirectoryLocation() { return Optional.ofNullable(this.requestedJobDirectoryLocation); } /** * Get the extension variables to the agent configuration as a JSON blob. * * @return The extension variables wrapped in an {@link Optional} */ public Optional<JsonNode> getExt() { return Optional.ofNullable(this.ext); } /** * Builder to create an immutable {@link AgentConfigRequest} instance. * * @author tgianos * @since 4.0.0 */ public static class Builder { private boolean bArchivingDisabled; private Integer bTimeoutRequested; private boolean bInteractive; private File bRequestedJobDirectoryLocation; private JsonNode bExt; /** * Set whether the agent should or should not archive the job directory. * * @param archivingDisabled True if archiving should be disabled (not done) * @return The builder */ public Builder withArchivingDisabled(final boolean archivingDisabled) { this.bArchivingDisabled = archivingDisabled; return this; } /** * Set whether the agent should be run as an interactive job or not. * * @param interactive True if the agent should be configured to run an interactive job * @return The builder */ public Builder withInteractive(final boolean interactive) { this.bInteractive = interactive; return this; } /** * Set the amount of time (in seconds) from the job start time that the job should be killed by the agent due * to timeout. * * @param timeoutRequested The requested amount of time in seconds * @return the builder */ public Builder withTimeoutRequested(@Nullable final Integer timeoutRequested) { this.bTimeoutRequested = timeoutRequested; return this; } /** * Set the directory where the agent should put the job working directory. * * @param requestedJobDirectoryLocation The location * @return The builder */ @JsonSetter public Builder withRequestedJobDirectoryLocation(@Nullable final String requestedJobDirectoryLocation) { this.bRequestedJobDirectoryLocation = requestedJobDirectoryLocation == null ? null : new File(requestedJobDirectoryLocation); return this; } /** * Set the directory where the agent should put the job working directory. * * @param requestedJobDirectoryLocation The location * @return The builder */ public Builder withRequestedJobDirectoryLocation(@Nullable final File requestedJobDirectoryLocation) { this.bRequestedJobDirectoryLocation = requestedJobDirectoryLocation; return this; } /** * Set the extension configuration for the agent. * * @param ext The extension configuration which is effectively a DSL per Agent implementation * @return The builder */ public Builder withExt(@Nullable final JsonNode ext) { this.bExt = ext; return this; } /** * Build a new immutable instance of an {@link AgentConfigRequest}. * * @return An instance containing the fields set in this builder */ public AgentConfigRequest build() { return new AgentConfigRequest(this); } } }
2,189
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ExecutionResourceCriteria.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.List; import java.util.stream.Collectors; /** * Container for various options for user supplying criteria for the execution environment of a job. * * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ExecutionResourceCriteria implements Serializable { private static final long serialVersionUID = 4888642026303173660L; @NotEmpty(message = "At least one cluster criterion is required") private final ImmutableList<@Valid Criterion> clusterCriteria; @NotNull(message = "Command criterion is required") @Valid private final Criterion commandCriterion; private final ImmutableList<String> applicationIds; /** * Constructor. * * @param clusterCriteria The ordered list of criteria used to find a cluster for job execution. Not null/empty. * @param commandCriterion The command criterion used to find a command to run on the cluster for job execution. * Not null. * @param applicationIds The ordered list of application ids to override the applications associated with * selected command for job execution. Optional. Any blanks will be removed */ @JsonCreator public ExecutionResourceCriteria( @JsonProperty(value = "clusterCriteria", required = true) final List<Criterion> clusterCriteria, @JsonProperty(value = "commandCriterion", required = true) final Criterion commandCriterion, @JsonProperty("applicationIds") @Nullable final List<String> applicationIds ) { this.clusterCriteria = ImmutableList.copyOf(clusterCriteria); this.commandCriterion = commandCriterion; this.applicationIds = applicationIds == null ? ImmutableList.of() : ImmutableList.copyOf( applicationIds .stream() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()) ); } /** * Get the ordered list of criteria the system should use to find a cluster for job execution. The underlying * implementation is immutable and any attempt to modify will throw an exception. * * @return The list of criterion in the order they should be evaluated along with supplied command criterion */ public List<Criterion> getClusterCriteria() { return this.clusterCriteria; } /** * Get the ordered list of ids the user desires to override the applications associated with selected command with. * This list is immutable and any attempt to modify will throw an exception. * * @return The ids in the order they should be setup by the execution module */ public List<String> getApplicationIds() { return this.applicationIds; } }
2,190
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ClusterMetadata.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import javax.validation.constraints.NotNull; /** * Metadata supplied by a user for a Cluster resource. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(callSuper = true, doNotUseGetters = true) @EqualsAndHashCode(callSuper = true, doNotUseGetters = true) @JsonDeserialize(builder = ClusterMetadata.Builder.class) @SuppressWarnings("checkstyle:finalclass") public class ClusterMetadata extends CommonMetadata { @NotNull(message = "A cluster status is required") private final ClusterStatus status; private ClusterMetadata(final Builder builder) { super(builder); this.status = builder.bStatus; } /** * A builder to create cluster user metadata instances. * * @author tgianos * @since 4.0.0 */ public static class Builder extends CommonMetadata.Builder<Builder> { private final ClusterStatus bStatus; /** * Constructor which has required fields. * * @param name The name to use for the cluster * @param user The user who owns the cluster * @param version The version of the cluster * @param status The status of the cluster */ @JsonCreator public Builder( @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "user", required = true) final String user, @JsonProperty(value = "version", required = true) final String version, @JsonProperty(value = "status", required = true) final ClusterStatus status ) { super(name, user, version); this.bStatus = status; } /** * Build the cluster metadata instance. * * @return Create the final read-only clusterMetadata instance */ public ClusterMetadata build() { return new ClusterMetadata(this); } } }
2,191
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/ResolvedResources.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableSet; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import java.util.Set; /** * Representing the result of resolving resources of type {@literal R} from a {@link Criterion}. * * @param <R> The type of the resource that was resolved * @author tgianos * @since 4.0.0 */ @Getter @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ResolvedResources<R> { private final Criterion criterion; private final ImmutableSet<R> resources; /** * Constructor. * * @param criterion The {@link Criterion} that was used to resolve {@literal resources} * @param resources The resources that were resolved based on the {@literal criterion} */ @JsonCreator public ResolvedResources( @JsonProperty(value = "criterion", required = true) final Criterion criterion, @JsonProperty(value = "resources", required = true) final Set<R> resources ) { this.criterion = criterion; this.resources = ImmutableSet.copyOf(resources); } /** * Get the resources that were resolved. * * @return The resolved resources as an immutable {@link Set}. Any attempt to modify will cause error. */ public Set<R> getResources() { return this.resources; } }
2,192
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/package-info.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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. * */ /** * DTOs shared between the Agent and the Server code base. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.dtos; import javax.annotation.ParametersAreNonnullByDefault;
2,193
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/DirectoryManifest.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tika.config.TikaConfig; import org.apache.tika.exception.TikaException; import org.apache.tika.io.TikaInputStream; import org.apache.tika.metadata.Metadata; import org.apache.tika.mime.MediaType; import javax.annotation.Nullable; import javax.validation.constraints.Min; import java.io.IOException; import java.io.InputStream; import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryStream; import java.nio.file.FileSystemLoopException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.util.Collection; import java.util.EnumSet; import java.util.Optional; import java.util.Set; /** * A manifest of all the files and subdirectories in a directory. * * @author tgianos * @since 4.0.0 */ @ToString(doNotUseGetters = true) @EqualsAndHashCode(doNotUseGetters = true) public class DirectoryManifest { private static final String ENTRIES_KEY = "entries"; private static final String EMPTY_STRING = ""; private final ImmutableMap<String, ManifestEntry> entries; private final ImmutableSet<ManifestEntry> files; private final ImmutableSet<ManifestEntry> directories; private final int numFiles; private final int numDirectories; private final long totalSizeOfFiles; private DirectoryManifest( final Path directory, final boolean calculateFileChecksums, final Filter filter ) throws IOException { // Walk the directory final ImmutableMap.Builder<String, ManifestEntry> builder = ImmutableMap.builder(); final ManifestVisitor manifestVisitor = new ManifestVisitor( directory, builder, calculateFileChecksums, filter ); final EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(directory, options, Integer.MAX_VALUE, manifestVisitor); this.entries = builder.build(); final ImmutableSet.Builder<ManifestEntry> filesBuilder = ImmutableSet.builder(); final ImmutableSet.Builder<ManifestEntry> directoriesBuilder = ImmutableSet.builder(); long sizeOfFiles = 0L; for (final ManifestEntry entry : this.entries.values()) { if (entry.isDirectory()) { directoriesBuilder.add(entry); } else { filesBuilder.add(entry); sizeOfFiles += entry.getSize(); } } this.totalSizeOfFiles = sizeOfFiles; this.directories = directoriesBuilder.build(); this.files = filesBuilder.build(); this.numDirectories = this.directories.size(); this.numFiles = this.files.size(); } /** * Create a manifest from an existing set of entries. Generally this should be used to regenerate an in memory * manifest instance from JSON. * * @param entries The entries in this manifest */ @JsonCreator public DirectoryManifest( @JsonProperty(value = ENTRIES_KEY, required = true) final Set<ManifestEntry> entries ) { final ImmutableMap.Builder<String, ManifestEntry> builder = ImmutableMap.builder(); final ImmutableSet.Builder<ManifestEntry> filesBuilder = ImmutableSet.builder(); final ImmutableSet.Builder<ManifestEntry> directoriesBuilder = ImmutableSet.builder(); long sizeOfFiles = 0L; for (final ManifestEntry entry : entries) { builder.put(entry.getPath(), entry); if (entry.isDirectory()) { directoriesBuilder.add(entry); } else { filesBuilder.add(entry); sizeOfFiles += entry.getSize(); } } this.entries = builder.build(); this.totalSizeOfFiles = sizeOfFiles; this.directories = directoriesBuilder.build(); this.files = filesBuilder.build(); this.numDirectories = this.directories.size(); this.numFiles = this.files.size(); } /** * Check whether an entry exists for the given path. * * @param path The path to check. Relative to the root of the original job directory. * @return {@code true} if an entry exists for this path */ public boolean hasEntry(final String path) { return this.entries.containsKey(path); } /** * Get the entry, if one exists, for the given path. * * @param path The path to get an entry for. Relative to the root of the original job directory. * @return The entry wrapped in an {@link Optional} or {@link Optional#empty()} if no entry exists */ @JsonIgnore public Optional<ManifestEntry> getEntry(final String path) { return Optional.ofNullable(this.entries.get(path)); } /** * A getter used to mask internal implementation for JSON serialization. * * @return All the entries as a collection. */ @JsonGetter(ENTRIES_KEY) Collection<ManifestEntry> getEntries() { return this.entries.values(); } /** * Get all the entries that are files for this manifest. * * @return All the file {@link ManifestEntry}'s as an immutable set. */ @JsonIgnore public Set<ManifestEntry> getFiles() { return this.files; } /** * Get all the entries that are directories for this manifest. * * @return All the directory {@link ManifestEntry}'s as an immutable set. */ @JsonIgnore public Set<ManifestEntry> getDirectories() { return this.directories; } /** * Get the total number of files in this manifest. * * @return The total number of files that are in this job directory */ @JsonIgnore public int getNumFiles() { return this.numFiles; } /** * Get the total number of directories in this manifest. * * @return The total number of sub directories that are in this job directory */ @JsonIgnore public int getNumDirectories() { return this.numDirectories; } /** * Get the total size of the files contained in this manifest. * * @return The total size (in bytes) of all the files in this job directory */ @JsonIgnore public long getTotalSizeOfFiles() { return this.totalSizeOfFiles; } /** * This interface defines a filter function used during creation of the manifest. * It can prune entire sub-trees of the directory, optionally including the directory itself, or skip individual * files. * The default implementation accepts all entries and filters none. */ public interface Filter { /** * Whether to include a given file in the manifest. * * @param filePath the file path * @param attrs the file attributes * @return true if the file should be included in the manifest, false if it should be excluded. */ default boolean includeFile(final Path filePath, BasicFileAttributes attrs) { return true; } /** * Whether to include a given directory in the manifest. If a directory is not included, all sub-directories * and files contained are also implicitly excluded. * * @param dirPath the directory path * @param attrs the directory attributes * @return true if the directory should be included in the manifest, false if it should be excluded. */ default boolean includeDirectory(final Path dirPath, BasicFileAttributes attrs) { return true; } /** * Whether to recurse into a given directory and add its contents to the manifest. Only evaluated if the * directory is not excluded. * * @param dirPath the directory path * @param attrs the directory attributes * @return true if the contents of the directory should be included in the manifest, false if they should be * excluded. */ default boolean walkDirectory(final Path dirPath, BasicFileAttributes attrs) { return true; } } /** * Factory that encapsulates directory manifest creation. */ public static class Factory { private static final Filter ACCEPT_ALL_FILTER = new DirectoryManifest.Filter() { }; private final Filter filter; /** * Constructor with no filters. */ public Factory() { this(ACCEPT_ALL_FILTER); } /** * Constructor with filter. * * @param filter the manifest filter */ public Factory(final Filter filter) { this.filter = filter; } /** * Create a manifest from the given job directory. * * @param directory The job directory to create a manifest from * @param includeChecksum Whether or not to calculate checksums for each file added to the manifest * @return a directory manifest * @throws IOException If there is an error reading the directory */ public DirectoryManifest getDirectoryManifest( final Path directory, final boolean includeChecksum ) throws IOException { return new DirectoryManifest(directory, includeChecksum, this.filter); } } @Slf4j private static class ManifestVisitor extends SimpleFileVisitor<Path> { private final Path root; private final ImmutableMap.Builder<String, ManifestEntry> builder; private final Metadata metadata; private final TikaConfig tikaConfig; private final boolean checksumFiles; private final Filter filter; ManifestVisitor( final Path root, final ImmutableMap.Builder<String, ManifestEntry> builder, final boolean checksumFiles, final Filter filter ) throws IOException { this.root = root; this.builder = builder; this.checksumFiles = checksumFiles; this.filter = filter; this.metadata = new Metadata(); try { this.tikaConfig = new TikaConfig(); } catch (final TikaException te) { log.error("Unable to create Tika Configuration due to error", te); throw new IOException(te); } } /** * {@inheritDoc} */ @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { final ManifestEntry entry = this.buildEntry(dir, attrs, true); if (this.filter.includeDirectory(dir, attrs)) { this.builder.put(entry.getPath(), entry); log.debug("Created manifest entry for directory {}", entry); if (this.filter.walkDirectory(dir, attrs)) { return FileVisitResult.CONTINUE; } } log.debug("Skipping directory: {}", dir.toAbsolutePath()); return FileVisitResult.SKIP_SUBTREE; } /** * {@inheritDoc} */ @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (this.filter.includeFile(file, attrs)) { final ManifestEntry entry = this.buildEntry(file, attrs, false); log.debug("Created manifest entry for file {}", entry); this.builder.put(entry.getPath(), entry); } else { log.debug("Skipped manifest entry for file {}", file.toAbsolutePath()); } return FileVisitResult.CONTINUE; } /** * {@inheritDoc} */ @Override public FileVisitResult visitFileFailed(final Path file, final IOException ioe) { if (ioe instanceof FileSystemLoopException) { log.warn("Detected file system cycle visiting while visiting {}. Skipping.", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof AccessDeniedException) { log.warn("Access denied for file {}. Skipping", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof NoSuchFileException) { log.warn("File or directory disappeared while visiting {}. Skipping", file); return FileVisitResult.SKIP_SUBTREE; } else { log.error("Got unknown error {} while visiting {}. Terminating visitor", ioe.getMessage(), file, ioe); // TODO: Not sure if we should do this or skip subtree or just continue and ignore it? return FileVisitResult.TERMINATE; } } @SuppressFBWarnings( value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "https://github.com/spotbugs/spotbugs/issues/756" ) private ManifestEntry buildEntry( final Path entry, final BasicFileAttributes attributes, final boolean directory ) throws IOException { final String path = this.root.relativize(entry).toString(); final Path fileName = entry.getFileName(); final String name = fileName == null ? EMPTY_STRING : fileName.toString(); final Instant lastModifiedTime = attributes.lastModifiedTime().toInstant(); final Instant lastAccessTime = attributes.lastAccessTime().toInstant(); final Instant creationTime = attributes.creationTime().toInstant(); final long size = attributes.size(); String md5 = null; String mimeType = null; if (!directory) { if (this.checksumFiles) { try (InputStream data = Files.newInputStream(entry, StandardOpenOption.READ)) { md5 = DigestUtils.md5Hex(data); } catch (final IOException ioe) { // For now MD5 isn't critical or required so we'll swallow errors here log.error("Unable to create MD5 for {} due to error", entry, ioe); } } mimeType = this.getMimeType(name, entry); } final Set<String> children = Sets.newHashSet(); if (directory) { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(entry)) { for (final Path child : directoryStream) { children.add(this.root.relativize(child).toString()); } } } String parent = null; if (StringUtils.isNotEmpty(path)) { // Not the root parent = this.root.relativize(entry.getParent()).toString(); } return new ManifestEntry( path, name, lastModifiedTime, lastAccessTime, creationTime, directory, size, md5, mimeType, parent, children ); } private String getMimeType(final String name, final Path path) { // TODO: Move configuration of special handling cases to external configuration for flexibility // probably a map of filename -> type or extension -> type or produced mime-type -> desired mime-type switch (name) { case "stdout": case "stderr": case "run": return MediaType.TEXT_PLAIN.toString(); default: try (TikaInputStream inputStream = TikaInputStream.get(path)) { return this.tikaConfig.getDetector().detect(inputStream, this.metadata).toString(); } catch (final IOException ioe) { log.error("Unable to detect mime type for {} due to error", path, ioe); return MediaType.OCTET_STREAM.toString(); } } } } /** * Representation of the metadata for a job file on a given underlying storage system. * * @author tgianos * @since 4.0.0 */ @Getter @ToString(doNotUseGetters = true) @EqualsAndHashCode(doNotUseGetters = true) public static class ManifestEntry { private final String path; private final String name; private final Instant lastModifiedTime; private final Instant lastAccessTime; private final Instant creationTime; private final boolean directory; @Min(value = 0L, message = "A file can't have a negative size") private final long size; private final String md5; private final String mimeType; private final String parent; private final Set<String> children; /** * Constructor. * * @param path The relative path to the entry from the root of the job directory * @param name The name of the entry * @param lastModifiedTime The time the entry was last modified * @param lastAccessTime The time the entry was last accessed * @param creationTime The time the entry was created * @param directory Whether this entry is a directory or not * @param size The current size of the entry within the storage system in bytes. Min 0 * @param md5 The md5 hex of the file contents if it's not a directory * @param mimeType The mime type of the file. Null if its a directory * @param parent Optional entry for the path of this entries parent relative to root * @param children The set of paths, from the root, representing children of this entry if any */ @JsonCreator public ManifestEntry( @JsonProperty(value = "path", required = true) final String path, @JsonProperty(value = "name", required = true) final String name, @JsonProperty(value = "lastModifiedTime", required = true) final Instant lastModifiedTime, @JsonProperty(value = "lastAccessTime", required = true) final Instant lastAccessTime, @JsonProperty(value = "creationTime", required = true) final Instant creationTime, @JsonProperty(value = "directory", required = true) final boolean directory, @JsonProperty(value = "size", required = true) final long size, @JsonProperty(value = "md5") @Nullable final String md5, @JsonProperty(value = "mimeType") @Nullable final String mimeType, @JsonProperty(value = "parent") @Nullable final String parent, @JsonProperty(value = "children", required = true) final Set<String> children ) { this.path = path; this.name = name; this.lastModifiedTime = lastModifiedTime; this.lastAccessTime = lastAccessTime; this.creationTime = creationTime; this.directory = directory; this.size = size; this.md5 = md5; this.mimeType = mimeType; this.parent = parent; this.children = ImmutableSet.copyOf(children); } /** * Get the MD5 hash of the file (as 32 hex characters) if it was calculated. * * @return The MD5 value or {@link Optional#empty()} */ public Optional<String> getMd5() { return Optional.ofNullable(this.md5); } /** * Get the mime type of this file if it was calculated. * * @return The mime type value or {@link Optional#empty()} */ public Optional<String> getMimeType() { return Optional.ofNullable(this.mimeType); } /** * Get the relative path from root of the parent of this entry if there was one. * There likely wouldn't be one for the root of the job directory. * * @return The relative path from root of the parent wrapped in an {@link Optional} */ public Optional<String> getParent() { return Optional.ofNullable(this.parent); } } }
2,194
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/converters/JobServiceProtoConverter.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos.converters; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.protobuf.Int32Value; import com.netflix.genie.common.external.util.GenieObjectMapper; import com.netflix.genie.common.internal.dtos.AgentClientMetadata; import com.netflix.genie.common.internal.dtos.AgentConfigRequest; import com.netflix.genie.common.internal.dtos.AgentJobRequest; import com.netflix.genie.common.internal.dtos.ArchiveStatus; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.common.internal.dtos.ExecutionEnvironment; import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria; import com.netflix.genie.common.internal.dtos.JobMetadata; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.dtos.JobSpecification; import com.netflix.genie.common.internal.dtos.JobStatus; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; import com.netflix.genie.proto.AgentConfig; import com.netflix.genie.proto.AgentMetadata; import com.netflix.genie.proto.ChangeJobArchiveStatusRequest; import com.netflix.genie.proto.ChangeJobStatusRequest; import com.netflix.genie.proto.ClaimJobRequest; import com.netflix.genie.proto.ConfigureRequest; import com.netflix.genie.proto.DryRunJobSpecificationRequest; import com.netflix.genie.proto.ExecutionResource; import com.netflix.genie.proto.GetJobStatusRequest; import com.netflix.genie.proto.HandshakeRequest; import com.netflix.genie.proto.JobSpecificationRequest; import com.netflix.genie.proto.JobSpecificationResponse; import com.netflix.genie.proto.ReserveJobIdRequest; import org.apache.commons.lang3.StringUtils; import javax.annotation.Nullable; import javax.validation.constraints.NotBlank; import java.io.File; import java.util.List; import java.util.stream.Collectors; /** * Converter of proto messages for the {@link com.netflix.genie.proto.JobServiceGrpc.JobServiceImplBase} service to * and from V4 DTO POJO's. * * @author tgianos * @see com.netflix.genie.common.internal.dtos * @see com.netflix.genie.proto * @since 4.0.0 */ public class JobServiceProtoConverter { /** * Convert a V4 Job Request DTO into a gRPC reserve job id request to be sent to the server. * * @param jobRequest The job request to convert * @param agentClientMetadata The metadata about the agent * @return The request that should be sent to the server for a new Job Specification given the parameters * @throws GenieConversionException if conversion fails */ public ReserveJobIdRequest toReserveJobIdRequestProto( final AgentJobRequest jobRequest, final AgentClientMetadata agentClientMetadata ) throws GenieConversionException { final ReserveJobIdRequest.Builder builder = ReserveJobIdRequest.newBuilder(); builder.setMetadata(this.toJobMetadataProto(jobRequest)); builder.setCriteria(this.toExecutionResourceCriteriaProto(jobRequest)); builder.setAgentConfig(this.toAgentConfigProto(jobRequest.getRequestedAgentConfig())); builder.setAgentMetadata(this.toAgentMetadataProto(agentClientMetadata)); return builder.build(); } /** * Generate a {@link JobSpecificationRequest} from the given job id. * * @param id The job id to generate the request for * @return The request instance */ public JobSpecificationRequest toJobSpecificationRequestProto(final String id) { return JobSpecificationRequest.newBuilder().setId(id).build(); } /** * Convert a gRPC reserve job id request into a V4 Job Request DTO for use within Genie codebase. * * @param request The request to convert * @return The job request * @throws GenieConversionException if conversion fails */ public JobRequest toJobRequestDto(final ReserveJobIdRequest request) throws GenieConversionException { return this.toJobRequestDto( request.getMetadata(), request.getCriteria(), request.getAgentConfig() ); } /** * Convert a V4 Job Request DTO into a gRPC dry run resolve job specification request to be sent to the server. * * @param jobRequest The job request to convert * @return The request that should be sent to the server for a new Job Specification given the parameters * @throws GenieConversionException if conversion fails */ public DryRunJobSpecificationRequest toDryRunJobSpecificationRequestProto( final AgentJobRequest jobRequest ) throws GenieConversionException { final DryRunJobSpecificationRequest.Builder builder = DryRunJobSpecificationRequest.newBuilder(); builder.setMetadata(this.toJobMetadataProto(jobRequest)); builder.setCriteria(this.toExecutionResourceCriteriaProto(jobRequest)); builder.setAgentConfig(this.toAgentConfigProto(jobRequest.getRequestedAgentConfig())); return builder.build(); } /** * Convert a gRPC request to dry run a job specification resolution into a {@link JobRequest} for use within * Genie server codebase. * * @param request The request to convert * @return The job request * @throws GenieConversionException if conversion fails */ public JobRequest toJobRequestDto(final DryRunJobSpecificationRequest request) throws GenieConversionException { return toJobRequestDto( request.getMetadata(), request.getCriteria(), request.getAgentConfig() ); } /** * Convert a proto {@link AgentMetadata} to an {@link AgentClientMetadata}. * * @param agentMetadata The metadata to convert * @return The immutable DTO representation */ public AgentClientMetadata toAgentClientMetadataDto(final AgentMetadata agentMetadata) { return new AgentClientMetadata( agentMetadata.getAgentHostname(), agentMetadata.getAgentVersion(), agentMetadata.getAgentPid() ); } /** * Build a {@link JobSpecificationResponse} out of the given {@link JobSpecification}. * * @param jobSpecification The job specification to serialize * @return The response instance */ public JobSpecificationResponse toJobSpecificationResponseProto(final JobSpecification jobSpecification) { return JobSpecificationResponse .newBuilder() .setSpecification(this.toJobSpecificationProto(jobSpecification)) .build(); } /** * Convert a response from server into a Job Specification DTO which can be used in the codebase free of gRPC. * * @param protoSpec The protobuf specification message * @return A job specification DTO */ public JobSpecification toJobSpecificationDto( final com.netflix.genie.proto.JobSpecification protoSpec ) { return new JobSpecification( protoSpec.getExecutableAndArgsList(), protoSpec.getJobArgsList(), toExecutionResourceDto(protoSpec.getJob()), toExecutionResourceDto(protoSpec.getCluster()), toExecutionResourceDto(protoSpec.getCommand()), protoSpec .getApplicationsList() .stream() .map(this::toExecutionResourceDto) .collect(Collectors.toList()), protoSpec.getEnvironmentVariablesMap(), protoSpec.getIsInteractive(), new File(protoSpec.getJobDirectoryLocation()), StringUtils.isBlank(protoSpec.getArchiveLocation()) ? null : protoSpec.getArchiveLocation(), protoSpec.hasTimeout() ? protoSpec.getTimeout().getValue() : null ); } /** * Convert a Job Specification DTO to a protobuf message representation. * * @param jobSpecification The {@link JobSpecification} to convert * @return A {@link com.netflix.genie.proto.JobSpecification} instance */ public com.netflix.genie.proto.JobSpecification toJobSpecificationProto(final JobSpecification jobSpecification) { final com.netflix.genie.proto.JobSpecification.Builder builder = com.netflix.genie.proto.JobSpecification.newBuilder(); builder.addAllExecutableAndArgs(jobSpecification.getExecutableArgs()); builder.addAllJobArgs(jobSpecification.getJobArgs()); // Keep populating commandArgs for backward compatibility builder.addAllCommandArgs(jobSpecification.getExecutableArgs()); builder.addAllCommandArgs(jobSpecification.getJobArgs()); builder.setJob(toExecutionResourceProto(jobSpecification.getJob())); builder.setCluster(toExecutionResourceProto(jobSpecification.getCluster())); builder.setCommand(toExecutionResourceProto(jobSpecification.getCommand())); builder.addAllApplications( jobSpecification .getApplications() .stream() .map(this::toExecutionResourceProto) .collect(Collectors.toList()) ); builder.putAllEnvironmentVariables(jobSpecification.getEnvironmentVariables()); builder.setIsInteractive(jobSpecification.isInteractive()); builder.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); jobSpecification.getArchiveLocation().ifPresent(builder::setArchiveLocation); jobSpecification.getTimeout().ifPresent(timeout -> builder.setTimeout(Int32Value.of(timeout))); return builder.build(); } /** * Convert agent metadata and job id into a ClaimJobRequest for the server. * * @param jobId job id * @param agentClientMetadata agent metadata * @return a ClaimJobRequest */ public ClaimJobRequest toClaimJobRequestProto( final String jobId, final AgentClientMetadata agentClientMetadata ) { return ClaimJobRequest.newBuilder() .setId(jobId) .setAgentMetadata( toAgentMetadataProto(agentClientMetadata) ) .build(); } /** * Convert parameters into ChangeJobStatusRequest for the server. * * @param jobId job id * @param currentJobStatus the expected current status on the server * @param newJobStatus the new current status for this job * @param message an optional message to record with the state change * @return a ChangeJobStatusRequest */ public ChangeJobStatusRequest toChangeJobStatusRequestProto( final @NotBlank String jobId, final JobStatus currentJobStatus, final JobStatus newJobStatus, final @Nullable String message ) { return ChangeJobStatusRequest.newBuilder() .setId(jobId) .setCurrentStatus(currentJobStatus.name()) .setNewStatus(newJobStatus.name()) .setNewStatusMessage(message == null ? "" : message) .build(); } /** * Convert parameters into HandshakeRequest for the server. * * @param agentClientMetadata agent client metadata * @return a {@link HandshakeRequest} * @throws GenieConversionException if the inputs are invalid */ public HandshakeRequest toHandshakeRequestProto( final AgentClientMetadata agentClientMetadata ) throws GenieConversionException { return HandshakeRequest.newBuilder() .setAgentMetadata( toAgentMetadataProto(agentClientMetadata) ) .build(); } /** * Convert parameters into ConfigureRequest for the server. * * @param agentClientMetadata agent client metadata * @return a {@link ConfigureRequest} * @throws GenieConversionException if the inputs are invalid */ public ConfigureRequest toConfigureRequestProto( final AgentClientMetadata agentClientMetadata ) throws GenieConversionException { return ConfigureRequest.newBuilder() .setAgentMetadata( toAgentMetadataProto(agentClientMetadata) ) .build(); } /** * Convert a protobuf Agent config request to a DTO representation. * * @param protoAgentConfig The {@link AgentConfig} proto message to convert * @return A {@link AgentConfigRequest} instance with the necessary information */ AgentConfigRequest toAgentConfigRequestDto(final AgentConfig protoAgentConfig) { return new AgentConfigRequest .Builder() .withRequestedJobDirectoryLocation( StringUtils.isNotBlank(protoAgentConfig.getJobDirectoryLocation()) ? protoAgentConfig.getJobDirectoryLocation() : null ) .withInteractive(protoAgentConfig.getIsInteractive()) .withTimeoutRequested(protoAgentConfig.hasTimeout() ? protoAgentConfig.getTimeout().getValue() : null) .withArchivingDisabled(protoAgentConfig.getArchivingDisabled()) .build(); } /** * Convert a Agent configuration request DTO to a protobuf message representation. * * @param agentConfigRequest The {@link AgentConfigRequest} DTO to convert * @return A {@link AgentConfig} message instance */ AgentConfig toAgentConfigProto(final AgentConfigRequest agentConfigRequest) { final AgentConfig.Builder builder = AgentConfig.newBuilder(); agentConfigRequest.getRequestedJobDirectoryLocation().ifPresent( location -> builder.setJobDirectoryLocation(location.getAbsolutePath()) ); builder.setIsInteractive(agentConfigRequest.isInteractive()); agentConfigRequest .getTimeoutRequested() .ifPresent(requestedTimeout -> builder.setTimeout(Int32Value.of(requestedTimeout))); builder.setArchivingDisabled(agentConfigRequest.isArchivingDisabled()); return builder.build(); } /** * Creates a request to fetch the job status currently seen by the server. * * @param jobId the job id * @return A {@link GetJobStatusRequest} message instance */ public GetJobStatusRequest toGetJobStatusRequestProto(final String jobId) { return GetJobStatusRequest.newBuilder().setId(jobId).build(); } /** * Creates a request to change the remote job archive status. * * @param jobId the job id * @param archiveStatus the new archive status * @return a {@link ChangeJobArchiveStatusRequest} message instance */ public ChangeJobArchiveStatusRequest toChangeJobStatusArchiveRequestProto( final String jobId, final ArchiveStatus archiveStatus ) { return ChangeJobArchiveStatusRequest.newBuilder() .setId(jobId) .setNewStatus(archiveStatus.name()) .build(); } private JobSpecification.ExecutionResource toExecutionResourceDto(final ExecutionResource protoResource) { return new JobSpecification.ExecutionResource( protoResource.getId(), new ExecutionEnvironment( ImmutableSet.copyOf(protoResource.getConfigsList()), ImmutableSet.copyOf(protoResource.getDependenciesList()), protoResource.getSetupFile().isEmpty() ? null : protoResource.getSetupFile() ) ); } private ExecutionResource toExecutionResourceProto( final JobSpecification.ExecutionResource executionResource ) { final ExecutionResource.Builder builder = ExecutionResource .newBuilder() .setId(executionResource.getId()) .addAllConfigs(executionResource.getExecutionEnvironment().getConfigs()) .addAllDependencies(executionResource.getExecutionEnvironment().getDependencies()); executionResource.getExecutionEnvironment().getSetupFile().ifPresent(builder::setSetupFile); return builder.build(); } private Criterion toCriterionDto( final com.netflix.genie.proto.Criterion protoCriterion ) throws GenieConversionException { try { return new Criterion .Builder() .withId(protoCriterion.getId()) .withName(protoCriterion.getName()) .withVersion(protoCriterion.getVersion()) .withStatus(protoCriterion.getStatus()) .withTags(Sets.newHashSet(protoCriterion.getTagsList())) .build(); } catch (final IllegalArgumentException e) { throw new GenieConversionException("Failed to convert criterion", e); } } private com.netflix.genie.proto.Criterion toCriterionProto(final Criterion criterion) { final com.netflix.genie.proto.Criterion.Builder builder = com.netflix.genie.proto.Criterion.newBuilder(); criterion.getId().ifPresent(builder::setId); criterion.getName().ifPresent(builder::setName); criterion.getVersion().ifPresent(builder::setVersion); criterion.getStatus().ifPresent(builder::setStatus); builder.addAllTags(criterion.getTags()); return builder.build(); } private com.netflix.genie.proto.JobMetadata toJobMetadataProto( final AgentJobRequest jobRequest ) throws GenieConversionException { final JobMetadata jobMetadata = jobRequest.getMetadata(); final ExecutionEnvironment jobResources = jobRequest.getResources(); final com.netflix.genie.proto.JobMetadata.Builder builder = com.netflix.genie.proto.JobMetadata.newBuilder(); jobRequest.getRequestedId().ifPresent(builder::setId); builder.setName(jobMetadata.getName()); builder.setUser(jobMetadata.getUser()); builder.setVersion(jobMetadata.getVersion()); jobMetadata.getDescription().ifPresent(builder::setDescription); builder.addAllTags(jobMetadata.getTags()); if (jobMetadata.getMetadata().isPresent()) { final String serializedMetadata; try { serializedMetadata = GenieObjectMapper.getMapper().writeValueAsString(jobMetadata.getMetadata().get()); } catch (JsonProcessingException e) { throw new GenieConversionException("Failed to serialize job metadata to JSON", e); } builder.setMetadata(serializedMetadata); } jobMetadata.getEmail().ifPresent(builder::setEmail); jobMetadata.getGrouping().ifPresent(builder::setGrouping); jobMetadata.getGroupingInstance().ifPresent(builder::setGroupingInstance); jobResources.getSetupFile().ifPresent(builder::setSetupFile); builder.addAllConfigs(jobResources.getConfigs()); builder.addAllDependencies(jobResources.getDependencies()); builder.addAllCommandArgs(jobRequest.getCommandArgs()); return builder.build(); } private com.netflix.genie.proto.ExecutionResourceCriteria toExecutionResourceCriteriaProto( final AgentJobRequest jobRequest ) { final ExecutionResourceCriteria executionResourceCriteria = jobRequest.getCriteria(); final com.netflix.genie.proto.ExecutionResourceCriteria.Builder builder = com.netflix.genie.proto.ExecutionResourceCriteria.newBuilder(); builder.addAllClusterCriteria( executionResourceCriteria .getClusterCriteria() .stream() .map(this::toCriterionProto) .collect(Collectors.toList()) ); builder.setCommandCriterion( toCriterionProto(executionResourceCriteria.getCommandCriterion()) ); builder.addAllRequestedApplicationIdOverrides(executionResourceCriteria.getApplicationIds()); return builder.build(); } private AgentMetadata toAgentMetadataProto(final AgentClientMetadata agentClientMetadata) { final AgentMetadata.Builder builder = AgentMetadata.newBuilder(); agentClientMetadata.getHostname().ifPresent(builder::setAgentHostname); agentClientMetadata.getVersion().ifPresent(builder::setAgentVersion); agentClientMetadata.getPid().ifPresent(builder::setAgentPid); return builder.build(); } private JobRequest toJobRequestDto( final com.netflix.genie.proto.JobMetadata protoJobMetadata, final com.netflix.genie.proto.ExecutionResourceCriteria protoExecutionResourceCriteria, final com.netflix.genie.proto.AgentConfig protoAgentConfig ) throws GenieConversionException { try { final JobMetadata jobMetadata = new JobMetadata.Builder( protoJobMetadata.getName(), protoJobMetadata.getUser(), protoJobMetadata.getVersion() ) .withDescription(protoJobMetadata.getDescription()) .withTags(Sets.newHashSet(protoJobMetadata.getTagsList())) .withMetadata(protoJobMetadata.getMetadata()) .withEmail(protoJobMetadata.getEmail()) .withGrouping(protoJobMetadata.getGrouping()) .withGroupingInstance(protoJobMetadata.getGroupingInstance()) .build(); final List<com.netflix.genie.proto.Criterion> protoCriteria = protoExecutionResourceCriteria.getClusterCriteriaList(); final List<Criterion> clusterCriteria = Lists.newArrayListWithExpectedSize(protoCriteria.size()); for (final com.netflix.genie.proto.Criterion protoCriterion : protoCriteria) { clusterCriteria.add(toCriterionDto(protoCriterion)); } final ExecutionResourceCriteria executionResourceCriteria = new ExecutionResourceCriteria( clusterCriteria, toCriterionDto(protoExecutionResourceCriteria.getCommandCriterion()), protoExecutionResourceCriteria.getRequestedApplicationIdOverridesList() ); final ExecutionEnvironment jobResources = new ExecutionEnvironment( Sets.newHashSet(protoJobMetadata.getConfigsList()), Sets.newHashSet(protoJobMetadata.getDependenciesList()), protoJobMetadata.getSetupFile() ); final AgentConfigRequest agentConfigRequest = this.toAgentConfigRequestDto(protoAgentConfig); final String jobId = protoJobMetadata.getId(); return new JobRequest( StringUtils.isBlank(jobId) ? null : jobId, jobResources, protoJobMetadata.getCommandArgsList(), jobMetadata, executionResourceCriteria, null, agentConfigRequest ); } catch (final IllegalArgumentException e) { throw new GenieConversionException("Failed to compose JobRequest", e); } } }
2,195
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/converters/JobDirectoryManifestProtoConverter.java
/* * * Copyright 2019 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos.converters; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.genie.common.internal.dtos.DirectoryManifest; import com.netflix.genie.common.internal.exceptions.checked.GenieConversionException; import com.netflix.genie.proto.AgentManifestMessage; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import java.io.IOException; /** * Converts {@link DirectoryManifest} from/to {@link AgentManifestMessage} in order to transport manifests * over gRPC. * * @author mprimi * @since 4.0.0 */ @Validated public class JobDirectoryManifestProtoConverter { private final ObjectMapper objectMapper; /** * Constructor. * * @param objectMapper an object mapper */ public JobDirectoryManifestProtoConverter(final ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** * Construct a {@link AgentManifestMessage} from the given {@link DirectoryManifest}. * * @param claimedJobId the id of the job this file manifest belongs to * @param manifest the manifest * @return a {@link AgentManifestMessage} * @throws GenieConversionException if conversion fails */ public AgentManifestMessage manifestToProtoMessage( @NotBlank final String claimedJobId, final DirectoryManifest manifest ) throws GenieConversionException { final String manifestJsonString; try { // Leverage the existing manifest serialization to JSON rather than creating and using a protobuf schema. manifestJsonString = objectMapper.writeValueAsString(manifest); } catch (final JsonProcessingException e) { throw new GenieConversionException("Failed to serialize manifest as JSON string", e); } return AgentManifestMessage.newBuilder() .setJobId(claimedJobId) .setManifestJson(manifestJsonString) .setLargeFilesSupported(true) .build(); } /** * Load a {@link DirectoryManifest} from a {@link AgentManifestMessage}. * * @param message the message * @return a {@link DirectoryManifest} * @throws GenieConversionException if loading fails */ public DirectoryManifest toManifest(final AgentManifestMessage message) throws GenieConversionException { try { return objectMapper.readValue(message.getManifestJson(), DirectoryManifest.class); } catch (final IOException e) { throw new GenieConversionException("Failed to load manifest", e); } } }
2,196
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/converters/DtoConverters.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.dtos.converters; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.netflix.genie.common.dto.ClusterCriteria; import com.netflix.genie.common.dto.ContainerImage; import com.netflix.genie.common.dto.Runtime; import com.netflix.genie.common.dto.RuntimeResources; import com.netflix.genie.common.exceptions.GeniePreconditionException; import com.netflix.genie.common.internal.dtos.AgentConfigRequest; import com.netflix.genie.common.internal.dtos.Application; import com.netflix.genie.common.internal.dtos.ApplicationMetadata; import com.netflix.genie.common.internal.dtos.ApplicationRequest; import com.netflix.genie.common.internal.dtos.ApplicationStatus; import com.netflix.genie.common.internal.dtos.Cluster; import com.netflix.genie.common.internal.dtos.ClusterMetadata; import com.netflix.genie.common.internal.dtos.ClusterRequest; import com.netflix.genie.common.internal.dtos.ClusterStatus; import com.netflix.genie.common.internal.dtos.Command; import com.netflix.genie.common.internal.dtos.CommandMetadata; import com.netflix.genie.common.internal.dtos.CommandRequest; import com.netflix.genie.common.internal.dtos.CommandStatus; import com.netflix.genie.common.internal.dtos.ComputeResources; import com.netflix.genie.common.internal.dtos.Criterion; import com.netflix.genie.common.internal.dtos.ExecutionEnvironment; import com.netflix.genie.common.internal.dtos.ExecutionResourceCriteria; import com.netflix.genie.common.internal.dtos.Image; import com.netflix.genie.common.internal.dtos.JobEnvironmentRequest; import com.netflix.genie.common.internal.dtos.JobMetadata; import com.netflix.genie.common.internal.dtos.JobRequest; import com.netflix.genie.common.internal.dtos.JobStatus; import org.apache.commons.lang3.StringUtils; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Utility class to help convert between V3 and internal DTOs. * * @author tgianos * @since 4.0.0 */ public final class DtoConverters { /** * The Genie 3 prefix for resource ID added to the set of tags by the system. */ public static final String GENIE_ID_PREFIX = "genie.id:"; /** * The Genie 3 prefix for resource names added to the set of tags by the system. */ public static final String GENIE_NAME_PREFIX = "genie.name:"; private DtoConverters() { } /** * Convert a V3 {@link com.netflix.genie.common.dto.Application} to a corresponding V4 {@link ApplicationRequest}. * * @param v3Application The application to convert * @return An immutable {@link ApplicationRequest} instance * @throws IllegalArgumentException If any field is invalid during the conversion */ public static ApplicationRequest toV4ApplicationRequest( final com.netflix.genie.common.dto.Application v3Application ) throws IllegalArgumentException { final ApplicationMetadata.Builder metadataBuilder = new ApplicationMetadata.Builder( v3Application.getName(), v3Application.getUser(), v3Application.getVersion(), toV4ApplicationStatus(v3Application.getStatus()) ) .withTags(toV4Tags(v3Application.getTags())); v3Application.getMetadata().ifPresent(metadataBuilder::withMetadata); v3Application.getType().ifPresent(metadataBuilder::withType); v3Application.getDescription().ifPresent(metadataBuilder::withDescription); final ApplicationRequest.Builder builder = new ApplicationRequest.Builder(metadataBuilder.build()); v3Application.getId().ifPresent(builder::withRequestedId); builder.withResources( new ExecutionEnvironment( v3Application.getConfigs(), v3Application.getDependencies(), v3Application.getSetupFile().orElse(null) ) ); return builder.build(); } /** * Convert a V3 Application DTO to a V4 Application DTO. * * @param v3Application The V3 application to convert * @return The V4 application representation of the data in the V3 DTO * @throws IllegalArgumentException On invalid argument to one of the fields */ public static Application toV4Application( final com.netflix.genie.common.dto.Application v3Application ) throws IllegalArgumentException { final ApplicationMetadata.Builder metadataBuilder = new ApplicationMetadata.Builder( v3Application.getName(), v3Application.getUser(), v3Application.getVersion(), toV4ApplicationStatus(v3Application.getStatus()) ) .withTags(toV4Tags(v3Application.getTags())); v3Application.getMetadata().ifPresent(metadataBuilder::withMetadata); v3Application.getType().ifPresent(metadataBuilder::withType); v3Application.getDescription().ifPresent(metadataBuilder::withDescription); return new Application( v3Application.getId().orElseThrow(IllegalArgumentException::new), v3Application.getCreated().orElse(Instant.now()), v3Application.getUpdated().orElse(Instant.now()), new ExecutionEnvironment( v3Application.getConfigs(), v3Application.getDependencies(), v3Application.getSetupFile().orElse(null) ), metadataBuilder.build() ); } /** * Convert a V4 Application DTO to a V3 application DTO. * * @param v4Application The V4 application to convert * @return The V3 application representation of the data in the V4 DTO * @throws IllegalArgumentException On invalid argument for one of the fields */ public static com.netflix.genie.common.dto.Application toV3Application( final Application v4Application ) throws IllegalArgumentException { final ApplicationMetadata applicationMetadata = v4Application.getMetadata(); final ExecutionEnvironment resources = v4Application.getResources(); final com.netflix.genie.common.dto.Application.Builder builder = new com.netflix.genie.common.dto.Application.Builder( applicationMetadata.getName(), applicationMetadata.getUser(), applicationMetadata.getVersion(), toV3ApplicationStatus(applicationMetadata.getStatus()) ) .withId(v4Application.getId()) .withTags(toV3Tags(v4Application.getId(), applicationMetadata.getName(), applicationMetadata.getTags())) .withConfigs(resources.getConfigs()) .withDependencies(resources.getDependencies()) .withCreated(v4Application.getCreated()) .withUpdated(v4Application.getUpdated()); applicationMetadata.getType().ifPresent(builder::withType); applicationMetadata.getDescription().ifPresent(builder::withDescription); applicationMetadata.getMetadata().ifPresent(builder::withMetadata); resources.getSetupFile().ifPresent(builder::withSetupFile); return builder.build(); } /** * Convert a {@link com.netflix.genie.common.dto.Cluster} to a V4 {@link ClusterRequest}. * * @param v3Cluster The V3 cluster instance to convert * @return An immutable {@link ClusterRequest} instance * @throws IllegalArgumentException On any invalid field during conversion */ public static ClusterRequest toV4ClusterRequest(final com.netflix.genie.common.dto.Cluster v3Cluster) { final ClusterMetadata.Builder metadataBuilder = new ClusterMetadata.Builder( v3Cluster.getName(), v3Cluster.getUser(), v3Cluster.getVersion(), toV4ClusterStatus(v3Cluster.getStatus()) ) .withTags(toV4Tags(v3Cluster.getTags())); v3Cluster.getMetadata().ifPresent(metadataBuilder::withMetadata); v3Cluster.getDescription().ifPresent(metadataBuilder::withDescription); final ClusterRequest.Builder builder = new ClusterRequest.Builder(metadataBuilder.build()); v3Cluster.getId().ifPresent(builder::withRequestedId); builder.withResources( new ExecutionEnvironment( v3Cluster.getConfigs(), v3Cluster.getDependencies(), v3Cluster.getSetupFile().orElse(null) ) ); return builder.build(); } /** * Convert a V3 {@link com.netflix.genie.common.dto.Cluster} to a V4 {@link Cluster}. * * @param v3Cluster The cluster to convert * @return The V4 representation of the cluster * @throws IllegalArgumentException On any invalid field during conversion */ public static Cluster toV4Cluster( final com.netflix.genie.common.dto.Cluster v3Cluster ) throws IllegalArgumentException { final ClusterMetadata.Builder metadataBuilder = new ClusterMetadata.Builder( v3Cluster.getName(), v3Cluster.getUser(), v3Cluster.getVersion(), toV4ClusterStatus(v3Cluster.getStatus()) ) .withTags(toV4Tags(v3Cluster.getTags())); v3Cluster.getMetadata().ifPresent(metadataBuilder::withMetadata); v3Cluster.getDescription().ifPresent(metadataBuilder::withDescription); return new Cluster( v3Cluster.getId().orElseThrow(IllegalArgumentException::new), v3Cluster.getCreated().orElse(Instant.now()), v3Cluster.getUpdated().orElse(Instant.now()), new ExecutionEnvironment( v3Cluster.getConfigs(), v3Cluster.getDependencies(), v3Cluster.getSetupFile().orElse(null) ), metadataBuilder.build() ); } /** * Convert a V4 {@link Cluster} to a V3 {@link com.netflix.genie.common.dto.Cluster}. * * @param v4Cluster The cluster to convert * @return The v3 cluster * @throws IllegalArgumentException On any invalid field during conversion */ public static com.netflix.genie.common.dto.Cluster toV3Cluster( final Cluster v4Cluster ) throws IllegalArgumentException { final ClusterMetadata clusterMetadata = v4Cluster.getMetadata(); final ExecutionEnvironment resources = v4Cluster.getResources(); final com.netflix.genie.common.dto.Cluster.Builder builder = new com.netflix.genie.common.dto.Cluster.Builder( clusterMetadata.getName(), clusterMetadata.getUser(), clusterMetadata.getVersion(), toV3ClusterStatus(clusterMetadata.getStatus()) ) .withId(v4Cluster.getId()) .withTags(toV3Tags(v4Cluster.getId(), clusterMetadata.getName(), clusterMetadata.getTags())) .withConfigs(resources.getConfigs()) .withDependencies(resources.getDependencies()) .withCreated(v4Cluster.getCreated()) .withUpdated(v4Cluster.getUpdated()); clusterMetadata.getDescription().ifPresent(builder::withDescription); clusterMetadata.getMetadata().ifPresent(builder::withMetadata); resources.getSetupFile().ifPresent(builder::withSetupFile); return builder.build(); } /** * Convert a V3 {@link com.netflix.genie.common.dto.Command} to a V4 {@link CommandRequest}. * * @param v3Command The V3 command to convert * @return An immutable {@link CommandRequest} instance * @throws IllegalArgumentException On any invalid field during conversion */ public static CommandRequest toV4CommandRequest( final com.netflix.genie.common.dto.Command v3Command ) throws IllegalArgumentException { final CommandMetadata.Builder metadataBuilder = new CommandMetadata.Builder( v3Command.getName(), v3Command.getUser(), v3Command.getVersion(), toV4CommandStatus(v3Command.getStatus()) ) .withTags(toV4Tags(v3Command.getTags())); v3Command.getMetadata().ifPresent(metadataBuilder::withMetadata); v3Command.getDescription().ifPresent(metadataBuilder::withDescription); final List<String> executable = v3Command.getExecutableAndArguments(); final CommandRequest.Builder builder = new CommandRequest.Builder(metadataBuilder.build(), executable); v3Command.getId().ifPresent(builder::withRequestedId); final Runtime runtime = v3Command.getRuntime(); builder.withComputeResources(toComputeResources(runtime.getResources())); builder.withImages( runtime .getImages() .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> toImage(entry.getValue()) ) ) ); builder.withResources( new ExecutionEnvironment( v3Command.getConfigs(), v3Command.getDependencies(), v3Command.getSetupFile().orElse(null) ) ); builder.withClusterCriteria( v3Command .getClusterCriteria() .stream() .map(DtoConverters::toV4CommandClusterCriterion) .collect(Collectors.toList()) ); return builder.build(); } /** * Convert a V3 {@link com.netflix.genie.common.dto.Command} to an intenral {@link Command}. * * @param v3Command The V3 Command to convert * @return The V4 representation of the supplied command * @throws IllegalArgumentException On any invalid field during conversion */ public static Command toV4Command( final com.netflix.genie.common.dto.Command v3Command ) throws IllegalArgumentException { final CommandMetadata.Builder metadataBuilder = new CommandMetadata.Builder( v3Command.getName(), v3Command.getUser(), v3Command.getVersion(), toV4CommandStatus(v3Command.getStatus()) ) .withTags(toV4Tags(v3Command.getTags())); v3Command.getDescription().ifPresent(metadataBuilder::withDescription); v3Command.getMetadata().ifPresent(metadataBuilder::withMetadata); final ExecutionEnvironment resources = new ExecutionEnvironment( v3Command.getConfigs(), v3Command.getDependencies(), v3Command.getSetupFile().orElse(null) ); return new Command( v3Command.getId().orElseThrow(IllegalArgumentException::new), v3Command.getCreated().orElse(Instant.now()), v3Command.getUpdated().orElse(Instant.now()), resources, metadataBuilder.build(), v3Command.getExecutableAndArguments(), v3Command .getClusterCriteria() .stream() .map(DtoConverters::toV4CommandClusterCriterion) .collect(Collectors.toList()), toComputeResources(v3Command.getRuntime().getResources()), v3Command .getRuntime() .getImages() .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> toImage(entry.getValue()) ) ) ); } /** * Convert a V4 {@link Command} to a V3 {@link com.netflix.genie.common.dto.Command}. * * @param v4Command The V4 command to convert * @return An immutable V3 Command instance * @throws IllegalArgumentException On any invalid field during conversion */ public static com.netflix.genie.common.dto.Command toV3Command( final Command v4Command ) throws IllegalArgumentException { final CommandMetadata commandMetadata = v4Command.getMetadata(); final ExecutionEnvironment resources = v4Command.getResources(); final com.netflix.genie.common.dto.Command.Builder builder = new com.netflix.genie.common.dto.Command.Builder( commandMetadata.getName(), commandMetadata.getUser(), commandMetadata.getVersion(), toV3CommandStatus(commandMetadata.getStatus()), v4Command.getExecutable() ) .withId(v4Command.getId()) .withTags(toV3Tags(v4Command.getId(), commandMetadata.getName(), commandMetadata.getTags())) .withConfigs(resources.getConfigs()) .withDependencies(resources.getDependencies()) .withCreated(v4Command.getCreated()) .withUpdated(v4Command.getUpdated()) .withClusterCriteria( v4Command .getClusterCriteria() .stream() .map(DtoConverters::toV3Criterion) .collect(Collectors.toList()) ); commandMetadata.getDescription().ifPresent(builder::withDescription); commandMetadata.getMetadata().ifPresent(builder::withMetadata); resources.getSetupFile().ifPresent(builder::withSetupFile); builder.withRuntime( new Runtime.Builder() .withResources(toV3RuntimeResources(v4Command.getComputeResources())) .withImages( v4Command .getImages() .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> toV3ContainerImage(entry.getValue()) ) ) ) .build() ); return builder.build(); } /** * Convert a V3 Job Request to a V4 Job Request. * * @param v3JobRequest The v3 request to convert * @return The V4 version of the information contained in the V3 request * @throws GeniePreconditionException When the criteria is invalid */ public static JobRequest toV4JobRequest( final com.netflix.genie.common.dto.JobRequest v3JobRequest ) throws GeniePreconditionException { final ExecutionEnvironment resources = new ExecutionEnvironment( v3JobRequest.getConfigs(), v3JobRequest.getDependencies(), v3JobRequest.getSetupFile().orElse(null) ); final JobMetadata.Builder metadataBuilder = new JobMetadata.Builder( v3JobRequest.getName(), v3JobRequest.getUser(), v3JobRequest.getVersion() ) .withTags(v3JobRequest.getTags()); v3JobRequest.getMetadata().ifPresent(metadataBuilder::withMetadata); v3JobRequest.getEmail().ifPresent(metadataBuilder::withEmail); v3JobRequest.getGroup().ifPresent(metadataBuilder::withGroup); v3JobRequest.getGrouping().ifPresent(metadataBuilder::withGrouping); v3JobRequest.getGroupingInstance().ifPresent(metadataBuilder::withGroupingInstance); v3JobRequest.getDescription().ifPresent(metadataBuilder::withDescription); final List<Criterion> clusterCriteria = Lists.newArrayList(); for (final ClusterCriteria criterion : v3JobRequest.getClusterCriterias()) { clusterCriteria.add(toV4Criterion(criterion)); } final ExecutionResourceCriteria criteria = new ExecutionResourceCriteria( clusterCriteria, toV4Criterion(v3JobRequest.getCommandCriteria()), v3JobRequest.getApplications() ); final Runtime runtime = v3JobRequest.getRuntime(); final JobEnvironmentRequest.Builder jobEnvironmentBuilder = new JobEnvironmentRequest.Builder(); jobEnvironmentBuilder.withRequestedComputeResources(toComputeResources(runtime.getResources())); jobEnvironmentBuilder.withRequestedImages( runtime .getImages() .entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> toImage(entry.getValue()))) ); final AgentConfigRequest.Builder agentConfigBuilder = new AgentConfigRequest .Builder() .withArchivingDisabled(/*v3JobRequest.isDisableLogArchival()*/ false) //TODO: Stop ignoring flag [GENIE-657] .withInteractive(false); v3JobRequest.getTimeout().ifPresent(agentConfigBuilder::withTimeoutRequested); // Keep arguments as joined string and store them as first (and only element of the list) final List<String> commandArgs = Lists.newArrayList(); v3JobRequest.getCommandArgs().ifPresent(commandArgs::add); return new JobRequest( v3JobRequest.getId().orElse(null), resources, commandArgs, metadataBuilder.build(), criteria, jobEnvironmentBuilder.build(), agentConfigBuilder.build() ); } /** * Helper method to convert a v4 JobRequest to a v3 job request. * * @param v4JobRequest The v4 job request instance * @return The v3 job request instance */ public static com.netflix.genie.common.dto.JobRequest toV3JobRequest(final JobRequest v4JobRequest) { final com.netflix.genie.common.dto.JobRequest.Builder v3Builder = new com.netflix.genie.common.dto.JobRequest.Builder( v4JobRequest.getMetadata().getName(), v4JobRequest.getMetadata().getUser(), v4JobRequest.getMetadata().getVersion(), v4JobRequest .getCriteria() .getClusterCriteria() .stream() .map(DtoConverters::toClusterCriteria) .collect(Collectors.toList()), toV3CriterionTags(v4JobRequest.getCriteria().getCommandCriterion()) ) .withApplications(v4JobRequest.getCriteria().getApplicationIds()) .withCommandArgs(v4JobRequest.getCommandArgs()) .withDisableLogArchival(v4JobRequest.getRequestedAgentConfig().isArchivingDisabled()) .withTags(v4JobRequest.getMetadata().getTags()); v4JobRequest.getRequestedId().ifPresent(v3Builder::withId); final JobMetadata metadata = v4JobRequest.getMetadata(); metadata.getEmail().ifPresent(v3Builder::withEmail); metadata.getGroup().ifPresent(v3Builder::withGroup); metadata.getGrouping().ifPresent(v3Builder::withGrouping); metadata.getGroupingInstance().ifPresent(v3Builder::withGroupingInstance); metadata.getDescription().ifPresent(v3Builder::withDescription); metadata.getMetadata().ifPresent(v3Builder::withMetadata); final ExecutionEnvironment jobResources = v4JobRequest.getResources(); v3Builder.withConfigs(jobResources.getConfigs()); v3Builder.withDependencies(jobResources.getDependencies()); jobResources.getSetupFile().ifPresent(v3Builder::withSetupFile); v4JobRequest.getRequestedAgentConfig().getTimeoutRequested().ifPresent(v3Builder::withTimeout); final JobEnvironmentRequest jobEnvironmentRequest = v4JobRequest.getRequestedJobEnvironment(); v3Builder.withRuntime( new Runtime.Builder() .withResources(toV3RuntimeResources(jobEnvironmentRequest.getRequestedComputeResources())) .withImages( jobEnvironmentRequest .getRequestedImages() .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> toV3ContainerImage(entry.getValue()) ) ) ) .build() ); return v3Builder.build(); } /** * Convert the V4 values supplied to how the tags would have looked in Genie V3. * * @param id The id of the resource * @param name The name of the resource * @param tags The tags on the resource * @return The set of tags as they would have been in Genie 3 */ public static ImmutableSet<String> toV3Tags(final String id, final String name, final Set<String> tags) { final ImmutableSet.Builder<String> v3Tags = ImmutableSet.builder(); v3Tags.addAll(tags); v3Tags.add(GENIE_ID_PREFIX + id); v3Tags.add(GENIE_NAME_PREFIX + name); return v3Tags.build(); } /** * Convert a given V4 {@code criterion} to the equivalent representation in V3 set of tags. * * @param criterion The {@link Criterion} to convert * @return A set of String's representing the criterion tags as they would have looked in V3 */ public static ImmutableSet<String> toV3CriterionTags(final Criterion criterion) { final ImmutableSet.Builder<String> tags = ImmutableSet.builder(); criterion.getId().ifPresent(id -> tags.add(GENIE_ID_PREFIX + id)); criterion.getName().ifPresent(name -> tags.add(GENIE_NAME_PREFIX + name)); tags.addAll(criterion.getTags()); return tags.build(); } /** * Convert the given {@code criterion} to a V3 {@link ClusterCriteria} object. * * @param criterion The {@link Criterion} to convert * @return The V3 criteria object */ public static ClusterCriteria toClusterCriteria(final Criterion criterion) { return new ClusterCriteria(toV3CriterionTags(criterion)); } /** * Convert a V3 Cluster Criteria to a V4 Criterion. * * @param criteria The criteria to convert * @return The criterion * @throws GeniePreconditionException If the criteria converts to an invalid criterion */ public static Criterion toV4Criterion(final ClusterCriteria criteria) throws GeniePreconditionException { return toV4Criterion(criteria.getTags()); } /** * Convert a set of V3 criterion tags to a V4 criterion object. * * @param tags The tags to convert * @return The V4 criterion * @throws GeniePreconditionException If the tags convert to an invalid criterion */ public static Criterion toV4Criterion(final Set<String> tags) throws GeniePreconditionException { final Criterion.Builder builder = new Criterion.Builder(); final Set<String> v4Tags = Sets.newHashSet(); for (final String tag : tags) { if (tag.startsWith(GENIE_ID_PREFIX)) { builder.withId(tag.substring(GENIE_ID_PREFIX.length())); } else if (tag.startsWith(GENIE_NAME_PREFIX)) { builder.withName(tag.substring(GENIE_NAME_PREFIX.length())); } else { v4Tags.add(tag); } } builder.withTags(v4Tags); // Maintain previous contract for this method even though Criterion now throws a IAE try { return builder.build(); } catch (final IllegalArgumentException e) { throw new GeniePreconditionException(e.getMessage(), e); } } /** * Convert a V3 {@link com.netflix.genie.common.dto.ApplicationStatus} to a V4 {@link ApplicationStatus}. * * @param v3Status The V3 status to convert * @return The V4 status the V3 status maps to * @throws IllegalArgumentException if the V3 status has no current V4 mapping */ public static ApplicationStatus toV4ApplicationStatus( final com.netflix.genie.common.dto.ApplicationStatus v3Status ) throws IllegalArgumentException { switch (v3Status) { case ACTIVE: return ApplicationStatus.ACTIVE; case INACTIVE: return ApplicationStatus.INACTIVE; case DEPRECATED: return ApplicationStatus.DEPRECATED; default: throw new IllegalArgumentException("Unmapped V3 status: " + v3Status); } } /** * Attempt to convert an Application status string into a known enumeration value from {@link ApplicationStatus}. * * @param status The status string. Not null or empty. * @return An {@link ApplicationStatus} instance * @throws IllegalArgumentException If the string couldn't be converted */ public static ApplicationStatus toV4ApplicationStatus(final String status) throws IllegalArgumentException { if (StringUtils.isBlank(status)) { throw new IllegalArgumentException("No application status entered. Unable to convert."); } final String upperCaseStatus = status.toUpperCase(); try { return ApplicationStatus.valueOf(upperCaseStatus); } catch (final IllegalArgumentException e) { // TODO: Remove this eventually once we're satisfied v3 statuses have been flushed // Since it may be a remnant of V3 try the older one and map return toV4ApplicationStatus(com.netflix.genie.common.dto.ApplicationStatus.valueOf(upperCaseStatus)); } } /** * Convert a V4 {@link ApplicationStatus} to a V3 {@link com.netflix.genie.common.dto.ApplicationStatus}. * * @param v4Status The V4 status to convert * @return The V3 status the V4 status maps to * @throws IllegalArgumentException If the V4 status has no current V3 mapping */ public static com.netflix.genie.common.dto.ApplicationStatus toV3ApplicationStatus( final ApplicationStatus v4Status ) throws IllegalArgumentException { switch (v4Status) { case ACTIVE: return com.netflix.genie.common.dto.ApplicationStatus.ACTIVE; case INACTIVE: return com.netflix.genie.common.dto.ApplicationStatus.INACTIVE; case DEPRECATED: return com.netflix.genie.common.dto.ApplicationStatus.DEPRECATED; default: throw new IllegalArgumentException("Unmapped V4 status: " + v4Status); } } /** * Convert a V3 {@link com.netflix.genie.common.dto.CommandStatus} to a V4 {@link CommandStatus}. * * @param v3Status The V3 status to convert * @return The V4 status the V3 status maps to * @throws IllegalArgumentException if the V3 status has no current V4 mapping */ public static CommandStatus toV4CommandStatus( final com.netflix.genie.common.dto.CommandStatus v3Status ) throws IllegalArgumentException { switch (v3Status) { case ACTIVE: return CommandStatus.ACTIVE; case INACTIVE: return CommandStatus.INACTIVE; case DEPRECATED: return CommandStatus.DEPRECATED; default: throw new IllegalArgumentException("Unmapped V3 status: " + v3Status); } } /** * Attempt to convert a Command status string into a known enumeration value from {@link CommandStatus}. * * @param status The status string. Not null or empty. * @return An {@link CommandStatus} instance * @throws IllegalArgumentException If the string couldn't be converted */ public static CommandStatus toV4CommandStatus(final String status) throws IllegalArgumentException { if (StringUtils.isBlank(status)) { throw new IllegalArgumentException("No command status entered. Unable to convert."); } final String upperCaseStatus = status.toUpperCase(); try { return CommandStatus.valueOf(upperCaseStatus); } catch (final IllegalArgumentException e) { // TODO: Remove this eventually once we're satisfied v3 statuses have been flushed // Since it may be a remnant of V3 try the older one and map return toV4CommandStatus(com.netflix.genie.common.dto.CommandStatus.valueOf(upperCaseStatus)); } } /** * Convert a V4 {@link CommandStatus} to a V3 {@link com.netflix.genie.common.dto.CommandStatus}. * * @param v4Status The V4 status to convert * @return The V3 status the V4 status maps to * @throws IllegalArgumentException If the V4 status has no current V3 mapping */ public static com.netflix.genie.common.dto.CommandStatus toV3CommandStatus( final CommandStatus v4Status ) throws IllegalArgumentException { switch (v4Status) { case ACTIVE: return com.netflix.genie.common.dto.CommandStatus.ACTIVE; case INACTIVE: return com.netflix.genie.common.dto.CommandStatus.INACTIVE; case DEPRECATED: return com.netflix.genie.common.dto.CommandStatus.DEPRECATED; default: throw new IllegalArgumentException("Unmapped V4 status: " + v4Status); } } /** * Convert a V3 {@link com.netflix.genie.common.dto.ClusterStatus} to a V4 {@link ClusterStatus}. * * @param v3Status The V3 status to convert * @return The V4 status the V3 status maps to * @throws IllegalArgumentException if the V3 status has no current V4 mapping */ public static ClusterStatus toV4ClusterStatus( final com.netflix.genie.common.dto.ClusterStatus v3Status ) throws IllegalArgumentException { switch (v3Status) { case UP: return ClusterStatus.UP; case TERMINATED: return ClusterStatus.TERMINATED; case OUT_OF_SERVICE: return ClusterStatus.OUT_OF_SERVICE; default: throw new IllegalArgumentException("Unmapped V3 status: " + v3Status); } } /** * Attempt to convert a Cluster status string into a known enumeration value from {@link ClusterStatus}. * * @param status The status string. Not null or empty. * @return An {@link ClusterStatus} instance * @throws IllegalArgumentException If the string couldn't be converted */ public static ClusterStatus toV4ClusterStatus(final String status) throws IllegalArgumentException { if (StringUtils.isBlank(status)) { throw new IllegalArgumentException("No cluster status entered. Unable to convert."); } final String upperCaseStatus = status.toUpperCase(); try { return ClusterStatus.valueOf(upperCaseStatus); } catch (final IllegalArgumentException e) { // TODO: Remove this eventually once we're satisfied v3 statuses have been flushed // Since it may be a remnant of V3 try the older one and map return toV4ClusterStatus(com.netflix.genie.common.dto.ClusterStatus.valueOf(upperCaseStatus)); } } /** * Convert a V4 {@link ClusterStatus} to a V3 {@link com.netflix.genie.common.dto.ClusterStatus}. * * @param v4Status The V4 status to convert * @return The V3 status the V4 status maps to * @throws IllegalArgumentException If the V4 status has no current V3 mapping */ public static com.netflix.genie.common.dto.ClusterStatus toV3ClusterStatus( final ClusterStatus v4Status ) throws IllegalArgumentException { switch (v4Status) { case UP: return com.netflix.genie.common.dto.ClusterStatus.UP; case TERMINATED: return com.netflix.genie.common.dto.ClusterStatus.TERMINATED; case OUT_OF_SERVICE: return com.netflix.genie.common.dto.ClusterStatus.OUT_OF_SERVICE; default: throw new IllegalArgumentException("Unmapped V4 status: " + v4Status); } } /** * Convert a V3 {@link com.netflix.genie.common.dto.JobStatus} to a V4 {@link JobStatus}. * * @param v3Status The V3 status to convert * @return The V4 status the V3 status maps to * @throws IllegalArgumentException if the V3 status has no current V4 mapping */ public static JobStatus toV4JobStatus( final com.netflix.genie.common.dto.JobStatus v3Status ) throws IllegalArgumentException { switch (v3Status) { case ACCEPTED: return JobStatus.ACCEPTED; case CLAIMED: return JobStatus.CLAIMED; case FAILED: return JobStatus.FAILED; case INIT: return JobStatus.INIT; case INVALID: return JobStatus.INVALID; case KILLED: return JobStatus.KILLED; case RESERVED: return JobStatus.RESERVED; case RESOLVED: return JobStatus.RESOLVED; case RUNNING: return JobStatus.RUNNING; case SUCCEEDED: return JobStatus.SUCCEEDED; default: throw new IllegalArgumentException("Unmapped V3 status: " + v3Status); } } /** * Convert a V4 {@link JobStatus} to a V3 {@link com.netflix.genie.common.dto.JobStatus}. * * @param v4Status The V4 status to convert * @return The V3 status the V4 status maps to * @throws IllegalArgumentException If the V4 status has no current V3 mapping */ public static com.netflix.genie.common.dto.JobStatus toV3JobStatus( final JobStatus v4Status ) throws IllegalArgumentException { switch (v4Status) { case ACCEPTED: return com.netflix.genie.common.dto.JobStatus.ACCEPTED; case CLAIMED: return com.netflix.genie.common.dto.JobStatus.CLAIMED; case FAILED: return com.netflix.genie.common.dto.JobStatus.FAILED; case INIT: return com.netflix.genie.common.dto.JobStatus.INIT; case INVALID: return com.netflix.genie.common.dto.JobStatus.INVALID; case KILLED: return com.netflix.genie.common.dto.JobStatus.KILLED; case RESERVED: return com.netflix.genie.common.dto.JobStatus.RESERVED; case RESOLVED: return com.netflix.genie.common.dto.JobStatus.RESOLVED; case RUNNING: return com.netflix.genie.common.dto.JobStatus.RUNNING; case SUCCEEDED: return com.netflix.genie.common.dto.JobStatus.SUCCEEDED; default: throw new IllegalArgumentException("Unmapped V4 status: " + v4Status); } } /** * Attempt to convert a Job status string into a known enumeration value from {@link JobStatus}. * * @param status The status string. Not null or empty. * @return A {@link JobStatus} instance * @throws IllegalArgumentException If the string couldn't be converted */ public static JobStatus toV4JobStatus(final String status) throws IllegalArgumentException { if (StringUtils.isBlank(status)) { throw new IllegalArgumentException("No job status entered. Unable to convert."); } final String upperCaseStatus = status.toUpperCase(); try { return JobStatus.valueOf(upperCaseStatus); } catch (final IllegalArgumentException e) { // TODO: Remove this eventually once we're satisfied v3 statuses have been flushed // Since it may be a remnant of V3 try the older one and map return toV4JobStatus(com.netflix.genie.common.dto.JobStatus.valueOf(upperCaseStatus)); } } /** * Convert an internal {@link Criterion} to a v3 {@link com.netflix.genie.common.dto.Criterion}. * * @param criterion The internal criterion representation to convert * @return The v3 API representation */ public static com.netflix.genie.common.dto.Criterion toV3Criterion(final Criterion criterion) { final com.netflix.genie.common.dto.Criterion.Builder builder = new com.netflix.genie.common.dto.Criterion.Builder(); criterion.getId().ifPresent(builder::withId); criterion.getName().ifPresent(builder::withName); criterion.getStatus().ifPresent(builder::withStatus); criterion.getVersion().ifPresent(builder::withVersion); builder.withTags(criterion.getTags()); return builder.build(); } /** * Convert internal {@link ComputeResources} to the V3 API {@link RuntimeResources} representation. * * @param computeResources The {@link ComputeResources} to convert * @return The same data within a new {@link RuntimeResources} instance */ public static RuntimeResources toV3RuntimeResources(final ComputeResources computeResources) { final RuntimeResources.Builder builder = new RuntimeResources.Builder(); computeResources.getCpu().ifPresent(builder::withCpu); computeResources.getGpu().ifPresent(builder::withGpu); computeResources.getMemoryMb().ifPresent(builder::withMemoryMb); computeResources.getDiskMb().ifPresent(builder::withDiskMb); computeResources.getNetworkMbps().ifPresent(builder::withNetworkMbps); return builder.build(); } /** * Convert the V3 API {@link RuntimeResources} to the internal {@link ComputeResources} representation. * * @param runtimeResources The {@link RuntimeResources} to convert * @return The same data within a new {@link ComputeResources} instance */ public static ComputeResources toComputeResources(final RuntimeResources runtimeResources) { final ComputeResources.Builder builder = new ComputeResources.Builder(); runtimeResources.getCpu().ifPresent(builder::withCpu); runtimeResources.getGpu().ifPresent(builder::withGpu); runtimeResources.getMemoryMb().ifPresent(builder::withMemoryMb); runtimeResources.getDiskMb().ifPresent(builder::withDiskMb); runtimeResources.getNetworkMbps().ifPresent(builder::withNetworkMbps); return builder.build(); } /** * Convert the internal {@link Image} to the V3 API {@link ContainerImage} representation. * * @param image The {@link Image} to convert * @return The same data within a new {@link ContainerImage} instance */ public static ContainerImage toV3ContainerImage(final Image image) { final ContainerImage.Builder builder = new ContainerImage.Builder(); image.getName().ifPresent(builder::withName); image.getTag().ifPresent(builder::withTag); builder.withArguments(image.getArguments()); return builder.build(); } /** * Convert the V3 API representation of {@link ContainerImage} to the internal {@link Image} representation. * * @param containerImage The {@link ContainerImage} to convert * @return The {@link Image} representation */ public static Image toImage(final ContainerImage containerImage) { final Image.Builder builder = new Image.Builder(); containerImage.getName().ifPresent(builder::withName); containerImage.getTag().ifPresent(builder::withTag); builder.withArguments(containerImage.getArguments()); return builder.build(); } /** * This utility takes a pre-existing {@link com.netflix.genie.common.dto.Criterion} that would have been submitted * by a call to the V3 command APIs (create/update/patch) and makes sure it doesn't contain any {@code genie.id} or * {@code genie.name} tags. If it does it puts their values in the proper place within the new {@link Criterion} * which is returned. This exists in case people take the tags returned in a V3 resource call (from a cluster) and * just copy them into their tags for a {@link Command} cluster criterion. If we don't check this the criterion * will never match. * * @param criterion The originally {@link Criterion} from the user in the V3 command API * @return A new correct V4 {@link Criterion} which should be used for subsequent processing * @throws IllegalArgumentException If the resulting criterion is invalid */ @VisibleForTesting static Criterion toV4CommandClusterCriterion( final com.netflix.genie.common.dto.Criterion criterion ) throws IllegalArgumentException { final Criterion.Builder builder = new Criterion.Builder(); criterion.getId().ifPresent(builder::withId); criterion.getName().ifPresent(builder::withName); criterion.getStatus().ifPresent(builder::withStatus); criterion.getVersion().ifPresent(builder::withVersion); // Note: We will override the above id or name with the value of genie.id or genie.name if they exist // due to assumption this is what user intended when using those specific tags final ImmutableSet.Builder<String> tagBuilder = ImmutableSet.builder(); for (final String tag : criterion.getTags()) { if (tag.startsWith(GENIE_ID_PREFIX)) { builder.withId(StringUtils.removeStart(tag, GENIE_ID_PREFIX)); } else if (tag.startsWith(GENIE_NAME_PREFIX)) { builder.withName(StringUtils.removeStart(tag, GENIE_NAME_PREFIX)); } else { tagBuilder.add(tag); } } builder.withTags(tagBuilder.build()); return builder.build(); } private static Set<String> toV4Tags(final Set<String> tags) { return tags .stream() .filter(tag -> !tag.startsWith(GENIE_ID_PREFIX) && !tag.startsWith(GENIE_NAME_PREFIX)) .collect(Collectors.toSet()); } }
2,197
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/dtos/converters/package-info.java
/* * * Copyright 2018 Netflix, Inc. * * Licensed 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 for converting gRPC messages to V4 DTOs and vice versa. * * @author tgianos * @since 4.0.0 */ @ParametersAreNonnullByDefault package com.netflix.genie.common.internal.dtos.converters; import javax.annotation.ParametersAreNonnullByDefault;
2,198
0
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal
Create_ds/genie/genie-common-internal/src/main/java/com/netflix/genie/common/internal/properties/RegexDirectoryManifestProperties.java
/* * * Copyright 2020 Netflix, Inc. * * Licensed 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 com.netflix.genie.common.internal.properties; import com.google.common.collect.Sets; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotBlank; import java.util.Set; /** * Properties for {@link com.netflix.genie.common.internal.util.RegexDirectoryManifestFilter}. * * @author mprimi * @since 4.0.0 */ @ConfigurationProperties(prefix = RegexDirectoryManifestProperties.PROPERTY_PREFIX) @Getter @Setter @Validated public class RegexDirectoryManifestProperties { /** * Properties prefix. */ public static final String PROPERTY_PREFIX = "genie.jobs.files.filter"; private boolean caseSensitiveMatching = true; private Set<@NotBlank String> fileRejectPatterns = Sets.newHashSet(); private Set<@NotBlank String> directoryRejectPatterns = Sets.newHashSet(); private Set<@NotBlank String> directoryTraversalRejectPatterns = Sets.newHashSet(); }
2,199