index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring/test/DatabseTest.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.test;
import org.apache.airavata.tools.workflow.monitoring.Server;
import org.apache.airavata.tools.workflow.monitoring.SummeryDB;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
import junit.framework.TestCase;
public class DatabseTest extends TestCase {
public void testDatabaseInsert() {
// new FaultMessagesDB(new JdbcStorage(Server.DB_CONFIG_NAME, true)).insert(PublishSendingFaultTest.workflowID,
// PublishSendingFaultTest.message);
SummeryDB summeryDB = new SummeryDB(new JdbcStorage(Server.DB_CONFIG_NAME, true));
summeryDB.insert("testid", null, null);
summeryDB.edit("testid", "TERMINATED");
}
} | 8,700 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring/test/MonitorTest.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.test;
import wsmg.WseClientAPI;
import org.apache.airavata.tools.workflow.monitoring.Server;
import junit.framework.TestCase;
public class MonitorTest extends TestCase {
public static final String brokerurl = "http://127.0.0.1:8888";
public static String message = "<wor:monitorWorkflow "
+ "xmlns:wor=\"http://lead.extreme.indiana.edu/namespaces/2006/06/workflow_tracking\">"
+ "<wor:notificationSource " + "wor:serviceID=\"urn:qname:http://www.extreme.indiana.edu/lead:WCS\""
+ "wor:workflowID=\"tag:gpel.leadproject.org,2006:6BD/WRFForecastWithADASInitializedData/instance7155555\""
+ "wor:workflowTimestep=\"18\" wor:workflowNodeID=\"WCS\" />"
+ "<wor:monitoringDuration>12</wor:monitoringDuration>" + "<wor:emailTo>cherath@indiana.edu</wor:emailTo>"
+ "<wor:timestamp>2007-01-20T10:53:28-05:00</wor:timestamp>" + "</wor:monitorWorkflow>";
public void testMonitor() {
// Server.main(null);
WseClientAPI client = new WseClientAPI();
client.publish(brokerurl, Server.monitoringTopic, message);
}
}
| 8,701 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring/test/WorkflowLifeCycleTest.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.test;
import wsmg.WseClientAPI;
import junit.framework.TestCase;
public class WorkflowLifeCycleTest extends TestCase {
private String worklowTerminated = "<wor:workflowTerminated xmlns:wor='http://lead.extreme.indiana.edu/namespaces/2006/06/workflow_tracking'><wor:notificationSource wor:serviceID='tag:gpel.leadproject.org,2006:71N/TestCISimpleEchoWorkflow/instance36'/><wor:timestamp>2007-02-05T00:21:33-05:00</wor:timestamp></wor:workflowTerminated>";
private String worklowStarted = "<wor:workflowInitialized xmlns:wor='http://lead.extreme.indiana.edu/namespaces/2006/06/workflow_tracking'><wor:notificationSource wor:serviceID='tag:gpel.leadproject.org,2006:71N/TestCISimpleEchoWorkflow/instance36'/><wor:timestamp>2007-02-04T23:57:20-05:00</wor:timestamp></wor:workflowInitialized>";
public void testStartWorkflow() {
WseClientAPI client = new WseClientAPI();
client.publish(MonitorTest.brokerurl, "anytopic-since-we-use-xpath", worklowStarted);
}
} | 8,702 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/WorkflowMonitoringException.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
public class WorkflowMonitoringException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public WorkflowMonitoringException() {
super();
// TODO Auto-generated constructor stub
}
public WorkflowMonitoringException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public WorkflowMonitoringException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public WorkflowMonitoringException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
} | 8,703 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/Util.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.io.StringReader;
import java.util.Iterator;
import org.xmlpull.v1.builder.XmlAttribute;
import org.xmlpull.v1.builder.XmlElement;
import org.xmlpull.v1.builder.XmlInfosetBuilder;
import org.xmlpull.v1.builder.XmlNamespace;
import xsul.XmlConstants;
public class Util {
private final static XmlInfosetBuilder builder = XmlConstants.BUILDER;
public static String getWorkflowID(String message, String firstElement, String attrName) {
XmlElement messageEl = builder.parseFragmentFromReader(new StringReader(message));
XmlElement body = messageEl.element(null, "Body");
if (body == null)
return null;
XmlElement firstElmt = body.element(null, firstElement);
if (firstElmt == null)
return null;
XmlElement source = firstElmt.element(null, "notificationSource");
if (source == null)
return null;
XmlNamespace ns = source.getNamespace();
String workflowid = source.getAttributeValue(ns.getNamespaceName(), attrName);
return workflowid;
}
public static String getDN(String message) {
XmlElement messageEl = builder.parseFragmentFromReader(new StringReader(message));
XmlElement body = messageEl.element(null, "Body");
if (body == null)
return null;
XmlElement firstelemt = body.element(null, "invokingService");
if (firstelemt == null)
return null;
XmlElement annotation = firstelemt.element(null, "annotation");
if (null == annotation)
return null;
XmlElement dn = annotation.element(null, "userDN");
if (null == dn)
return null;
Iterator children = dn.children();
if (children.hasNext()) {
return (String) children.next();
}
return null;
}
public static String getInitialID(String message) {
XmlElement messageEl = builder.parseFragmentFromReader(new StringReader(message));
XmlElement body = messageEl.element(null, "Body");
if (body == null)
return null;
XmlElement firstelemt = body.element(null, "invokingService");
if (firstelemt == null)
return null;
XmlElement request = firstelemt.element(null, "request");
if (null == request)
return null;
XmlElement header = request.element(null, "header");
if (null == header) {
return null;
}
XmlElement secHeader = header.element(null, "Header");
if (secHeader == null)
return null;
XmlElement context = secHeader.element(null, "context");
XmlElement id = context.element(null, "workflow-instance-id");
if (null == context)
return null;
Iterator itr = id.children();
if (itr.hasNext()) {
return (String) itr.next();
}
return null;
}
} | 8,704 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/EmailAlertHander.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.xmlpull.v1.builder.Iterable;
import org.xmlpull.v1.builder.XmlElement;
import xsul.MLogger;
public class EmailAlertHander implements AlertHandler {
private static MLogger log = MLogger.getLogger();
private static final String drlead = "drlead@extreme.indiana.edu";
private static final String messageBoundary = "\n\n------------------\n\n";
private static final String subject = "Workflow Monitoring service: Error in workflow with id=";
private static final String from = "Do not Reply<workflow@extreme.indiana.edu>";
private Vector<String> emails = new Vector<String>();
public EmailAlertHander(Iterable iterable) {
Iterator iterator = iterable.iterator();
while (iterator.hasNext()) {
XmlElement element = (XmlElement) iterator.next();
emails.add(element.requiredTextContent());
}
}
public EmailAlertHander() {
this.emails.add(this.drlead);
}
public void alert(Vector<String> payload, String workflowID) {
String mailMessage = "";
for (String message : payload) {
mailMessage += message;
mailMessage += messageBoundary;
}
this.postMail(this.getStingArray(this.emails), subject + workflowID, mailMessage, from);
}
public void postMail(String recipients[], String subject, String message, String from) {
boolean debug = false;
log.finest("Intiating emai");
// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "rainier.extreme.indiana.edu");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
try {
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if
// you Want
// msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
} catch (AddressException e) {
throw new WorkflowMonitoringException(e);
} catch (MessagingException e) {
throw new WorkflowMonitoringException(e);
}
log.finest("Sent mail " + subject);
}
private String[] getStingArray(Vector<String> vector) {
String[] array = new String[vector.size()];
for (int i = 0; i < vector.size(); ++i) {
array[i] = vector.get(i);
}
return array;
}
} | 8,705 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/FaultReportorThread.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.util.Date;
import java.util.Vector;
import xsul.MLogger;
public class FaultReportorThread implements Runnable {
private static MLogger log = MLogger.getLogger();
private ServerContext context;
public FaultReportorThread(ServerContext context) {
this.context = context;
}
public void run() {
while (true) {
try {
Thread.sleep(context.getReportorSleepTime());
log.finest("Running Reporter thread after sleeptime secs=" + (context.getReportorSleepTime() / 1000));
Date now = new Date(System.currentTimeMillis());
for (String key : context.getMonitoredWorkflows().keySet()) {
Workflow workflow = context.getMonitoredWorkflows().get(key);
if (workflow.getExpirationTime().before(now)) {
// synchronized since once workflow is removed from context no one
// could add more
context.removeWorkflow(workflow.getWorkflowID());
}
Vector messages = workflow.getAllMessagesAndReset();
if (messages.size() > 0) {
log.finest("Reporting faults on workflow" + workflow.getWorkflowID());
this.sendFaults(messages, workflow.getAlertHandler(), workflow.getWorkflowID());
}
}
} catch (Exception e) {
log.caught(e);
}
}
}
public void sendFaults(Vector faultMessages, AlertHandler alertHandler, String workflowid) {
alertHandler.alert(faultMessages, workflowid);
}
} | 8,706 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/FaultMessageHandler.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.io.StringReader;
import org.xmlpull.v1.builder.XmlElement;
import org.xmlpull.v1.builder.XmlInfosetBuilder;
import wsmg.NotificationHandler;
import xsul.MLogger;
import xsul.XmlConstants;
public class FaultMessageHandler implements NotificationHandler, StatusConstants {
private static MLogger log = MLogger.getLogger();
private ServerContext context;
private FaultMessagesDB messageDB;
private SummeryDB summeryTbl;
public FaultMessageHandler(ServerContext context) {
this.context = context;
this.messageDB = new FaultMessagesDB(context.getDatabase());
this.summeryTbl = new SummeryDB(context.getDatabase());
}
public void handleNotification(String message) {
String workflowID = Util.getWorkflowID(message, Server.SENDING_FAULT, "workflowID");
if (workflowID != null) {
this.messageDB.insert(workflowID, message);
boolean success = context.checkAndRegistorMonitoredWorkflow(workflowID, message);
if (success) {
log.finest("Received a fault with workflowid" + workflowID + message);
} else {
log.warning("Failed registring fault message" + workflowID);
}
this.summeryTbl.edit(workflowID, STATUS_FAILED);
}
}
} | 8,707 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/FaultMessagesDB.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
public class FaultMessagesDB {
private static final String TABLE_NAME = "faults";
private static final String SQL_INSERT_STATEMENT = "INSERT INTO " + TABLE_NAME + " (xml, workflowid) "
+ "VALUES(?,?)";
private JdbcStorage db;
public FaultMessagesDB(JdbcStorage db) {
this.db = db;
}
public void insert(String workflowID, String message) {
try {
Connection connection = db.connect();
PreparedStatement stmt = connection.prepareStatement(SQL_INSERT_STATEMENT);
byte[] buffer;
ByteArrayOutputStream output = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(output);
out.writeObject(message);
buffer = output.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(buffer);
stmt.setBinaryStream(1, in, buffer.length);
stmt.setString(2, workflowID);
db.insert(stmt);
stmt.close();
connection.commit();
db.closeConnection(connection);
} catch (SQLException e) {
throw new WorkflowMonitoringException(e);
} catch (IOException e) {
throw new WorkflowMonitoringException(e);
}
}
}
| 8,708 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/SummeryDB.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
public class SummeryDB implements StatusConstants {
private static final String TABLE_NAME = "summary";
private static String SQL_INSERT_STMT = "INSERT INTO " + TABLE_NAME
+ " (workflowid, templateid, status, startTime, username) VALUES (?,?,?,?,?)";
private static String SQL_UPDATE_STMT = "UPDATE " + TABLE_NAME + " set status=?, endTime=? WHERE workflowid=?";
private JdbcStorage db;
public SummeryDB(JdbcStorage db) {
this.db = db;
}
public void insert(String workflowID, String templateID, String username) {
if (null == templateID) {
templateID = workflowID.substring(0, workflowID.indexOf("/instance"));
}
try {
Connection connection = db.connect();
PreparedStatement stmt = connection.prepareStatement(SQL_INSERT_STMT);
stmt.setString(1, workflowID);
stmt.setString(2, templateID);
stmt.setString(3, STATUS_RUNNING);
stmt.setBigDecimal(4, new BigDecimal(System.currentTimeMillis()));
stmt.setString(5, username);
db.insert(stmt);
stmt.close();
db.closeConnection(connection);
} catch (SQLException e) {
throw new WorkflowMonitoringException(e);
}
}
public void edit(String workflowid, String status) {
try {
Connection connection = db.connect();
PreparedStatement stmt = connection.prepareStatement(SQL_UPDATE_STMT);
stmt.setString(1, status);
stmt.setBigDecimal(2, new BigDecimal(System.currentTimeMillis()));
stmt.setString(3, workflowid);
stmt.executeUpdate();
stmt.close();
db.closeConnection(connection);
} catch (SQLException e) {
throw new WorkflowMonitoringException(e);
}
}
} | 8,709 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/AlertFactory.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import org.xmlpull.v1.builder.XmlElement;
public class AlertFactory {
public static AlertHandler createAlertHandler(XmlElement source) {
if (source.element(null, "emailTo") != null) {
return new EmailAlertHander(source.elements(source.getNamespace(), "emailTo"));
}
return new EmailAlertHander();
}
} | 8,710 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/ServerContext.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.util.Hashtable;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
public class ServerContext {
private JdbcStorage db;
private Hashtable<String, Workflow> monitoredWorkflows = new Hashtable<String, Workflow>();
private long reportorThreadSleeptime = 300000;
public ServerContext(JdbcStorage database, long sleepMilisecs) {
this.db = database;
this.reportorThreadSleeptime = sleepMilisecs;
}
public JdbcStorage getDatabase() {
return db;
}
public Hashtable<String, Workflow> getMonitoredWorkflows() {
return monitoredWorkflows;
}
public void addWorkflow(Workflow workflow) {
if (this.monitoredWorkflows.get(workflow.getWorkflowID()) == null) {
this.monitoredWorkflows.put(workflow.getWorkflowID(), workflow);
}
}
public Workflow getWorkflow(String workflowID) {
return this.monitoredWorkflows.get(workflowID);
}
public void removeWorkflow(String workflowID) {
this.monitoredWorkflows.remove(workflowID);
}
public boolean checkAndRegistorMonitoredWorkflow(String workflowID, String message) {
Workflow workflow = this.monitoredWorkflows.get(workflowID);
if (workflow != null) {
workflow.addFaultMessage(message);
return true;
} else {
return false;
}
}
public long getReportorSleepTime() {
return this.reportorThreadSleeptime;
}
public void setReportorSleepTime(long time) {
this.reportorThreadSleeptime = time;
}
} | 8,711 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/AlertHandler.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.util.Vector;
public interface AlertHandler {
public void alert(Vector<String> payload, String workflowID);
} | 8,712 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/ManagementHandler.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import wsmg.NotificationHandler;
import xsul.MLogger;
public class ManagementHandler implements NotificationHandler {
private static MLogger log = MLogger.getLogger();
private ServerContext context;
public ManagementHandler(ServerContext context) {
this.context = context;
}
/*
* (non-Javadoc)
*
* @see wsmg.NotificationHandler#handleNotification(java.lang.String)
*/
public void handleNotification(String message) {
try {
Workflow workflow = new Workflow();
if (workflow.parse(message)) {
context.addWorkflow(workflow);
log.finest("Added a workflow to monitor with workflow id=" + workflow.getWorkflowID());
} else {
log.fine("The monitoring request is ignored due to message format error:" + message);
}
} catch (WorkflowMonitoringException e) {
log.caught("Error occured in intiating a monitor", e.getMessage(), e);
}
}
} | 8,713 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/Server.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
import org.apache.airavata.tools.workflow.monitoring.status.WorkflowStartedStatusHandler;
import org.apache.airavata.tools.workflow.monitoring.status.WorkflowTerminatedHandler;
import org.exolab.jms.util.CommandLine;
import wsmg.WseClientAPI;
public class Server {
public static final String SENDING_FAULT = "sendingFault";
public static final String WORKFLOW_INITIATED = "invokingService";
public static final String WORKFLOW_TERMINATED = "workflowTerminated";
private static final String XPATH_SENDING_FAULT = "/" + SENDING_FAULT;
private static final String XPATH_WORKFLOW_INTIATED = "/" + WORKFLOW_INITIATED;
private static final String XPATH_WORKFLOW_TERMINATED = "/" + WORKFLOW_TERMINATED;
private static int faultListenerPort = 5555;
private static int managementListenerPort = 5556;
private static int successListenerPort = 5557;
private static int initiatedListerPort = 5558;
public static final String DB_CONFIG_NAME = "db.config";
private static long senderThreadSleep = 120000;// 1 minutes
public static String monitoringTopic = "MonitorWorkflow";
public static String brokerLocation;
public Server() {
}
/**
* @param args
*/
public static void main(String[] args) {
CommandLine cmdline = new CommandLine(args);
brokerLocation = cmdline.value("broker", "http://ogceportal.iu.teragrid.org:12346/");
faultListenerPort = Integer.parseInt(cmdline.value("fport", "5555"));
managementListenerPort = Integer.parseInt(cmdline.value("mport", "5556"));
senderThreadSleep = Integer.parseInt(cmdline.value("sleepminutes", "2")) * 60000;
new Server().start();
}
public void start() {
ServerContext serverContext = new ServerContext(new JdbcStorage(DB_CONFIG_NAME, true), senderThreadSleep);
FaultMessageHandler handler = new FaultMessageHandler(serverContext);
WseClientAPI client = new WseClientAPI();
int consumer = client.startConsumerService(faultListenerPort, handler);
client.subscribe(brokerLocation, getConsumeEPR(consumer), null, XPATH_SENDING_FAULT);
WseClientAPI successClient = new WseClientAPI();
successListenerPort = successClient.startConsumerService(successListenerPort, new WorkflowTerminatedHandler(
serverContext));
successClient.subscribe(brokerLocation, getConsumeEPR(successListenerPort), null, XPATH_WORKFLOW_TERMINATED);
WseClientAPI initiatedClient = new WseClientAPI();
initiatedListerPort = initiatedClient.startConsumerService(initiatedListerPort,
new WorkflowStartedStatusHandler(serverContext));
initiatedClient.subscribe(brokerLocation, getConsumeEPR(initiatedListerPort), null, XPATH_WORKFLOW_INTIATED);
ManagementHandler managementHandler = new ManagementHandler(serverContext);
WseClientAPI managementClient = new WseClientAPI();
int managementPort = managementClient.startConsumerService(managementListenerPort, managementHandler);
client.subscribe(brokerLocation, getConsumeEPR(managementPort), monitoringTopic);
new Thread(new FaultReportorThread(serverContext)).start();
}
private String getConsumeEPR(int port) {
String epr;
try {
epr = InetAddress.getLocalHost().getHostAddress() + ":" + port;
} catch (UnknownHostException e) {
throw new WorkflowMonitoringException(e);
}
System.out.println(epr);
return epr;
}
} | 8,714 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/Workflow.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
import java.io.StringReader;
import java.util.Date;
import java.util.Vector;
import org.xmlpull.v1.builder.Iterable;
import org.xmlpull.v1.builder.XmlElement;
import org.xmlpull.v1.builder.XmlInfosetBuilder;
import org.xmlpull.v1.builder.XmlNamespace;
import xsul.XmlConstants;
public class Workflow {
private final static XmlInfosetBuilder builder = XmlConstants.BUILDER;
private static final int DEFAULT_EXPIRATION_HOURS = 10;
private String workflowID;
private Vector<String> faultMessages = new Vector<String>();
private Date expirationTime;
private long firstFaultArrivalTimeForCurrentBatch;
// TODA abstract this to capture generic "Alert" mechanism
private Vector<String> emails = new Vector<String>();
private AlertHandler alertHandler;
public Workflow() {
}
public boolean parse(String message) {
XmlElement messageEl = builder.parseFragmentFromReader(new StringReader(message));
XmlElement body = messageEl.element(null, "Body");
if (body == null) {
return false;
}
XmlElement mon = body.element(null, "monitorWorkflow");
if (mon == null) {
return false;
}
XmlElement source = mon.element(null, "notificationSource");
if (source == null) {
return false;
}
XmlNamespace ns = source.getNamespace();
this.workflowID = source.getAttributeValue(ns.getNamespaceName(), "workflowID");
if (this.workflowID == null) {
return false;
}
XmlElement duration = mon.element(null, "monitoringDuration");
if (duration == null) {
this.expirationTime = this.getDateAfter(DEFAULT_EXPIRATION_HOURS);
} else {
this.expirationTime = this.getDateAfter(this.getHours(duration.requiredTextContent()));
}
this.alertHandler = AlertFactory.createAlertHandler(mon);
return true;
}
// No need for mutex synchronisation the code is written with
// global event ordering
public void addFaultMessage(String message) {
if (this.faultMessages.size() == 0) {
this.firstFaultArrivalTimeForCurrentBatch = System.currentTimeMillis();
}
this.faultMessages.add(message);
}
// do not require synchromisation since if a message is missed it will be
// caught in the next lot;
public Vector getAllMessagesAndReset() {
Vector oldmessages = this.faultMessages;
this.faultMessages = new Vector<String>();
return oldmessages;
}
public Vector<String> getFaultMessages() {
return faultMessages;
}
public String getWorkflowID() {
return workflowID;
}
public Date getExpirationTime() {
return expirationTime;
}
public long getFirstFaultArrivalTimeForCurrentBatch() {
return this.firstFaultArrivalTimeForCurrentBatch;
}
public Date getDateAfter(int hours) {
long now = System.currentTimeMillis();
long future = now + hours * 60 * 60 * 1000;
return new Date(future);
}
public int getHours(String str) {
return Integer.parseInt(str);
}
public AlertHandler getAlertHandler() {
return alertHandler;
}
}
| 8,715 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/StatusConstants.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring;
public interface StatusConstants {
public static final String STATUS_RUNNING = "RUNNING";
public static final String STATUS_SUCCESSFUL = "SUCCESSFUL";
public static final String STATUS_FAILED = "FAILED";
}
| 8,716 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/status/WorkflowStartedStatusHandler.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.status;
import org.apache.airavata.tools.workflow.monitoring.Server;
import org.apache.airavata.tools.workflow.monitoring.ServerContext;
import org.apache.airavata.tools.workflow.monitoring.SummeryDB;
import org.apache.airavata.tools.workflow.monitoring.Util;
import wsmg.NotificationHandler;
import xsul.MLogger;
public class WorkflowStartedStatusHandler implements NotificationHandler {
private static MLogger log = MLogger.getLogger();
private ServerContext context;;
private SummeryDB summeryTbl;
public WorkflowStartedStatusHandler(ServerContext context) {
this.context = context;
this.summeryTbl = new SummeryDB(context.getDatabase());
}
public void handleNotification(String message) {
String workflowID = Util.getInitialID(message);
if (null != workflowID) {
log.finest("Adding workflowStarted entry " + message);
this.context.removeWorkflow(workflowID);
this.summeryTbl.insert(workflowID, null, Util.getDN(message));
}else{
log.warning("Got null for workflow started"+message);
}
}
} | 8,717 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/status/WorkflowTerminatedHandler.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.status;
import org.apache.airavata.tools.workflow.monitoring.Server;
import org.apache.airavata.tools.workflow.monitoring.ServerContext;
import org.apache.airavata.tools.workflow.monitoring.StatusConstants;
import org.apache.airavata.tools.workflow.monitoring.SummeryDB;
import org.apache.airavata.tools.workflow.monitoring.Util;
import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage;
import sun.security.acl.WorldGroupImpl;
import wsmg.NotificationHandler;
import xsul.MLogger;
public class WorkflowTerminatedHandler implements NotificationHandler, StatusConstants {
private static MLogger log = MLogger.getLogger();
private ServerContext context;
private SummeryDB summeryTbl;
public WorkflowTerminatedHandler(ServerContext context) {
this.context = context;
this.summeryTbl = new SummeryDB(context.getDatabase());
}
public void handleNotification(String message) {
String workflowID = Util.getWorkflowID(message, Server.WORKFLOW_TERMINATED, "serviceID");
if (workflowID != null) {
this.summeryTbl.edit(workflowID, STATUS_SUCCESSFUL);
this.context.removeWorkflow(workflowID);
log.finest("Adding Finished entry " + message);
} else {
log.warning("goat a null workflowid for terminated handler" + message);
}
}
} | 8,718 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/db/JdbcStorage.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcStorage {
private ConfigurationParamsReader config;
// private String jdbcUrl=
// "jdbc:mysql://156.56.104.175:3306/wsnt?user=root";
private String jdbcUrl = null;;
private PreparedStatement stmt = null;
private ResultSet rs = null;
private ResultSetMetaData rsmd = null;
// private Connection conn = null;
private ConnectionPool connectionPool;
private String jdbcDriver;
public JdbcStorage(String fileName, boolean enableTransactions) {
config = new ConfigurationParamsReader(fileName);
jdbcUrl = config.getProperty("jdbcUrl");
jdbcDriver = config.getProperty("jdbcDriver");
try {
if (enableTransactions) {
connectionPool = new ConnectionPool(jdbcDriver, jdbcUrl, 10, 50, true, false,
Connection.TRANSACTION_SERIALIZABLE);
} else {
connectionPool = new ConnectionPool(jdbcDriver, jdbcUrl, 10, 50, true);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new RuntimeException("Failed to create database connection poll.", e);
}
}
public JdbcStorage(String fileName) {
this(fileName, false);
}
public Connection connect() throws SQLException {
Connection conn = connectionPool.getConnection();
return conn;
}
public void closeConnection(Connection conn) throws java.sql.SQLException {
connectionPool.free(conn);
}
public int update(String query) throws java.sql.SQLException {
int result = 0;
// connect();
Connection conn = connectionPool.getConnection();
stmt = conn.prepareStatement(query);
result = stmt.executeUpdate();
stmt.close();
connectionPool.free(conn);
return result;
}
/**
* This method is provided so that yo can have better control over the statement. For example: You can use
* stmt.setString to convert quotation mark automatically in an INSERT statement
*/
public int insert(PreparedStatement stmt) throws java.sql.SQLException {
int rows = 0;
rows = stmt.executeUpdate();
stmt.close();
return rows;
}
public int insert(String query) throws java.sql.SQLException {
int rows = 0;
Connection conn = connectionPool.getConnection();
stmt = conn.prepareStatement(query);
rows = stmt.executeUpdate();
stmt.close();
connectionPool.free(conn);
return rows;
}
public ResultSet query(String query) throws SQLException {
Connection conn = connectionPool.getConnection();
// Create a scrollable ResultSet so that I can use rs.last() to get
// total number of rows without using another COUNT in SQL query
Statement lstmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = lstmt.executeQuery(query);
connectionPool.free(conn);
return rs;
}
public int countRow(String tableName, String columnName) throws java.sql.SQLException {
String query = new String("SELECT COUNT(" + columnName + ") FROM " + tableName);
Connection conn = connectionPool.getConnection();
stmt = conn.prepareStatement(query);
rs = stmt.executeQuery();
rs.next();
int count = rs.getInt(1);
stmt.close();
connectionPool.free(conn);
return count;
}
}
| 8,719 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/db/ConnectionPool.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import javax.sql.DataSource;
public class ConnectionPool implements Runnable {
private long MAX_IDLE_TIME = 5 * 60 * 1000; // 5 minutes
private String driver, url, username, password, jdbcUrl;
private int initialConnections, maxConnections;
private boolean waitIfBusy;
private Vector availableConnections, busyConnections;
private boolean connectionPending = false;
private HashMap lastAccessTimeRecord = new HashMap();
private String urlType = "";
private DataSource datasource;
private boolean autoCommit = true;
private int transactionIsolation = Connection.TRANSACTION_NONE;
public ConnectionPool(String driver, String url, String username, String password, int initialConnections,
int maxConnections, boolean waitIfBusy) throws SQLException {
this(initialConnections, maxConnections, waitIfBusy);
this.driver = driver;
this.url = url;
this.username = username;
this.password = password;
urlType = "speratedURL";
createConnectionPool();
}
public ConnectionPool(String driver, String jdbcUrl, int initialConnections, int maxConnections,
boolean waitIfBusy, boolean autoCommit, int transactionIsolation) throws SQLException {
this(initialConnections, maxConnections, waitIfBusy);
this.driver = driver;
this.jdbcUrl = jdbcUrl;
urlType = "simpleURL";
this.autoCommit = autoCommit;
this.transactionIsolation = transactionIsolation;
createConnectionPool();
}
public ConnectionPool(String driver, String jdbcUrl, int initialConnections, int maxConnections, boolean waitIfBusy)
throws SQLException {
this(initialConnections, maxConnections, waitIfBusy);
this.driver = driver;
this.jdbcUrl = jdbcUrl;
urlType = "simpleURL";
createConnectionPool();
}
public ConnectionPool(DataSource dataSource, int initialConnections, int maxConnections, boolean waitIfBusy)
throws SQLException {
this(initialConnections, maxConnections, waitIfBusy);
urlType = "dataSource";
this.datasource = dataSource;
createConnectionPool();
}
protected ConnectionPool(int initialConnections, int maxConnections, boolean waitIfBusy) throws SQLException {
this.initialConnections = initialConnections;
this.maxConnections = maxConnections;
this.waitIfBusy = waitIfBusy;
if (initialConnections > maxConnections) {
initialConnections = maxConnections;
}
availableConnections = new Vector(initialConnections);
busyConnections = new Vector();
CleanUpThread cleanUpThread = new CleanUpThread();
new Thread(cleanUpThread).start();
}
private void createConnectionPool() throws SQLException {
for (int i = 0; i < initialConnections; i++) {
availableConnections.addElement(makeNewConnection());
}
}
public synchronized Connection getConnection() throws SQLException {
if (!availableConnections.isEmpty()) {
Connection existingConnection = (Connection) availableConnections.lastElement();
int lastIndex = availableConnections.size() - 1;
// System.out.println("ConnectionNo="+lastIndex);
availableConnections.removeElementAt(lastIndex);
long lastAccess = ((Long) lastAccessTimeRecord.get(existingConnection)).longValue();
// If connection on available list is closed (e.g.,
// it timed out), then remove it from available list
// and repeat the process of obtaining a connection.
// Also wake up threads that were waiting for a
// connection because maxConnection limit was reached.
if (existingConnection.isClosed()) {
notifyAll(); // Freed up a spot for anybody waiting
Connection connection = getConnection();
setTimeStamp(connection);
return (connection);
} else {
busyConnections.addElement(existingConnection);
setTimeStamp(existingConnection);
return existingConnection;
}
} else {
// Three possible cases:
// 1) You haven't reached maxConnections limit. So
// establish one in the background if there isn't
// already one pending, then wait for
// the next available connection (whether or not
// it was the newly established one).
// 2) You reached maxConnections limit and waitIfBusy
// flag is false. Throw SQLException in such a case.
// 3) You reached maxConnections limit and waitIfBusy
// flag is true. Then do the same thing as in second
// part of step 1: wait for next available connection.
if ((totalConnections() < maxConnections) && !connectionPending) {
makeBackgroundConnection();
} else if (!waitIfBusy) {
throw new SQLException("Connection limit reached");
}
// Wait for either a new connection to be established
// (if you called makeBackgroundConnection) or for
// an existing connection to be freed up.
try {
wait();
} catch (InterruptedException ie) {
}
// Someone freed up a connection, so try again.
Connection connection = getConnection();
setTimeStamp(connection);
return connection;
}
}
// You can't just make a new connection in the foreground
// when none are available, since this can take several
// seconds with a slow network connection. Instead,
// start a thread that establishes a new connection,
// then wait. You get woken up either when the new connection
// is established or if someone finishes with an existing
// connection.
private void makeBackgroundConnection() {
connectionPending = true;
try {
Thread connectThread = new Thread(this);
connectThread.start();
} catch (OutOfMemoryError oome) {
// Give up on new connection
}
}
public void run() {
try {
Connection connection = makeNewConnection();
synchronized (this) {
availableConnections.addElement(connection);
connectionPending = false;
notifyAll();
}
} catch (Exception e) { // SQLException or OutOfMemory
// Give up on new connection and wait for existing one
// to free up.
}
}
// This explicitly makes a new connection. Called in
// the foreground when initializing the ConnectionPool,
// and called in the background when running.
private Connection makeNewConnection() throws SQLException {
try {
// Load database driver if not already loaded
Class.forName(driver);
Connection connection;
// Establish network connection to database
if (urlType.equals("speratedURL")) {
connection = DriverManager.getConnection(url, username, password);
} else if (urlType.equals("simpleURL")) {
connection = DriverManager.getConnection(jdbcUrl);
} else { // if(urlType.equals("dataSource")){
connection = datasource.getConnection();
}
connection.setTransactionIsolation(this.transactionIsolation);
connection.setAutoCommit(this.autoCommit);
setTimeStamp(connection);
return connection;
} catch (ClassNotFoundException cnfe) {
// Simplify try/catch blocks of people using this by
// throwing only one exception type.
throw new SQLException("Can't find class for driver: " + driver);
}
}
private void setTimeStamp(Connection connection) {
lastAccessTimeRecord.put(connection, Long.valueOf(System.currentTimeMillis()));
}
// The database connection cannot be left idle for too long, otherwise TCP connection will be broken.
/**
* From http://forums.mysql.com/read.php?39,28450,57460#msg-57460 Okay, then it looks like wait_timeout on the
* server is killing your connection (it is set to 8 hours of idle time by default). Either set that value higher on
* your server, or configure your connection pool to not hold connections idle that long (I prefer the latter). Most
* folks I know that run MySQL with a connection pool in high-load production environments only let connections sit
* idle for a matter of minutes, since it only takes a few milliseconds to open a connection, and the longer one
* sits idle the more chance it will go "bad" because of a network hiccup or the MySQL server being restarted.
*
* @throws SQLException
*/
private boolean isConnectionStale(Connection connection) throws SQLException {
long currentTime = System.currentTimeMillis();
long lastAccess = ((Long) lastAccessTimeRecord.get(connection)).longValue();
if (currentTime - lastAccess > MAX_IDLE_TIME) {
// connection.close();
// System.out.println("*************JDBC Connection Stale!");
return true;
} else
return false;
}
private void closeStaleConnections() throws SQLException {
// close idle connections
Iterator iter = availableConnections.iterator();
while (iter.hasNext()) {
Connection existingConnection = (Connection) iter.next();
if (isConnectionStale(existingConnection)) {
existingConnection.close();
iter.remove();
}
}
// close busy connections that have been checked out for too long.
// This should not happen sinc ethis means program has bug for not releasing connections .
iter = busyConnections.iterator();
while (iter.hasNext()) {
Connection busyConnection = (Connection) iter.next();
if (isConnectionStale(busyConnection)) {
iter.remove();
busyConnection.close();
System.out
.println("****Connection has checked out too long. Forced release. Check the program for unReleased connection.");
}
}
}
public synchronized void free(Connection connection) {
busyConnections.removeElement(connection);
availableConnections.addElement(connection);
// Wake up threads that are waiting for a connection
notifyAll();
}
public synchronized int totalConnections() {
return (availableConnections.size() + busyConnections.size());
}
/**
* Close all the connections. Use with caution: be sure no connections are in use before calling. Note that you are
* not <I>required</I> to call this when done with a ConnectionPool, since connections are guaranteed to be closed
* when garbage collected. But this method gives more control regarding when the connections are closed.
*/
public synchronized void closeAllConnections() {
closeConnections(availableConnections);
availableConnections = new Vector();
closeConnections(busyConnections);
busyConnections = new Vector();
lastAccessTimeRecord.clear();
}
private void closeConnections(Vector connections) {
try {
for (int i = 0; i < connections.size(); i++) {
Connection connection = (Connection) connections.elementAt(i);
if (!connection.isClosed()) {
connection.close();
}
}
} catch (SQLException sqle) {
// Ignore errors; garbage collect anyhow
}
}
public synchronized String toString() {
String info = "ConnectionPool(" + url + "," + username + ")" + ", available=" + availableConnections.size()
+ ", busy=" + busyConnections.size() + ", max=" + maxConnections;
return (info);
}
class CleanUpThread implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(MAX_IDLE_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
closeStaleConnections();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} | 8,720 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/db/Configuration.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.db;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Vector;
/**
* Configuration interface.
*
*/
public interface Configuration {
/**
* Create an Configuration object that is a subset of this one. The new
* Configuration object contains every key from the current Configuration
* that starts with prefix. The prefix is removed from the keys in the
* subset.
*
* @param prefix
* The prefix used to select the properties.
*/
Configuration subset(String prefix);
/**
* Check if the configuration is empty.
*
* @return true is the configuration contains no key/value pair, false
* otherwise
*/
boolean isEmpty();
/**
* Check if the configuration contains the key.
*
* @return true is the configuration contains a value for this key, false
* otherwise
*/
boolean containsKey(String key);
/**
* Add a property to the configuration. If it already exists then the value
* stated here will be added to the configuration entry. For example, if
*
* resource.loader = file
*
* is already present in the configuration and you
*
* addProperty("resource.loader", "classpath")
*
* Then you will end up with a Vector like the following:
*
* ["file", "classpath"]
*
* @param key
* The Key to add the property to.
* @param token
* The Value to add.
*/
void addProperty(String key, Object value);
/**
* Set a property, this will replace any previously set values. Set values
* is implicitly a call to clearProperty(key), addProperty(key,value).
*
* @param key
* The key of the property to change
* @param value
* The new value
*/
void setProperty(String key, Object value);
/**
* Clear a property in the configuration.
*
* @param key
* the key to remove along with corresponding value.
*/
void clearProperty(String key);
/**
* Gets a property from the configuration.
*
* @param key
* property to retrieve
* @return value as object. Will return user value if exists, if not then
* default value if exists, otherwise null
*/
String getProperty(String key);
/**
* Get the list of the keys contained in the configuration repository that
* match the specified prefix.
*
* @param prefix
* The prefix to test against.
* @return An Iterator of keys that match the prefix.
*/
Iterator getKeys(String prefix);
/**
* Get the list of the keys contained in the configuration repository.
*
* @return An Iterator.
*/
Iterator getKeys();
/**
* Get a list of properties associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated properties if key is found.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* String/Vector.
* @exception IllegalArgumentException
* if one of the tokens is malformed (does not contain an
* equals sign).
*/
Properties getProperties(String key);
/**
* Get a boolean associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated boolean.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Boolean.
*/
boolean getBoolean(String key);
/**
* Get a boolean associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated boolean.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Boolean.
*/
boolean getBoolean(String key, boolean defaultValue);
/**
* Get a boolean associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated boolean if key is found and has valid format,
* default value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Boolean.
*/
Boolean getBoolean(String key, Boolean defaultValue);
/**
* Get a byte associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated byte.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Byte.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
byte getByte(String key);
/**
* Get a byte associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated byte.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Byte.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
byte getByte(String key, byte defaultValue);
/**
* Get a byte associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated byte if key is found and has valid format, default
* value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Byte.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Byte getByte(String key, Byte defaultValue);
/**
* Get a double associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated double.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Double.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
double getDouble(String key);
/**
* Get a double associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated double.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Double.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
double getDouble(String key, double defaultValue);
/**
* Get a double associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated double if key is found and has valid format,
* default value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Double.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Double getDouble(String key, Double defaultValue);
/**
* Get a float associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated float.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Float.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
float getFloat(String key);
/**
* Get a float associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated float.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Float.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
float getFloat(String key, float defaultValue);
/**
* Get a float associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated float if key is found and has valid format,
* default value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Float.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Float getFloat(String key, Float defaultValue);
/**
* Get a int associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated int.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Integer.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
int getInt(String key);
/**
* Get a int associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated int.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Integer.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
int getInt(String key, int defaultValue);
/**
* Get a int associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated int if key is found and has valid format, default
* value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Integer.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Integer getInteger(String key, Integer defaultValue);
/**
* Get a long associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated long.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Long.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
long getLong(String key);
/**
* Get a long associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated long.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Long.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
long getLong(String key, long defaultValue);
/**
* Get a long associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated long if key is found and has valid format, default
* value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a Long.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Long getLong(String key, Long defaultValue);
/**
* Get a short associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated short.
* @exception NoSuchElementException
* is thrown if the key doesn't map to an existing object.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Short.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
short getShort(String key);
/**
* Get a short associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated short.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Short.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
short getShort(String key, short defaultValue);
/**
* Get a short associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated short if key is found and has valid format,
* default value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Short.
* @exception NumberFormatException
* is thrown if the value mapped by the key has not a valid
* number format.
*/
Short getShort(String key, Short defaultValue);
/**
* Get a string associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated string.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* String.
*/
String getString(String key);
/**
* Get a string associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated string if key is found and has valid format,
* default value otherwise.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* String.
*/
String getString(String key, String defaultValue);
/**
* Get an array of strings associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated string array if key is found.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* String/Vector of Strings.
*/
String[] getStringArray(String key);
/**
* Get a Vector of strings associated with the given configuration key.
*
* @param key
* The configuration key.
* @return The associated Vector.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Vector.
*/
Vector getVector(String key);
/**
* Get a Vector of strings associated with the given configuration key.
*
* @param key
* The configuration key.
* @param defaultValue
* The default value.
* @return The associated Vector.
* @exception ClassCastException
* is thrown if the key maps to an object that is not a
* Vector.
*/
Vector getVector(String key, Vector defaultValue);
}
| 8,721 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/db/ConfigurationParamsReader.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.db;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import xsul.MLogger;
public class ConfigurationParamsReader implements Configuration {
private final static MLogger log = MLogger.getLogger();
public final String FILE_SEPARATOR = "/";
public final String DELIMITER = ",";
private final int INITIAL_LIST_SIZE = 3;
private String basePath = null;
private ArrayList keysList = new ArrayList();
protected Configuration defaults = null;
protected Hashtable store = new Hashtable();
public ConfigurationParamsReader() {
}
public ConfigurationParamsReader(String file) {
try {
load(file);
} catch (IOException ioe) {
ioe.printStackTrace();
log.info(ioe.getMessage());
}
}
public ConfigurationParamsReader(Configuration defaults) {
this.defaults = defaults;
}
/**
* Load the properties from the given file
*
* @param file
* The properties file to load
* @throws IOException
*/
public void load(String file) throws IOException {
load(this.getClass().getClassLoader().getResourceAsStream(file));
}
/**
* Load the properties from the given input stream.
*
* @param input
* An InputStream on the properties file
* @throws IOException
*/
public void load(InputStream input) throws IOException {
load(input, null);
}
/**
* Load the properties from the given input stream and using the specified
* encoding.
*
* @param input
* An InputStream.
* @param enc
* An encoding.
* @exception IOException
*/
public synchronized void load(InputStream input, String enc)
throws IOException {
LineNumberReader reader = null;
if (enc != null) {
try {
reader = new LineNumberReader(new InputStreamReader(input, enc));
} catch (UnsupportedEncodingException e) {
// Get one with the default encoding...
}
}
if (reader == null) {
reader = new LineNumberReader(new InputStreamReader(input));
}
StringBuffer sb = new StringBuffer();
while (true) {
String line = reader.readLine();
if (line == null) {
break; // EOF
}
line = line.trim();
if (line.startsWith("#")) {
continue;
} else if (line.equals("")) {
continue;
} else if (line.endsWith("\\")) {
sb.append(line.substring(0, line.length() - 1));
continue;
} else {
line = sb.append(line).toString();
sb = new StringBuffer();
int equalIndex = line.indexOf('=');
/**
* fix commons.configuration bug
*
* @see BasePropertiesConfiguration#load we not only make sure
* there is an equal sign, but also there is something
* after the equal sign
*/
if (equalIndex > 0 && (equalIndex + 1) < line.length()) {
String key = line.substring(0, equalIndex).trim();
String value = line.substring(equalIndex + 1).trim();
addProperty(key, value);
}
}
}
}
/**
* @param The
* file name with which to get InputStream
* @return An InputStream
* @throws IOException
*/
public InputStream getPropertyStream(String resourceName)
throws IOException {
InputStream resource = null;
File file = null;
if (resourceName.startsWith(FILE_SEPARATOR)) {
// an absolute path
file = new File(resourceName);
log.info("configuration: load " + resourceName);
} else if (basePath == null || basePath.equals("")) {
file = new File(resourceName);
String canonName = file.getCanonicalPath();
file = new File(canonName);
log.info("configuration: load " + canonName);
} else {
StringBuffer fileName = new StringBuffer();
if (!basePath.endsWith(FILE_SEPARATOR)) {
basePath = basePath + FILE_SEPARATOR;
}
fileName.append(basePath).append(resourceName);
file = new File(fileName.toString());
String canonName = file.getCanonicalPath();
file = new File(canonName);
log.info("configuration: load " + canonName);
}
if (file == null || !file.exists()) {
throw new FileNotFoundException("File not exists " + resourceName);
} else if (!file.canRead()) {
throw new IOException("File " + resourceName
+ " exists but could not be read.");
} else {
resource = new FileInputStream(file);
}
return resource;
}
/**
* @see Configuration
*/
public void addProperty(String key, Object token) {
List tokenAdd = null;
if (token instanceof String) {
tokenAdd = processString((String) token);
} else if (token instanceof Collection) {
for (Iterator it = ((Collection) token).iterator(); it.hasNext();) {
addProperty(key, it.next());
}
return;
} else {
tokenAdd = new Vector(1);
tokenAdd.add(token);
}
Object o = store.get(key);
if (o instanceof Vector) {
for (Iterator it = tokenAdd.iterator(); it.hasNext();) {
((Vector) o).add(it.next());
}
} else {
Vector v = new Vector();
if (o != null) {
v.add(o);
}
for (Iterator it = tokenAdd.iterator(); it.hasNext();) {
v.add(it.next());
}
if (o == null && v.size() == 1) {
addPropertyDirect(key, v.get(0));
} else {
addPropertyDirect(key, v);
}
}
}
/**
* @param token
* A String token
* @return A List of Strings
*/
protected List processString(String token) {
List l = new ArrayList(INITIAL_LIST_SIZE);
if (token.indexOf(DELIMITER) > 0) {
StringTokenizer tokenizer = new StringTokenizer(token, DELIMITER);
while (tokenizer.hasMoreTokens()) {
String value = tokenizer.nextToken();
/**
* fix commons.configuration bug
*
* @see PropertiesConfiguration#processString() more trim() call
* allows both comma "," AND whitespace between values
*/
l.add(value.trim());
}
} else {
l.add(token);
}
return l;
}
/**
* @param key
* key to use for mapping
* @param obj
* object to store
*/
protected void addPropertyDirect(String key, Object obj) {
if (!store.containsKey(key)) {
keysList.add(key);
}
store.put(key, obj);
}
/**
* Map <code> true </code>, <code> on </code>, <code> yes </code> to true;
* <code> false </code>, <code> off </code>, <code> no </code> to false.
*
* @param value
* The value to test for boolean state.
* @return String of true, false or null
*/
public String testBoolean(String value) {
String val = value.toLowerCase();
if (val.equals("true") || val.equals("on") || val.equals("yes")) {
return "true";
} else if (val.equals("false") || val.equals("off") || val.equals("no")) {
return "false";
} else {
return null;
}
}
/**
*
* @see Configuration
*/
public Configuration subset(String prefix) {
Configuration pc = new ConfigurationParamsReader();
Iterator keys = this.getKeys();
boolean valid = false;
while (keys.hasNext()) {
Object key = keys.next();
if (key instanceof String && ((String) key).startsWith(prefix)) {
if (!valid) {
valid = true;
}
String newKey = null;
if (((String) key).length() == prefix.length()) {
newKey = prefix;
} else {
newKey = ((String) key).substring(prefix.length() + 1);
}
Object value = store.get(key);
((ConfigurationParamsReader) pc).addPropertyDirect(newKey,
value);
}
}
if (valid) {
return pc;
} else {
return null;
}
}
/**
* @see Configuration#isEmpty
*/
public boolean isEmpty() {
return store.isEmpty();
}
/**
* @see Configuration
*/
public boolean containsKey(String key) {
return store.containsKey(key);
}
/**
* @see Configuration
*/
public void setProperty(String key, Object value) {
clearProperty(key);
addProperty(key, value);
}
/**
* @see Configuration
*/
public void clearProperty(String key) {
if (containsKey(key)) {
for (int i = 0; i < keysList.size(); i++) {
if (((String) keysList.get(i)).equals(key)) {
keysList.remove(i);
break;
}
}
store.remove(key);
}
}
/**
* @see Configuration
*/
public Iterator getKeys() {
return keysList.iterator();
}
/**
* @see Configuration
*/
public Iterator getKeys(String prefix) {
Iterator keys = getKeys();
ArrayList matchingKeys = new ArrayList();
while (keys.hasNext()) {
Object key = keys.next();
if (key instanceof String && ((String) key).startsWith(prefix)) {
matchingKeys.add(key);
}
}
return matchingKeys.iterator();
}
/**
* Returns all the properties that have been read from the specified
* configuration file
*/
public Properties getProperties(Properties _defaults) {
Properties props = new Properties(_defaults);
Enumeration e = store.keys();
while (e.hasMoreElements()) {
String _key = (String) e.nextElement();
String _value = store.get(_key).toString();
props.setProperty(_key, _value);
}
return props;
}
/**
* @see Configuration
* @see #getProperties(String, Properties)
*/
public Properties getProperties(String key) {
return getProperties(key, null);
}
/**
* @see Configuration
*/
public Properties getProperties(String key, Properties defaults) {
String[] tokens = getStringArray(key);
/*
* Each token is of the form 'key=value'.
*/
Properties props = (defaults == null ? new Properties()
: new Properties(defaults));
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
int equalIndex = token.indexOf('=');
if (equalIndex > 0) {
String pkey = token.substring(0, equalIndex).trim();
String pvalue = token.substring(equalIndex + 1).trim();
props.put(pkey, pvalue);
} else if (tokens.length == 1 && token.equals("")) {
// Semantically equivalent to an empty Properties
// object.
break;
} else {
throw new IllegalArgumentException('\'' + token
+ "' does not contain an equals sign");
}
}
return props;
}
/**
* @see Configuration
*/
public String getProperty(String key) {
Object o = store.get(key);
if (o == null) {
if (defaults != null) {
o = defaults.getProperty(key);
}
}
return o.toString();
}
/**
* @see Configuration
*/
public boolean getBoolean(String key) {
Boolean b = getBoolean(key, (Boolean) null);
if (b != null) {
return b.booleanValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public boolean getBoolean(String key, boolean defaultValue) {
return getBoolean(key, new Boolean(defaultValue)).booleanValue();
}
/**
* @see Configuration
*/
public Boolean getBoolean(String key, Boolean defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
String s = testBoolean((String) value);
Boolean b = new Boolean(s);
return b;
} else if (value == null) {
if (defaults != null) {
return defaults.getBoolean(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Boolean object");
}
}
/**
* @see Configuration
*/
public byte getByte(String key) {
Byte b = getByte(key, null);
if (b != null) {
return b.byteValue();
} else {
throw new NoSuchElementException('\'' + key
+ " doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public byte getByte(String key, byte defaultValue) {
return getByte(key, new Byte(defaultValue)).byteValue();
}
/**
* @see Configuration
*/
public Byte getByte(String key, Byte defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Byte) {
return (Byte) value;
} else if (value instanceof String) {
Byte b = new Byte((String) value);
return b;
} else if (value == null) {
if (defaults != null) {
return defaults.getByte(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Byte object");
}
}
/**
* @see Configuration
*/
public double getDouble(String key) {
Double d = getDouble(key, null);
if (d != null) {
return d.doubleValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public double getDouble(String key, double defaultValue) {
return getDouble(key, new Double(defaultValue)).doubleValue();
}
/**
* @see Configuration
*/
public Double getDouble(String key, Double defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Double) {
return (Double) value;
} else if (value instanceof String) {
Double d = new Double((String) value);
return d;
} else if (value == null) {
if (defaults != null) {
return defaults.getDouble(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Double object");
}
}
/**
* @see Configuration
*/
public float getFloat(String key) {
Float f = getFloat(key, null);
if (f != null) {
return f.floatValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public float getFloat(String key, float defaultValue) {
return getFloat(key, new Float(defaultValue)).floatValue();
}
/**
* @see Configuration
*/
public Float getFloat(String key, Float defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Float) {
return (Float) value;
} else if (value instanceof String) {
Float f = new Float((String) value);
return f;
} else if (value == null) {
if (defaults != null) {
return defaults.getFloat(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Float object");
}
}
/**
* @see Configuration
*/
public int getInt(String key) {
Integer i = getInteger(key, null);
if (i != null) {
return i.intValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public int getInt(String key, int defaultValue) {
Integer i = getInteger(key, null);
if (i == null) {
return defaultValue;
}
return i.intValue();
}
/**
* @see Configuration
*/
public Integer getInteger(String key, Integer defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof String) {
Integer i = new Integer((String) value);
return i;
} else if (value == null) {
if (defaults != null) {
return defaults.getInteger(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Integer object");
}
}
/**
* @see Configuration
*/
public long getLong(String key) {
Long l = getLong(key, null);
if (l != null) {
return l.longValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public long getLong(String key, long defaultValue) {
return getLong(key, new Long(defaultValue)).longValue();
}
/**
* @see Configuration
*/
public Long getLong(String key, Long defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Long) {
return (Long) value;
} else if (value instanceof String) {
Long l = new Long((String) value);
return l;
} else if (value == null) {
if (defaults != null) {
return defaults.getLong(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Long object");
}
}
/**
* @see Configuration
*/
public short getShort(String key) {
Short s = getShort(key, null);
if (s != null) {
return s.shortValue();
} else {
throw new NoSuchElementException('\'' + key
+ "' doesn't map to an existing object");
}
}
/**
* @see Configuration
*/
public short getShort(String key, short defaultValue) {
return getShort(key, new Short(defaultValue)).shortValue();
}
/**
* @see Configuration
*/
public Short getShort(String key, Short defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof Short) {
return (Short) value;
} else if (value instanceof String) {
Short s = new Short((String) value);
return s;
} else if (value == null) {
if (defaults != null) {
return defaults.getShort(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Short object");
}
}
/**
* @see Configuration
*/
public String getString(String key) {
return getString(key, null);
}
/**
* @see Configuration
*/
public String getString(String key, String defaultValue) {
Object value = resolveVectorStore(key);
if (value instanceof String) {
return (String) value;
} else if (value == null) {
if (defaults != null) {
return defaults.getString(key, defaultValue);
} else {
return defaultValue;
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a String object");
}
}
/**
* @see Configuration
*/
public String[] getStringArray(String key) {
Object value = store.get(key);
String[] tokens;
if (value instanceof String) {
tokens = new String[1];
tokens[0] = (String) value;
} else if (value instanceof Vector) {
tokens = new String[((Vector) value).size()];
for (int i = 0; i < tokens.length; i++) {
tokens[i] = (String) ((Vector) value).get(i);
}
} else if (value == null) {
if (defaults != null) {
tokens = defaults.getStringArray(key);
} else {
tokens = new String[0];
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a String/Vector object");
}
return tokens;
}
/**
* @see Configuration
*/
public Vector getVector(String key) {
return getVector(key, null);
}
/**
* @see Configuration
*/
public Vector getVector(String key, Vector defaultValue) {
Object value = store.get(key);
Vector v = null;
if (value instanceof String) {
v = new Vector(1);
v.addElement((String) value);
} else if (value == null) {
if (defaults != null) {
v = defaults.getVector(key, defaultValue);
} else {
v = ((defaultValue == null) ? new Vector() : defaultValue);
}
} else {
throw new ClassCastException('\'' + key
+ "' doesn't map to a Vector object: " + value + ", a "
+ value.getClass().getName());
}
return v;
}
/**
*
*/
public String getBasePath() {
return this.basePath;
}
/**
*
*/
public void setBasePath(String path) {
this.basePath = path;
}
/**
* Returns an object from the store described by the key. If the value is a
* Vector object, replace it with the first object in the container
*
* @param key
* The property key.
*
* @return value Value, transparently resolving a possible Vector
* dependency.
*/
private Object resolveVectorStore(String key) {
Object value = store.get(key);
if (value != null && value instanceof Vector) {
value = ((Vector) value).get(0);
}
return value;
}
}
| 8,722 |
0 | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring | Create_ds/airavata-sandbox/workflow-monitoring-util/src/main/java/org/apache/airavata/tools/workflow/monitoring/db/DBConstants.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.tools.workflow.monitoring.db;
public abstract class DBConstants {
/****************************************************************
* Summary Table Information *
****************************************************************/
public static final String T_SUMMARY_NAME = "summary";
public static final String T_SUMMARY_WORKFLOW_ID = "workflowid";
public static final String T_SUMMARY_TEMPLATE_ID = "templateid";
public static final String T_SUMMARY_STATUS = "status";
public static final String T_SUMMARY_END_TIME = "endTime";
public static final String T_SUMMARY_START_TIME = "startTime";
public static final String T_SUMMARY_USERNAME = "username";
/****************************************************************
* Faults Table Information *
****************************************************************/
public static final String T_FAULTS_NAME = "faults";
public static final String T_FAULTS_ID = "id";
public static final String T_FAULTS_XML = "xml";
public static final String T_FAULTS_WORKFLOW_ID = "workflowid";
}
| 8,723 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/HelixUtil.java | package edu.iu.helix.airavata;
import edu.iu.helix.airavata.tasks.HelixTaskA;
import edu.iu.helix.airavata.tasks.HelixTaskB;
import edu.iu.helix.airavata.tasks.HelixTaskC;
import edu.iu.helix.airavata.tasks.HelixTaskD;
import edu.iu.helix.airavata.tasks.ssh.SSHKeyAuthentication;
import edu.iu.helix.airavata.tasks.ssh.SSHServerInfo;
import edu.iu.helix.airavata.tasks.ssh.SSHTask;
import edu.iu.helix.airavata.tasks.ssh.SSHTaskContext;
import org.apache.commons.io.IOUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.helix.task.*;
import org.jboss.netty.util.internal.ThreadLocalRandom;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixUtil {
public static final String TASK_STATE_DEF = "Task";
public static final String ZK_ADDRESS = "localhost:2199";
public static final String CLUSTER_NAME = "HelixDemoCluster";
public static final String SSH_WORKFLOW = "SSH_Workflow";
public static final String CREATE_DIR_TASK = "Task_CreateDir";
public static final String COPY_PBS_TASK = "Task_CopyPBS";
public static final String COPY_PY_TASK = "Task_CopyPY";
public static final String QSUB_TASK = "Task_QSUB";
public static final String USERNAME = "username";
public static final String PRIVATE_KEY = "private_key";
public static final String PUBLIC_KEY = "public_key";
public static final String HOSTNAME = "hostname";
public static final String PORT = "port";
public static final String COMMAND = "command";
public static final String SRC_PATH = "src_path";
public static final String DEST_PATH = "dest_path";
public enum DAGType {
TYPE_A,
TYPE_B,
TYPE_C,
SSH
}
private static Workflow.Builder getWorkflowBuilder(DAGType dagType) throws Exception {
Workflow.Builder workflow = null;
if (dagType.equals(DAGType.SSH)) {
if (!setWorkflowData()) {
throw new Exception("Failed to create zk data for SSH workflow");
}
// create dir task - 1 task for job
List<TaskConfig> createDirTask = new ArrayList<TaskConfig>();
createDirTask.add(new TaskConfig.Builder().setTaskId(CREATE_DIR_TASK).setCommand(SSHTask.TASK_COMMAND).build());
// copy files task - 2 tasks for job
List<TaskConfig> copyFilesTask = new ArrayList<TaskConfig>();
copyFilesTask.add(new TaskConfig.Builder().setTaskId(COPY_PBS_TASK).setCommand(SSHTask.TASK_COMMAND).build());
copyFilesTask.add(new TaskConfig.Builder().setTaskId(COPY_PY_TASK).setCommand(SSHTask.TASK_COMMAND).build());
// qsub task - 1 task for job
List<TaskConfig> qsubTask = new ArrayList<TaskConfig>();
qsubTask.add(new TaskConfig.Builder().setTaskId(QSUB_TASK).setCommand(SSHTask.TASK_COMMAND).build());
// create-dir job config
JobConfig.Builder createDirJob = new JobConfig.Builder().addTaskConfigs(createDirTask).setMaxAttemptsPerTask(3);
// copy-files job config
JobConfig.Builder copyFilesJob = new JobConfig.Builder().addTaskConfigs(copyFilesTask).setMaxAttemptsPerTask(3);
// qsub job config
JobConfig.Builder qsubJob = new JobConfig.Builder().addTaskConfigs(qsubTask).setMaxAttemptsPerTask(1);
// create workflow
workflow = new Workflow.Builder(SSH_WORKFLOW).setExpiry(0);
workflow.addJob("createDirJob", createDirJob);
workflow.addJob("copyFilesJob", copyFilesJob);
workflow.addJob("qsubJob", qsubJob);
} else {
// create task configs
List<TaskConfig> taskConfig1 = new ArrayList<TaskConfig>();
List<TaskConfig> taskConfig2 = new ArrayList<TaskConfig>();
List<TaskConfig> taskConfig3 = new ArrayList<TaskConfig>();
List<TaskConfig> taskConfig4 = new ArrayList<TaskConfig>();
taskConfig1.add(new TaskConfig.Builder().setTaskId("helix_task_a").setCommand(HelixTaskA.TASK_COMMAND).build());
taskConfig2.add(new TaskConfig.Builder().setTaskId("helix_task_b").setCommand(HelixTaskB.TASK_COMMAND).build());
taskConfig3.add(new TaskConfig.Builder().setTaskId("helix_task_c").setCommand(HelixTaskC.TASK_COMMAND).build());
taskConfig4.add(new TaskConfig.Builder().setTaskId("helix_task_d").setCommand(HelixTaskD.TASK_COMMAND).build());
// create job configs
JobConfig.Builder jobConfig1 = new JobConfig.Builder().addTaskConfigs(taskConfig1).setMaxAttemptsPerTask(3);
JobConfig.Builder jobConfig2 = new JobConfig.Builder().addTaskConfigs(taskConfig2).setMaxAttemptsPerTask(3);
JobConfig.Builder jobConfig3 = new JobConfig.Builder().addTaskConfigs(taskConfig3).setMaxAttemptsPerTask(3);
JobConfig.Builder jobConfig4 = new JobConfig.Builder().addTaskConfigs(taskConfig4).setMaxAttemptsPerTask(3);
// create workflow
workflow = new Workflow.Builder("helix_workflow").setExpiry(0);
workflow.addJob("helix_job_a", jobConfig1);
workflow.addJob("helix_job_b", jobConfig2);
workflow.addJob("helix_job_c", jobConfig3);
workflow.addJob("helix_job_d", jobConfig4);
}
switch (dagType) {
case TYPE_A:
workflow.addParentChildDependency("helix_job_a", "helix_job_b");
workflow.addParentChildDependency("helix_job_b", "helix_job_c");
workflow.addParentChildDependency("helix_job_c", "helix_job_d");
break;
case TYPE_B:
workflow.addParentChildDependency("helix_job_a", "helix_job_c");
workflow.addParentChildDependency("helix_job_c", "helix_job_d");
workflow.addParentChildDependency("helix_job_d", "helix_job_b");
break;
case TYPE_C:
workflow.addParentChildDependency("helix_job_a", "helix_job_d");
workflow.addParentChildDependency("helix_job_d", "helix_job_b");
workflow.addParentChildDependency("helix_job_b", "helix_job_c");
break;
case SSH:
workflow.addParentChildDependency("createDirJob", "copyFilesJob");
workflow.addParentChildDependency("copyFilesJob", "qsubJob");
break;
}
return workflow;
}
public static Workflow getWorkflow(DAGType dagType) throws Exception {
Workflow.Builder workflowBuilder = getWorkflowBuilder(dagType);
return workflowBuilder.build();
}
private static String generateWorkflowName() {
return "workflow_" + ThreadLocalRandom.current().nextInt(9999);
}
private static boolean setWorkflowData() {
try {
CuratorFramework curatorClient = ZkUtils.getCuratorClient();
SSHKeyAuthentication br2SshAuthentication = new SSHKeyAuthentication(
"snakanda",
IOUtils.toByteArray(HelixUtil.class.getClassLoader().getResourceAsStream("ssh/id_rsa")),
IOUtils.toByteArray(HelixUtil.class.getClassLoader().getResourceAsStream("ssh/id_rsa.pub")),
"dummy",
HelixUtil.class.getClassLoader().getResource("ssh/known_hosts").getPath(),
false
);
SSHServerInfo br2 = new SSHServerInfo("snakanda", "bigred2.uits.iu.edu", br2SshAuthentication,22);
SSHTaskContext createDirTC = new SSHTaskContext(SSHTaskContext.TASK_TYPE.EXECUTE_COMMAND,
br2SshAuthentication, null, br2, "mkdir -p airavata");
SSHTaskContext qsubTC = new SSHTaskContext(SSHTaskContext.TASK_TYPE.EXECUTE_COMMAND,
br2SshAuthentication, null, br2, "qsub ~/airavata/job_tf.pbs");
SSHTaskContext copyPbsTC = new SSHTaskContext(SSHTaskContext.TASK_TYPE.FILE_COPY,
br2SshAuthentication, null, br2,
HelixUtil.class.getClassLoader().getResource("job_tf.pbs").getPath(), "~/airavata/");
SSHTaskContext copyPyTC = new SSHTaskContext(SSHTaskContext.TASK_TYPE.FILE_COPY,
br2SshAuthentication, null, br2,
HelixUtil.class.getClassLoader().getResource("job_tf.pbs").getPath(), "~/airavata/");
ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, CREATE_DIR_TASK, getBytes(createDirTC));
ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, COPY_PBS_TASK, getBytes(copyPbsTC));
ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, COPY_PY_TASK, getBytes(copyPyTC));
ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, QSUB_TASK, getBytes(qsubTC));
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
private static byte[] getBytes(Object object) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(object);
out.flush();
return bos.toByteArray();
}
public static Object getObject(byte[] objectBytes) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(objectBytes);
ObjectInput in = new ObjectInputStream(bis);
return in.readObject();
}
// public static void main(String[] args) throws Exception {
//
// CuratorFramework curatorClient = ZkUtils.getCuratorClient();
//
// // set common data
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, USERNAME, "snakanda");
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, HOSTNAME, "bigred2.uits.iu.edu");
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, PORT, "22");
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, PUBLIC_KEY,
// IOUtils.toByteArray(HelixUtil.class.getClassLoader().getResourceAsStream("ssh/id_rsa.pub")));
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW, PRIVATE_KEY,
// IOUtils.toByteArray(HelixUtil.class.getClassLoader().getResourceAsStream("ssh/id_rsa")));
//
//
// // set data for mkdir
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + CREATE_DIR_TASK, COMMAND, "mkdir -p airavata");
//
// // set data for copy files
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + COPY_PBS_TASK, SRC_PATH,
// HelixUtil.class.getClassLoader().getResource("job_tf.pbs").getPath());
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + COPY_PBS_TASK, DEST_PATH, "~/airavata/");
//
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + COPY_PY_TASK, SRC_PATH,
// HelixUtil.class.getClassLoader().getResource("code_tf.py").getPath());
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + COPY_PY_TASK, DEST_PATH, "~/airavata/");
//
// // set data for qsub
// ZkUtils.createZkNode(curatorClient, SSH_WORKFLOW + "/" + CREATE_DIR_TASK, COMMAND, "qsub ~/airavata/job_tf.pbs");
// }
}
| 8,724 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/ControllerNode.java | package edu.iu.helix.airavata;
import org.apache.helix.HelixManager;
import org.apache.helix.controller.HelixControllerMain;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.concurrent.CountDownLatch;
/**
* Created by goshenoy on 6/21/17.
*/
public class ControllerNode implements Runnable {
private static final Logger logger = LogManager.getLogger(ControllerNode.class);
private String clusterName;
private String controllerName;
private String zkAddress;
private HelixManager zkHelixManager;
private CountDownLatch startLatch = new CountDownLatch(1);
private CountDownLatch stopLatch = new CountDownLatch(1);
public ControllerNode(String zkAddress, String clusterName, String controllerName) {
this.clusterName = clusterName;
this.controllerName = controllerName;
this.zkAddress = zkAddress;
}
@Override
public void run() {
try {
zkHelixManager = HelixControllerMain.startHelixController(zkAddress, clusterName,
controllerName, HelixControllerMain.STANDALONE);
startLatch.countDown();
stopLatch.await();
} catch (Exception ex) {
logger.error("Error in run() for Controller: " + controllerName + ", reason: " + ex, ex);
} finally {
disconnect();
}
}
public void start() {
new Thread(this).start();
try {
startLatch.await();
logger.info("Controller: " + controllerName + ", has connected to cluster: " + clusterName);
} catch (InterruptedException ex) {
logger.error("Controller: " + controllerName + ", is interrupted! reason: " + ex, ex);
}
}
public void stop() {
stopLatch.countDown();
}
private void disconnect() {
if (zkHelixManager != null) {
logger.info("Controller: " + controllerName + ", has disconnected from cluster: " + clusterName);
zkHelixManager.disconnect();
}
}
}
| 8,725 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/ParticipantNode.java | package edu.iu.helix.airavata;
import edu.iu.helix.airavata.tasks.HelixTaskA;
import edu.iu.helix.airavata.tasks.HelixTaskB;
import edu.iu.helix.airavata.tasks.HelixTaskC;
import edu.iu.helix.airavata.tasks.HelixTaskD;
import edu.iu.helix.airavata.tasks.ssh.SSHTask;
import org.apache.helix.InstanceType;
import org.apache.helix.examples.OnlineOfflineStateModelFactory;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskFactory;
import org.apache.helix.task.TaskStateModelFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by goshenoy on 6/21/17.
*/
public class ParticipantNode implements Runnable {
private static final Logger logger = LogManager.getLogger(ParticipantNode.class);
private String zkAddress;
private String clusterName;
private String participantName;
private ZKHelixManager zkHelixManager;
public ParticipantNode(String zkAddress, String clusterName, String participantName) {
logger.debug("Initializing Participant Node");
this.zkAddress = zkAddress;
this.clusterName = clusterName;
this.participantName = participantName;
}
@Override
public void run() {
ZkClient zkClient = null;
try {
zkClient = new ZkClient(zkAddress, ZkClient.DEFAULT_SESSION_TIMEOUT,
ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
ZKHelixAdmin zkHelixAdmin = new ZKHelixAdmin(zkClient);
List<String> nodesInCluster = zkHelixAdmin.getInstancesInCluster(clusterName);
if (!nodesInCluster.contains(participantName)) {
InstanceConfig instanceConfig = new InstanceConfig(participantName);
instanceConfig.setHostName("localhost");
instanceConfig.setInstanceEnabled(true);
zkHelixAdmin.addInstance(clusterName, instanceConfig);
logger.debug("Instance: " + participantName + ", has been added to cluster: " + clusterName);
}
Runtime.getRuntime().addShutdownHook(
new Thread() {
@Override
public void run() {
logger.debug("Participant: " + participantName + ", shutdown hook called.");
disconnect();
}
}
);
// connect the participant manager
connect();
} catch (Exception ex) {
logger.error("Error in run() for Participant: " + participantName + ", reason: " + ex, ex);
} finally {
if (zkClient != null) {
zkClient.close();
}
}
}
private void connect() {
try {
zkHelixManager = new ZKHelixManager(clusterName, participantName, InstanceType.PARTICIPANT, zkAddress);
// register online-offline model
StateMachineEngine machineEngine = zkHelixManager.getStateMachineEngine();
OnlineOfflineStateModelFactory factory = new OnlineOfflineStateModelFactory(participantName);
machineEngine.registerStateModelFactory(BuiltInStateModelDefinitions.OnlineOffline.name(), factory);
// register task model
Map<String, TaskFactory> taskRegistry = new HashMap<String, TaskFactory>();
taskRegistry.put(SSHTask.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new SSHTask(context);
}
});
taskRegistry.put(HelixTaskA.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskA(context);
}
});
taskRegistry.put(HelixTaskB.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskB(context);
}
});
taskRegistry.put(HelixTaskC.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskC(context);
}
});
taskRegistry.put(HelixTaskD.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskD(context);
}
});
machineEngine.registerStateModelFactory(HelixUtil.TASK_STATE_DEF,
new TaskStateModelFactory(zkHelixManager, taskRegistry));
logger.debug("Participant: " + participantName + ", registered state model factories.");
zkHelixManager.connect();
logger.info("Participant: " + participantName + ", has connected to cluster: " + clusterName);
Thread.currentThread().join();
} catch (InterruptedException ex) {
logger.error("Participant: " + participantName + ", is interrupted! reason: " + ex, ex);
}
catch (Exception ex) {
logger.error("Error in connect() for Participant: " + participantName + ", reason: " + ex, ex);
} finally {
disconnect();
}
}
private void disconnect() {
if (zkHelixManager != null) {
logger.info("Participant: " + participantName + ", has disconnected from cluster: " + clusterName);
zkHelixManager.disconnect();
}
}
}
| 8,726 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/HelixClusterManager.java | package edu.iu.helix.airavata;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.task.TaskDriver;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.Workflow;
import org.apache.helix.task.WorkflowContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.print.attribute.standard.JobState;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixClusterManager {
private static final Logger logger = LogManager.getLogger(HelixClusterManager.class);
private int numWorkers;
private int numPartitions;
private String clusterName;
private String zkAddress;
private HelixManager helixManager;
private TaskDriver taskDriver;
private ControllerNode controllerNode;
private HelixCluster helixCluster;
private static final String CONTROLLER_NAME = "HelixDemoController";
private static final String PARTICIPANT_NAME = "HelixDemoParticipant_";
public HelixClusterManager(String clusterName, String zkAddress, int numWorkers, int numPartitions) {
this.numWorkers = numWorkers;
this.numPartitions = numPartitions;
this.clusterName = clusterName;
this.zkAddress = zkAddress;
}
public void startHelixCluster() {
// create the cluster
helixCluster = new HelixCluster(zkAddress, clusterName, numPartitions);
helixCluster.setup();
System.out.println("Successfully created helix cluster: " + clusterName + ", with [ " + numPartitions + " ] partitions.");
// start the participants
Executor executor = Executors.newFixedThreadPool(numWorkers);
for (int i = 0; i < numWorkers; i++) {
String participantName = PARTICIPANT_NAME + i;
ParticipantNode participant = new ParticipantNode(zkAddress, clusterName, participantName);
executor.execute(participant);
System.out.println("Successfully started participant node: " + participantName + ", on cluster: " + clusterName);
}
// add resources to cluster
helixCluster.addResourcesToCluster();
System.out.println("Successfully added resources to cluster: " + clusterName);
// start the controller
controllerNode = new ControllerNode(zkAddress, clusterName, CONTROLLER_NAME);
controllerNode.start();
System.out.println("Successfully started the controller node: " + CONTROLLER_NAME + ", on cluster: " + clusterName);
// start the cluster manager
connect();
System.out.println("Successfully started the helix cluster manager (admin), on cluster: " + clusterName);
}
private void connect() {
this.helixManager = HelixManagerFactory.getZKHelixManager(clusterName, "Admin",
InstanceType.SPECTATOR, zkAddress);
try {
this.helixManager.connect();
} catch (Exception ex) {
logger.error("Error in connect() for Admin, reason: " + ex, ex);
}
this.taskDriver = new TaskDriver(helixManager);
logger.debug("HelixManager Admin connected.");
Runtime.getRuntime().addShutdownHook(
new Thread() {
@Override
public void run() {
disconnect();
controllerNode.stop();
helixCluster.disconnect();
}
}
);
}
private void disconnect() {
if (helixManager != null) {
System.out.println("HelixManager Admin disconnecting from cluster: " + clusterName);
helixManager.disconnect();
}
}
public boolean submitDag(HelixUtil.DAGType dagType) {
try {
Workflow workflow = HelixUtil.getWorkflow(dagType);
taskDriver.start(workflow);
System.out.println("Started workflow for DagType: " + dagType + ", in cluster: " + clusterName);
taskDriver.pollForWorkflowState(workflow.getName(), TaskState.COMPLETED, TaskState.FAILED);
// while (true) {
// Thread.sleep(100);
// WorkflowContext context = taskDriver.getWorkflowContext(workflow.getName());
// System.out.println(context);
// if (context != null && context.getWorkflowState() != null) {
// if (context.getWorkflowState().equals(TaskState.COMPLETED)) {
// System.out.println("Workflow completed!");
// break;
// } else if (context.getWorkflowState().equals(TaskState.FAILED)) {
// System.err.println("Workflow failed!");
// break;
// }
// }
// }
return true;
} catch (Exception ex) {
logger.error("Error submitting Dag for type: " + dagType + ", reason: " + ex, ex);
return false;
}
}
public static void main(String[] args) {
String clusterName = HelixUtil.CLUSTER_NAME;
String zkAddress = HelixUtil.ZK_ADDRESS;
int numWorkers = 3;
int numPartitions = 1;
try {
System.out.println("Starting helix manager for cluster [ " + clusterName + " ], " +
"on ZK server [ " + zkAddress + " ], " +
"with [ " + numWorkers + " ] workers, " +
"having [ " + numPartitions + "] partitions.");
HelixClusterManager manager = new HelixClusterManager(clusterName, zkAddress, numWorkers, numPartitions);
manager.startHelixCluster();
System.out.println("Submitting Workflow for DagType: " + HelixUtil.DAGType.SSH);
if (manager.submitDag(HelixUtil.DAGType.SSH)) {
System.out.println("Successfully completed workflow for Dag: " + HelixUtil.DAGType.SSH);
} else {
throw new Exception("Failed to run workflow for Dag: " + HelixUtil.DAGType.SSH);
}
} catch (Exception ex) {
logger.error("Something went wrong while running helix cluster manager. Reason: " + ex, ex);
}
System.out.println("*** Exiting System ***");
// System.exit(0);
}
}
| 8,727 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/HelixCluster.java | package edu.iu.helix.airavata;
import edu.iu.helix.airavata.tasks.HelixTaskA;
import edu.iu.helix.airavata.tasks.HelixTaskB;
import edu.iu.helix.airavata.tasks.HelixTaskC;
import edu.iu.helix.airavata.tasks.HelixTaskD;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.OnlineOfflineSMD;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixCluster {
private static final Logger logger = LogManager.getLogger(HelixCluster.class);
private String zkAddress;
private String clusterName;
private int numPartitions;
private ZkClient zkClient;
private ZKHelixAdmin zkHelixAdmin;
public HelixCluster(String zkAddress, String clusterName, int numPartitions) {
this.zkAddress = zkAddress;
this.clusterName = clusterName;
this.numPartitions = numPartitions;
zkClient = new ZkClient(this.zkAddress, ZkClient.DEFAULT_SESSION_TIMEOUT,
ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
zkHelixAdmin = new ZKHelixAdmin(zkClient);
}
public void setup() {
zkHelixAdmin.addCluster(clusterName, true);
zkHelixAdmin.addStateModelDef(clusterName, OnlineOfflineSMD.name, OnlineOfflineSMD.build());
logger.info("Cluster: " + clusterName + ", has been added.");
}
public void addResourcesToCluster() {
String stateModel = BuiltInStateModelDefinitions.OnlineOffline.name();
zkHelixAdmin.addResource(clusterName, HelixTaskA.TASK_COMMAND, numPartitions, stateModel);
zkHelixAdmin.addResource(clusterName, HelixTaskB.TASK_COMMAND, numPartitions, stateModel);
zkHelixAdmin.addResource(clusterName, HelixTaskC.TASK_COMMAND, numPartitions, stateModel);
zkHelixAdmin.addResource(clusterName, HelixTaskD.TASK_COMMAND, numPartitions, stateModel);
logger.debug("Resources (A,B,C,D) with [ " + numPartitions + " ] partitions have been added to Cluster: " + clusterName);
zkHelixAdmin.rebalance(clusterName, HelixTaskA.TASK_COMMAND, 1);
zkHelixAdmin.rebalance(clusterName, HelixTaskB.TASK_COMMAND, 1);
zkHelixAdmin.rebalance(clusterName, HelixTaskC.TASK_COMMAND, 1);
zkHelixAdmin.rebalance(clusterName, HelixTaskD.TASK_COMMAND, 1);
logger.debug("Resources (A,B,C,D) have been rebalanced");
}
public void disconnect() {
if (zkClient != null) {
zkClient.close();
}
}
}
| 8,728 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/ZkUtils.java | package edu.iu.helix.airavata;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by goshenoy on 6/28/17.
*/
public class ZkUtils {
private static final Logger logger = LoggerFactory.getLogger(ZkUtils.class);
private static CuratorFramework curatorClient;
/**
* Get curatorFramework instance
* @return
* @throws Exception
*/
public static CuratorFramework getCuratorClient() throws Exception {
if (curatorClient == null) {
synchronized (ZkUtils.class) {
if (curatorClient == null) {
String connectionSting = HelixUtil.ZK_ADDRESS;
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy);
curatorClient.start();
}
}
}
return curatorClient;
}
public static String getZkPath(String parentNode, String childNode) throws Exception {
return ZKPaths.makePath(parentNode, childNode);
}
public static void createZkNode(CuratorFramework curatorClient, String parentNode, String childNode, String data) throws Exception {
String zkPath = getZkPath(parentNode, childNode);
logger.debug("Creating Zk node for: " + zkPath);
ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), zkPath);
setZkData(curatorClient, zkPath, data.getBytes());
}
public static void createZkNode(CuratorFramework curatorClient, String parentNode, String childNode, byte[] data) throws Exception {
String zkPath = getZkPath(parentNode, childNode);
logger.debug("Creating Zk node for: " + zkPath);
ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), zkPath);
setZkData(curatorClient, zkPath, data);
}
public static void setZkData(CuratorFramework curatorClient, String zkPath, byte[] data) throws Exception {
curatorClient.setData().withVersion(-1).forPath(zkPath, data);
}
public static Object getZkData(CuratorFramework curatorClient, String parentNode, String childNode) throws Exception {
String zkPath = getZkPath(parentNode, childNode);
return getZkData(curatorClient, zkPath);
}
public static Object getZkData(CuratorFramework curatorClient, String zkPath) throws Exception {
byte[] data = curatorClient.getData().forPath(zkPath);
return HelixUtil.getObject(data);
}
}
| 8,729 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/HelixTaskA.java | package edu.iu.helix.airavata.tasks;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixTaskA extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskA.class);
public static final String TASK_COMMAND = "HelixTask_A";
private static int count = 0;
public HelixTaskA(TaskCallbackContext callbackContext) {
System.out.println("HelixTaskA | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
System.out.println("HelixTaskA | Inside run(), sleeping for 2 secs");
addToUserStore();
// sleep(2000);
System.out.println("HelixTaskA | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "HelixTask completed!");
}
@Override
public void cancel() {
System.out.println("HelixTaskA | Inside cancel()");
}
private void addToUserStore() {
System.out.println("HelixTaskA | Inside addToUserStore()");
putUserContent("fullName", "Gourav Shenoy", Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,730 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/HelixTaskB.java | package edu.iu.helix.airavata.tasks;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixTaskB extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskB.class);
public static final String TASK_COMMAND = "HelixTask_B";
private static int retryCount = 0;
public HelixTaskB(TaskCallbackContext callbackContext) {
System.out.println("HelixTaskB | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
if (retryCount < 2) {
retryCount++;
System.out.println("HelixTaskB | Returning status FAILED, Helix will retry this task. Retry count: " + retryCount);
return new TaskResult(TaskResult.Status.FAILED, "HelixTaskB should be retried!");
}
System.out.println("HelixTaskB | After 2 retries, Inside run(), sleeping for 2 secs");
// sleep(2000);
System.out.println("HelixTaskB | Retrieved from UserStore : " + getFromUserStore("fullName"));
// System.out.println("HelixTaskB | Returning status : FATAL_FAILED.");
// return new TaskResult(TaskResult.Status.FATAL_FAILED, "edu.iu.helix.play.HelixTaskB completed!");
System.out.println("HelixTaskB | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "HelixTaskB completed!");
}
@Override
public void cancel() {
System.out.println("HelixTaskB | Inside cancel()");
}
private String getFromUserStore(String key) {
System.out.println("HelixTaskB | Inside getFromUserStore()");
return getUserContent(key, Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,731 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/HelixTaskC.java | package edu.iu.helix.airavata.tasks;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixTaskC extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskC.class);
public static final String TASK_COMMAND = "HelixTask_C";
public HelixTaskC(TaskCallbackContext callbackContext) {
System.out.println("HelixTaskC | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
System.out.println("HelixTaskC | Inside run(), sleeping for 2 secs");
// sleep(2000);
System.out.println("HelixTaskC | Retrieved from UserStore : " + getFromUserStore("fullName"));
System.out.println("HelixTaskC | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "HelixTaskC completed!");
}
@Override
public void cancel() {
System.out.println("HelixTaskC | Inside cancel()");
}
private String getFromUserStore(String key) {
System.out.println("HelixTaskC | Inside getFromUserStore()");
return getUserContent(key, Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,732 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/HelixTaskD.java | package edu.iu.helix.airavata.tasks;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/21/17.
*/
public class HelixTaskD extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskD.class);
public static final String TASK_COMMAND = "HelixTask_D";
public HelixTaskD(TaskCallbackContext callbackContext) {
System.out.println("HelixTaskD | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
System.out.println("HelixTaskD | Inside run(), sleeping for 2 secs");
// sleep(2000);
System.out.println("HelixTaskD | Retrieved from UserStore : " + getFromUserStore("fullName"));
System.out.println("HelixTaskD | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "HelixTaskD completed!");
}
@Override
public void cancel() {
System.out.println("HelixTaskD | Inside cancel()");
}
private String getFromUserStore(String key) {
System.out.println("HelixTaskD | Inside getFromUserStore()");
return getUserContent(key, Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,733 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHApiException.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
/**
* An exception class to wrap SSH command execution related errors.
*/
public class SSHApiException extends Exception {
public SSHApiException(String message) {
super(message);
}
public SSHApiException(String message, Exception e) {
super(message, e);
}
}
| 8,734 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHUserInfo.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import com.jcraft.jsch.UserInfo;
import java.io.Serializable;
public class SSHUserInfo implements UserInfo, Serializable {
private String userName;
private String password;
private String passphrase;
public SSHUserInfo(String userName, String password, String passphrase) {
this.userName = userName;
this.password = password;
this.passphrase = passphrase;
}
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassword(String s) {
return false;
}
@Override
public boolean promptPassphrase(String s) {
return false;
}
@Override
public boolean promptYesNo(String s) {
return false;
}
@Override
public void showMessage(String s) {
}
} | 8,735 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/ServerInfo.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import java.io.Serializable;
public class ServerInfo implements Serializable {
public static enum ComProtocol {SSH, LOCAL}
protected String host;
protected String userName;
protected int port;
protected ComProtocol comProtocol;
public ServerInfo(){}
public ServerInfo(String userName, String host, ComProtocol comProtocol, int port) {
this.userName = userName;
this.host = host;
this.comProtocol = comProtocol;
this.port = port;
}
public String getHost() {
return host;
}
public String getUserName() {
return userName;
}
} | 8,736 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHCommandOutputReader.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import com.jcraft.jsch.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class SSHCommandOutputReader {
private static final Logger logger = LoggerFactory.getLogger(SSHCommandOutputReader.class);
String stdOutputString = null;
String stdErrorString = null;
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
private int exitCode;
public void onOutput(Channel channel) {
try {
this.setStdOutputString(getOutputStream(channel, channel.getInputStream()));
this.setStdErrorString(new String(errorStream.toByteArray(), "UTF-8"));
this.exitCode = channel.getExitStatus();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private String getOutputStream(Channel channel, InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder("");
byte[] tmp = new byte[1024];
do {
while (inputStream.available() > 0) {
int i = inputStream.read(tmp, 0, 1024);
if (i < 0) break;
output.append(new String(tmp, 0, i));
}
} while (!channel.isClosed()) ;
return output.toString();
}
public void setExitCode(int exitCode) {
this.exitCode = exitCode;
}
public int getExitCode() {
return exitCode;
}
public String getStdOutputString() {
return stdOutputString;
}
public void setStdOutputString(String stdOutputString) {
this.stdOutputString = stdOutputString;
}
public String getStdErrorString() {
return stdErrorString;
}
public void setStdErrorString(String stdErrorString) {
this.stdErrorString = stdErrorString;
}
public ByteArrayOutputStream getErrorStream() {
return errorStream;
}
} | 8,737 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHServerInfo.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SSHServerInfo extends ServerInfo {
private final static Logger logger = LoggerFactory.getLogger(SSHServerInfo.class);
SSHKeyAuthentication authentication;
int sshPort;
public SSHServerInfo(String userName, String host, SSHKeyAuthentication authentication, int port){
super(userName, host, ComProtocol.SSH, port);
this.authentication = authentication;
this.sshPort = port;
}
public SSHServerInfo(String userName, String host, SSHKeyAuthentication authentication){
super(userName, host, ComProtocol.SSH, 22);
this.authentication = authentication;
this.sshPort = 22;
}
public SSHKeyAuthentication getAuthentication() {
return authentication;
}
public int getSshPort() {
return sshPort;
}
} | 8,738 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHTaskContext.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
public class SSHTaskContext implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(SSHTaskContext.class);
public static enum TASK_TYPE {FILE_COPY, EXECUTE_COMMAND;}
private TASK_TYPE task_type;
private SSHKeyAuthentication sshKeyAuthentication;
private SSHUserInfo sshUserInfo;
private ServerInfo serverInfo;
private String sourceFilePath;
private String destFilePath;
private String command;
/**
* Constructor to create SSHTaskContext for File Copy type
* @param task_type
* @param sshKeyAuthentication
* @param sshUserInfo
* @param serverInfo
* @param sourceFilePath
* @param destFilePath
*/
public SSHTaskContext(TASK_TYPE task_type, SSHKeyAuthentication sshKeyAuthentication, SSHUserInfo sshUserInfo, ServerInfo serverInfo, String sourceFilePath, String destFilePath) {
this.task_type = task_type;
this.sshKeyAuthentication = sshKeyAuthentication;
this.sshUserInfo = sshUserInfo;
this.serverInfo = serverInfo;
this.sourceFilePath = sourceFilePath;
this.destFilePath = destFilePath;
}
/**
* Constructor to crete SSHTaskContext for Command Execute type
* @param task_type
* @param sshKeyAuthentication
* @param sshUserInfo
* @param serverInfo
* @param command
*/
public SSHTaskContext(TASK_TYPE task_type, SSHKeyAuthentication sshKeyAuthentication, SSHUserInfo sshUserInfo, ServerInfo serverInfo, String command) {
this.task_type = task_type;
this.sshKeyAuthentication = sshKeyAuthentication;
this.sshUserInfo = sshUserInfo;
this.serverInfo = serverInfo;
this.command = command;
}
public TASK_TYPE getTask_type() {
return task_type;
}
public void setTask_type(TASK_TYPE task_type) {
this.task_type = task_type;
}
public SSHKeyAuthentication getSshKeyAuthentication() {
return sshKeyAuthentication;
}
public void setSshKeyAuthentication(SSHKeyAuthentication sshKeyAuthentication) {
this.sshKeyAuthentication = sshKeyAuthentication;
}
public SSHUserInfo getSshUserInfo() {
return sshUserInfo;
}
public void setSshUserInfo(SSHUserInfo sshUserInfo) {
this.sshUserInfo = sshUserInfo;
}
public ServerInfo getServerInfo() {
return serverInfo;
}
public void setServerInfo(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
public String getSourceFilePath() {
return sourceFilePath;
}
public void setSourceFilePath(String sourceFilePath) {
this.sourceFilePath = sourceFilePath;
}
public String getDestFilePath() {
return destFilePath;
}
public void setDestFilePath(String destFilePath) {
this.destFilePath = destFilePath;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
@Override
public String toString() {
return "SSHTaskContext{" +
"task_type=" + task_type +
", sshKeyAuthentication=" + sshKeyAuthentication +
", sshUserInfo=" + sshUserInfo +
", serverInfo=" + serverInfo +
", sourceFilePath='" + sourceFilePath + '\'' +
", destFilePath='" + destFilePath + '\'' +
", command='" + command + '\'' +
'}';
}
} | 8,739 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/Authentication.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
public class Authentication implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(Authentication.class);
protected String userName;
} | 8,740 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHKeyAuthentication.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
public class SSHKeyAuthentication extends Authentication {
private byte[] privateKey;
private byte[] publicKey;
private String passphrase;
private String knownHostsFilePath;
private String strictHostKeyChecking; // yes or no
public SSHKeyAuthentication(String userName, byte[] privateKey, byte[] publicKey, String passphrase, String knownHostsFilePath, boolean strictHostKeyChecking) {
this.userName = userName;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.passphrase = passphrase;
this.knownHostsFilePath = knownHostsFilePath;
if(strictHostKeyChecking){
this.strictHostKeyChecking = "yes";
}else{
this.strictHostKeyChecking = "no";
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public byte[] getPrivateKey() {
return privateKey;
}
public void setPrivateKey(byte[] privateKey) {
this.privateKey = privateKey;
}
public byte[] getPublicKey() {
return publicKey;
}
public void setPublicKey(byte[] publicKey) {
this.publicKey = publicKey;
}
public String getPassphrase() {
return passphrase;
}
public void setPassphrase(String passphrase) {
this.passphrase = passphrase;
}
public String getKnownHostsFilePath() {
return knownHostsFilePath;
}
public void setKnownHostsFilePath(String knownHostsFilePath) {
this.knownHostsFilePath = knownHostsFilePath;
}
public String getStrictHostKeyChecking() {
return strictHostKeyChecking;
}
public void setStrictHostKeyChecking(String strictHostKeyChecking) {
this.strictHostKeyChecking = strictHostKeyChecking;
}
}
| 8,741 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHRunner.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
public class SSHRunner {
private final static Logger log = LoggerFactory.getLogger(SSHRunner.class);
public Session createSSHSession(SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws JSchException {
JSch jSch = new JSch();
jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(),
authentication.getPassphrase().getBytes());
Session session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(),
serverInfo.getSshPort());
session.setUserInfo(new SSHUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase()));
if (authentication.getStrictHostKeyChecking().equals("yes")) {
jSch.setKnownHosts(authentication.getKnownHostsFilePath());
} else {
session.setConfig("StrictHostKeyChecking", "no");
}
session.connect();
return session;
}
public String scpTo(String routingKey, String localFile, String remoteFile, SSHServerInfo serverInfo,
SSHKeyAuthentication authentication) throws IOException, JSchException, SSHApiException {
Session session = createSSHSession(serverInfo, authentication);
FileInputStream fis = null;
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile;
Channel channel = session.openChannel("exec");
SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream());
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
File _lfile = new File(localFile);
if (ptimestamp) {
command = "T" + (_lfile.lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (localFile.lastIndexOf('/') > 0) {
command += localFile.substring(localFile.lastIndexOf('/') + 1);
} else {
command += localFile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
// send a content of localFile
fis = new FileInputStream(localFile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
out.close();
stdOutReader.onOutput(channel);
channel.disconnect();
if (stdOutReader.getStdErrorString().contains("scp:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
session.disconnect();
//since remote file is always a file we just return the file
return remoteFile;
}
/**
* This method will copy a remote file to a local directory
*
* @param remoteFile remote file path, this has to be a full qualified path
* @param localFile This is the local file to copy, this can be a directory too
* @return returns the final local file path of the new file came from the remote resource
*/
public void scpFrom(String routingKey, String remoteFile, String localFile, SSHServerInfo serverInfo,
SSHKeyAuthentication authentication) throws IOException,
JSchException, SSHApiException {
Session session = createSSHSession(serverInfo, authentication);
FileOutputStream fos = null;
try {
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader();
// exec 'scp -f remotefile' remotely
String command = "scp -f " + remoteFile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream());
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
if (!channel.isClosed()){
channel.connect();
}
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') break;
filesize = filesize * 10L + (long) (buf[0] - '0');
}
String file = null;
for (int i = 0; ; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
//System.out.println("filesize="+filesize+", file="+file);
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
fos = new FileOutputStream(prefix == null ? localFile : prefix + file);
int foo;
while (true) {
if (buf.length < filesize) foo = buf.length;
else foo = (int) filesize;
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L) break;
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
String error = "Error transfering the file content";
log.error(error);
throw new SSHApiException(error);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
}
stdOutReader.onOutput(channel);
if (stdOutReader.getStdErrorString().contains("scp:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (fos != null) fos.close();
session.disconnect();
} catch (Exception ee) {
}
}
}
public void makeDirectory(String routingKey, String path, SSHServerInfo serverInfo, SSHKeyAuthentication authentication)
throws IOException, JSchException, Exception {
Session session = createSSHSession(serverInfo, authentication);
// exec 'scp -t rfile' remotely
String command = "mkdir -p " + path;
Channel channel = session.openChannel("exec");
SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream());
try {
channel.connect();
} catch (JSchException e) {
channel.disconnect();
log.error("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName());
throw e;
}
stdOutReader.onOutput(channel);
if (stdOutReader.getStdErrorString().contains("mkdir:")) {
throw new Exception(stdOutReader.getStdErrorString());
}
channel.disconnect();
session.disconnect();
}
public List<String> listDirectory(String routingKey, String path, SSHServerInfo serverInfo, SSHKeyAuthentication authentication)
throws IOException, JSchException, Exception {
Session session = createSSHSession(serverInfo, authentication);
// exec 'scp -t rfile' remotely
String command = "ls " + path;
Channel channel = session.openChannel("exec");
SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream());
try {
channel.connect();
} catch (JSchException e) {
channel.disconnect();
throw new Exception("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
}
if (stdOutReader.getStdErrorString().contains("ls:")) {
throw new Exception(stdOutReader.getStdErrorString());
}
channel.disconnect();
session.disconnect();
return Arrays.asList(stdOutReader.getStdOutputString().split("\n"));
}
public SSHCommandOutputReader executeCommand(String routingKey, String command, SSHServerInfo serverInfo,
SSHKeyAuthentication authentication) throws Exception {
Session session = createSSHSession(serverInfo, authentication);
Map<String, String> results = new HashMap<>();
Channel channel = session.openChannel("exec");
SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream());
try {
channel.connect();
} catch (JSchException e) {
channel.disconnect();
throw new Exception("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
}
stdOutReader.onOutput(channel);
session.disconnect();
return stdOutReader;
}
public SSHCommandOutputReader executeCommand(String routingKey, String[] commands, SSHServerInfo serverInfo,
SSHKeyAuthentication authentication) throws Exception {
return executeCommand(routingKey, String.join(" && ", commands), serverInfo, authentication);
}
private int checkAck(InputStream in) throws IOException {
int b = in.read();
if (b == 0) return b;
if (b == -1) return b;
if (b == 1 || b == 2) {
StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
if (b == 1) { // error
System.out.print(sb.toString());
}
if (b == 2) { // fatal error
System.out.print(sb.toString());
}
log.warn(sb.toString());
}
return b;
}
} | 8,742 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/airavata/tasks/ssh/SSHTask.java | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package edu.iu.helix.airavata.tasks.ssh;
import edu.iu.helix.airavata.HelixUtil;
import edu.iu.helix.airavata.ZkUtils;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class SSHTask implements Task {
private final static Logger logger = LoggerFactory.getLogger(SSHTask.class);
public static final String TASK_COMMAND = "SSH_TASK";
private TaskCallbackContext callbackContext;
private String taskId;
public SSHTask(TaskCallbackContext callbackContext){
this.callbackContext = callbackContext;
this.taskId = callbackContext.getTaskConfig().getId();
}
@Override
public TaskResult run() {
// Todo Should be stored before the DAG execution start
// byte[] input = SerializationUtils.serialize(yourList);
// curator.create()
// .creatingParentContainersIfNeeded()
// .forPath(path, input);
// Todo Deserialize the TaskContext from data store.
// byte[] output = curator.getData().forPath(path);
// List<String> newList = (List<String>)SerializationUtils.deserialize(output);
System.out.println("Running SSH Task for ID: " + taskId);
try {
SSHTaskContext taskContext = (SSHTaskContext) ZkUtils.getZkData(ZkUtils.getCuratorClient(), HelixUtil.SSH_WORKFLOW, taskId);
String routingKey = UUID.randomUUID().toString();
SSHRunner sshExecutor = new SSHRunner();
System.out.println("Task: " + taskId + ", is of Type: " + taskContext.getTask_type());
switch (taskContext.getTask_type()) {
case EXECUTE_COMMAND:
SSHCommandOutputReader sshOut = sshExecutor.executeCommand(routingKey, taskContext.getCommand(),
(SSHServerInfo) taskContext.getServerInfo(), taskContext.getSshKeyAuthentication());
System.out.println("SSH Command Output: " + sshOut.getStdOutputString());
break;
case FILE_COPY:
String scpOut = sshExecutor.scpTo(routingKey, taskContext.getSourceFilePath(), taskContext.getDestFilePath(),
(SSHServerInfo) taskContext.getServerInfo(), taskContext.getSshKeyAuthentication());
System.out.println("SCP Command Output: " + scpOut);
break;
default:
throw new Exception("Unknown SSH Task Type: " + taskContext.getTask_type());
}
} catch (Exception ex) {
System.err.println("Something went wrong for task: " + taskId + ", reason: " + ex);
return new TaskResult(TaskResult.Status.FAILED, "SSH command completed!");
}
return new TaskResult(TaskResult.Status.COMPLETED, "SSH command completed!");
}
@Override
public void cancel() {
}
} | 8,743 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/play/HelixTaskA.java | package edu.iu.helix.play;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/19/17.
*/
public class HelixTaskA extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskA.class);
public static final String TASK_COMMAND = "HelixTask-A";
HelixTaskA(TaskCallbackContext callbackContext) {
logger.info("edu.iu.helix.play.HelixTaskA | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
logger.info("edu.iu.helix.play.HelixTaskA | Inside run(), sleeping for 5 secs");
addToUserStore();
sleep(5000);
logger.info("edu.iu.helix.play.HelixTaskA | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "HelixTask completed!");
}
@Override
public void cancel() {
logger.info("edu.iu.helix.play.HelixTaskA | Inside cancel()");
}
private void addToUserStore() {
logger.info("edu.iu.helix.play.HelixTaskA | Inside addToUserStore()");
putUserContent("fullName", "Gourav Shenoy", Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,744 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/play/HelixTaskB.java | package edu.iu.helix.play;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by goshenoy on 6/20/17.
*/
public class HelixTaskB extends UserContentStore implements Task {
private static Logger logger = LogManager.getLogger(HelixTaskA.class);
public static final String TASK_COMMAND = "HelixTask-B";
HelixTaskB(TaskCallbackContext callbackContext) {
logger.info("edu.iu.helix.play.HelixTaskB | callbackContext: " + callbackContext);
}
@Override
public TaskResult run() {
logger.info("edu.iu.helix.play.HelixTaskB | Inside run(), sleeping for 5 secs");
long expiry = System.currentTimeMillis() + 3000L;
while (System.currentTimeMillis() < expiry) {
logger.info("edu.iu.helix.play.HelixTaskB | Inside run(), *** Waiting ***");
// sleep(50);
}
logger.info("edu.iu.helix.play.HelixTaskB | Retrieved from UserStore : " + getFromUserStore("fullName"));
logger.info("edu.iu.helix.play.HelixTaskB | Returning status : COMPLETED.");
return new TaskResult(TaskResult.Status.COMPLETED, "edu.iu.helix.play.HelixTaskB completed!");
}
@Override
public void cancel() {
logger.info("edu.iu.helix.play.HelixTaskB | Inside cancel()");
}
private String getFromUserStore(String key) {
logger.info("edu.iu.helix.play.HelixTaskB | Inside getFromUserStore()");
return getUserContent(key, Scope.WORKFLOW);
}
private static void sleep(long d) {
try {
Thread.sleep(d);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 8,745 |
0 | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix | Create_ds/airavata-sandbox/helix-playground/src/main/java/edu/iu/helix/play/HelixDAGFramework.java | package edu.iu.helix.play;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.examples.OnlineOfflineStateModelFactory;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.task.*;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.testng.Assert;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by goshenoy on 6/18/17.
*/
public class HelixDAGFramework {
private static Logger logger = LogManager.getLogger(HelixDAGFramework.class);
private static final String ZK_ADDRESS = "localhost:2199";
private static final String PARTICIPANT_ADDRESS = "localhost:12918";
private static final String CLUSTER_NAME = "HelixDagCluster";
private static final String RESOURCE_NAME = "HelixResource";
private static final String CONTROLLER_NAME = "HelixController";
private static final String ADMIN_NAME = "HelixAdmin";
private static final String WORKFLOW_NAME = "helix_workflow";
private static final String JOB_NAME = "helix_job";
private static final String TASK_A_NAME = "helix_task_id_a";
private static final String TASK_B_NAME = "helix_task_id_b";
private static final String ONLINE_OFFLINE = "OnlineOffline";
private static HelixManager adminManager;
private static ZKHelixManager participantManager;
private static ZKHelixManager controllerManager;
private static ClusterSetup _setupTool;
public static void main(String[] args) {
try {
// create cluster
createCluster();
// add instance, resource to cluster
addInstanceToCluster();
addResourceToCluster();
// create participant, controller & admin manager
createParticipantManager();
createControllerManager();
createAdminManager();
// verifying cluster state
verifyClusterState();
// create task-driver
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating TaskDriver.");
TaskDriver taskDriver = new TaskDriver(adminManager);
// create task-config list
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating TaskConfig list.");
List<TaskConfig> taskConfigList1 = new ArrayList<TaskConfig>();
List<TaskConfig> taskConfigList2 = new ArrayList<TaskConfig>();
taskConfigList1.add(
new TaskConfig.Builder().setTaskId(TASK_A_NAME).setCommand(HelixTaskA.TASK_COMMAND).build()
);
taskConfigList2.add(
new TaskConfig.Builder().setTaskId(TASK_B_NAME).setCommand(HelixTaskB.TASK_COMMAND).build()
);
// create job-config-builder
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating JobConfig.Builder.");
JobConfig.Builder jobConfigBuilder1 = new JobConfig.Builder().addTaskConfigs(taskConfigList1);
JobConfig.Builder jobConfigBuilder2 = new JobConfig.Builder().addTaskConfigs(taskConfigList2);
// create workflow-builder & add job
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating Workflow.Builder.");
Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME).setExpiry(0);
logger.info("edu.iu.helix.play.HelixDAGFramework | Adding Jobs (a,b) to Workflow.Builder.");
workflowBuilder.addJob(JOB_NAME + "_a", jobConfigBuilder1);
workflowBuilder.addJob(JOB_NAME + "_b", jobConfigBuilder2);
logger.info("edu.iu.helix.play.HelixDAGFramework | Setting Job A parent of Job B.");
workflowBuilder.addParentChildDependency(JOB_NAME + "_a", JOB_NAME + "_b");
// start the workflow
logger.info("edu.iu.helix.play.HelixDAGFramework | Starting the Workflow.");
taskDriver.start(workflowBuilder.build());
// waiting for job to complete
logger.info("edu.iu.helix.play.HelixDAGFramework | Waiting for Workflow to COMPLETE.");
// taskDriver.pollForJobState(WORKFLOW_NAME, WORKFLOW_NAME + "_" + JOB_NAME, TaskState.COMPLETED);
taskDriver.pollForWorkflowState(WORKFLOW_NAME, TaskState.COMPLETED);
// job completed, exit
logger.info("edu.iu.helix.play.HelixDAGFramework | Job Completed, Exiting.");
} catch (Exception ex) {
logger.error("Exception caught | ex: " + ex.getMessage(), ex);
} finally {
// disconnect all managers
logger.info("edu.iu.helix.play.HelixDAGFramework | Disconnecting All Managers (Participant, Controller, Admin).");
disconnectManagers();
logger.info("edu.iu.helix.play.HelixDAGFramework | Bye!");
}
}
private static void createCluster() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating a cluster.");
_setupTool = new ClusterSetup(ZK_ADDRESS);
_setupTool.addCluster(CLUSTER_NAME, true);
}
private static void addInstanceToCluster() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Adding instanace to cluster.");
_setupTool.addInstanceToCluster(CLUSTER_NAME, PARTICIPANT_ADDRESS);
}
private static void addResourceToCluster() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Adding resource to cluster.");
_setupTool.addResourceToCluster(CLUSTER_NAME, RESOURCE_NAME, 1, ONLINE_OFFLINE);
_setupTool.rebalanceStorageCluster(CLUSTER_NAME, RESOURCE_NAME, 1);
}
private static void createParticipantManager() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating a Participant Manager.");
String instanceName = PARTICIPANT_ADDRESS.replaceAll(":", "_");
participantManager = new ZKHelixManager(CLUSTER_NAME, instanceName, InstanceType.PARTICIPANT, ZK_ADDRESS);
logger.info("edu.iu.helix.play.HelixDAGFramework | Registering SMF for Participant.");
StateMachineEngine sme = participantManager.getStateMachineEngine();
sme.registerStateModelFactory(BuiltInStateModelDefinitions.OnlineOffline.name(), new OnlineOfflineStateModelFactory());
try {
logger.info("edu.iu.helix.play.HelixDAGFramework | Registering Task for Participant.");
registerTaskAndStateModel();
logger.info("edu.iu.helix.play.HelixDAGFramework | Starting Participant Manager.");
participantManager.connect();
} catch (Exception ex) {
logger.error("Error creating Participant Manager, ex: " + ex, ex);
}
}
private static void createAdminManager() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating a Admin Manager.");
adminManager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, ADMIN_NAME, InstanceType.ADMINISTRATOR, ZK_ADDRESS);
try {
logger.info("edu.iu.helix.play.HelixDAGFramework | Starting Admin Manager.");
adminManager.connect();
} catch (Exception ex) {
logger.error("Error creating Admin Manager, ex: " + ex, ex);
}
}
private static void createControllerManager() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Creating a Controller Manager.");
controllerManager = new ZKHelixManager(CLUSTER_NAME, CONTROLLER_NAME, InstanceType.CONTROLLER, ZK_ADDRESS);
try {
logger.info("edu.iu.helix.play.HelixDAGFramework | Starting Controller Manager.");
controllerManager.connect();
} catch (Exception ex) {
logger.error("Error creating Controller Manager, ex: " + ex, ex);
}
}
private static void registerTaskAndStateModel() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Registering Task.");
Map<String, TaskFactory> taskRegistry = new HashMap<String, TaskFactory>();
taskRegistry.put(HelixTaskA.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskA(context);
}
});
taskRegistry.put(HelixTaskB.TASK_COMMAND, new TaskFactory() {
@Override
public Task createNewTask(TaskCallbackContext context) {
return new HelixTaskB(context);
}
});
logger.info("edu.iu.helix.play.HelixDAGFramework | Registering Task StateModel Factory.");
StateMachineEngine sme = participantManager.getStateMachineEngine();
sme.registerStateModelFactory("Task", new TaskStateModelFactory(participantManager, taskRegistry));
}
private static void verifyClusterState() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Verifying Cluster State.");
boolean result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDRESS, CLUSTER_NAME));
Assert.assertTrue(result);
}
private static void disconnectManagers() {
logger.info("edu.iu.helix.play.HelixDAGFramework | Disconnecting Admin Manager.");
adminManager.disconnect();
logger.info("edu.iu.helix.play.HelixDAGFramework | Disconnecting Participant Manager.");
participantManager.disconnect();
logger.info("edu.iu.helix.play.HelixDAGFramework | Disconnecting Contoller Manager.");
controllerManager.disconnect();
System.exit(0);
}
}
| 8,746 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/Application.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@SpringBootApplication
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
| 8,747 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/service/ExperimentLaunchService.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator.service;
import org.apache.airavata.k8s.api.resources.application.ApplicationDeploymentResource;
import org.apache.airavata.k8s.api.resources.application.ApplicationIfaceResource;
import org.apache.airavata.k8s.api.resources.compute.ComputeResource;
import org.apache.airavata.k8s.api.resources.experiment.ExperimentInputResource;
import org.apache.airavata.k8s.api.resources.experiment.ExperimentOutputResource;
import org.apache.airavata.k8s.api.resources.experiment.ExperimentResource;
import org.apache.airavata.k8s.api.resources.process.ProcessResource;
import org.apache.airavata.k8s.api.resources.task.TaskParamResource;
import org.apache.airavata.k8s.api.resources.task.TaskResource;
import org.apache.airavata.k8s.orchestrator.messaging.KafkaSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Service
public class ExperimentLaunchService {
private final RestTemplate restTemplate;
private final KafkaSender kafkaSender;
@Value("${api.server.url}")
private String apiServerUrl;
@Value("${scheduler.topic.name}")
private String schedulerTopic;
public ExperimentLaunchService(RestTemplate restTemplate, KafkaSender kafkaSender) {
this.restTemplate = restTemplate;
this.kafkaSender = kafkaSender;
}
public void launch(long experimentId) {
ExperimentResource experimentResource = this.restTemplate.getForObject(
"http://" + this.apiServerUrl + "/experiment/{experimentId}",
ExperimentResource.class,
experimentId);
ApplicationIfaceResource ifaceResource = this.restTemplate.getForObject(
"http://" + this.apiServerUrl + "/appiface/{ifaceId}",
ApplicationIfaceResource.class,
experimentResource.getApplicationInterfaceId());
ApplicationDeploymentResource deploymentResource = this.restTemplate.getForObject(
"http://" + this.apiServerUrl + "/appdep/{depId}",
ApplicationDeploymentResource.class,
experimentResource.getApplicationDeploymentId());
ComputeResource computeResource = this.restTemplate.getForObject(
"http://" + this.apiServerUrl + "/compute/{computeId}",
ComputeResource.class,
deploymentResource.getComputeResourceId());
ProcessResource processResource = new ProcessResource();
processResource.setCreationTime(System.currentTimeMillis());
processResource.setExperimentDataDir("/tmp/experiments/" + experimentId);
processResource.setExperimentId(experimentId);
List<TaskResource> taskDagResources = determineTaskDag(experimentResource, ifaceResource, deploymentResource, processResource, computeResource);
processResource.setTasks(taskDagResources);
Long processId = this.restTemplate.postForObject("http://" + this.apiServerUrl + "/process", processResource, Long.class);
System.out.println("Iface " + ifaceResource.getName() + ", Dep " + deploymentResource.getId());
kafkaSender.send(schedulerTopic, processId.toString());
}
private List<TaskResource> determineTaskDag(ExperimentResource exRes,
ApplicationIfaceResource appIfRes,
ApplicationDeploymentResource appDepRes,
ProcessResource processResource,
ComputeResource computeResource) {
List<TaskResource> taskDag = new ArrayList<>();
/*AtomicInteger dagOrder = new AtomicInteger(0);
TaskResource dataDirTaskReasource = new TaskResource();
dataDirTaskReasource.setTaskType(TaskResource.TaskTypes.ENV_SETUP);
dataDirTaskReasource.setCreationTime(System.currentTimeMillis());
dataDirTaskReasource.setTaskDetail("Create data dir command for experiment " + exRes.getId());
dataDirTaskReasource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("command").setValue("/bin/mkdir -p {process-data-dir}/inputs && mkdir -p {process-data-dir}/outputs"),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
dataDirTaskReasource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(dataDirTaskReasource);
Optional.ofNullable(appDepRes.getPreJobCommand()).ifPresent(preJob -> {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.ENV_SETUP);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Pre-job command for experiment " + exRes.getId());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("command").setValue(preJob),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
});
StringBuffer inputArgument = new StringBuffer();
Optional.ofNullable(exRes.getExperimentInputs()).ifPresent(exInps -> exInps.forEach(expInp -> {
switch (expInp.getType()) {
case ExperimentInputResource.Types.URI:
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.INGRESS_DATA_STAGING);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Ingress data staging for input " + expInp.getName());
String localPath = "{process-data-dir}/inputs/" + expInp.getId();
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("source").setValue(expInp.getValue()),
new TaskParamResource().setKey("target").setValue(localPath),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
inputArgument.append(" ");
if (expInp.getArguments() != null && !expInp.getArguments().isEmpty()) {
inputArgument.append(expInp.getArguments());
inputArgument.append(" ");
}
inputArgument.append(localPath);
taskDag.add(resource);
break;
case ExperimentInputResource.Types.FLOAT:
case ExperimentInputResource.Types.STRING:
case ExperimentInputResource.Types.INTEGER:
inputArgument.append(" ");
if (expInp.getArguments() != null && !expInp.getArguments().isEmpty()) {
inputArgument.append(expInp.getArguments());
inputArgument.append(" ");
}
inputArgument.append(expInp.getValue());
break;
}
}));
inputArgument.append(" > {process-data-dir}/outputs/stdout.txt 2> {process-data-dir}/outputs/stderr.txt");
Optional.ofNullable(appDepRes.getExecutablePath()).ifPresent(exPath -> {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.JOB_SUBMISSION);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Job submission command for experiment " + exRes.getId());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("command").setValue(exPath),
new TaskParamResource().setKey("arguments").setValue(inputArgument.toString()),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
});
Optional.ofNullable(exRes.getExperimentOutputs()).ifPresent(exOps -> exOps.forEach(expOut -> {
if (expOut.getType() == ExperimentOutputResource.Types.URI) {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.EGRESS_DATA_STAGING);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Egress data staging for output " + expOut.getName());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("source").setValue("{process-data-dir}/" + expOut.getValue()),
new TaskParamResource().setKey("target").setValue(expOut.getId() + ""),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
}
if (expOut.getType() == ExperimentOutputResource.Types.STDOUT) {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.EGRESS_DATA_STAGING);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Egress data staging for output " + expOut.getName());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("source").setValue("{process-data-dir}/outputs/stdout.txt"),
new TaskParamResource().setKey("target").setValue(expOut.getId() + ""),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
}
if (expOut.getType() == ExperimentOutputResource.Types.STDERR) {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.EGRESS_DATA_STAGING);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Egress data staging for output " + expOut.getName());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("source").setValue("{process-data-dir}/outputs/stderr.txt"),
new TaskParamResource().setKey("target").setValue(expOut.getId() + ""),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
}
}));
Optional.ofNullable(appDepRes.getPostJobCommand()).ifPresent(postJob -> {
TaskResource resource = new TaskResource();
resource.setTaskType(TaskResource.TaskTypes.ENV_CLEANUP);
resource.setCreationTime(System.currentTimeMillis());
resource.setTaskDetail("Post-job command for experiment " + exRes.getId());
resource.setTaskParams(Arrays.asList(
new TaskParamResource().setKey("exp-data-dir").setValue(processResource.getExperimentDataDir()),
new TaskParamResource().setKey("command").setValue(postJob),
new TaskParamResource().setKey("compute-id").setValue(computeResource.getId() + ""),
new TaskParamResource().setKey("compute-name").setValue(computeResource.getName() + "")));
resource.setReferenceId(dagOrder.incrementAndGet());
taskDag.add(resource);
});*/
return taskDag;
}
}
| 8,748 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/messaging/KafkaSender.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator.messaging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class KafkaSender {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void send(String topic, String payload) {
kafkaTemplate.send(topic, payload);
}
}
| 8,749 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/messaging/KafkaReceiver.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator.messaging;
import org.apache.airavata.k8s.orchestrator.service.ExperimentLaunchService;
import org.springframework.kafka.annotation.KafkaListener;
import javax.annotation.Resource;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class KafkaReceiver {
@Resource
private ExperimentLaunchService experimentLaunchService;
@KafkaListener(topics = "${launch.topic.name}")
public void receive(String payload) {
System.out.println("received payload=" + payload);
if (payload.startsWith("exp-")) {
long experimentId = Long.parseLong(payload.substring(4));
this.experimentLaunchService.launch(experimentId);
}
}
}
| 8,750 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/messaging/SenderConfig.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator.messaging;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Configuration
public class SenderConfig {
@Value("${kafka.bootstrap-servers}")
private String bootstrapServers;
@Bean
public Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
// list of host:port pairs used for establishing the initial connections to the Kakfa cluster
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}
@Bean
public ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<String, String>(producerConfigs());
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public KafkaSender kafkaSender() {
return new KafkaSender();
}
}
| 8,751 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/workflow-generator/src/main/java/org/apache/airavata/k8s/orchestrator/messaging/ReceiverConfig.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.orchestrator.messaging;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import java.util.HashMap;
import java.util.Map;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Configuration
@EnableKafka
public class ReceiverConfig {
@Value("${kafka.bootstrap-servers}")
private String bootstrapServers;
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
// list of host:port pairs used for establishing the initial connections to the Kakfa cluster
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
// allows a pool of processes to divide the work of consuming and processing records
props.put(ConsumerConfig.GROUP_ID_CONFIG, "helloworld");
return props;
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<String, String>(consumerConfigs());
}
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
@Bean
public KafkaReceiver receiver() {
return new KafkaReceiver();
}
}
| 8,752 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/Application.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* TODO: Class level comments please
*
* @author Dimuthu Upeksha
* @since 1.0.0-SNAPSHOT
*/
@SpringBootApplication(scanBasePackages={"org.apache.airavata.k8s.api.server.controller"})
@EnableJpaRepositories(basePackages = {"org.apache.airavata.k8s.api.server.repository"})
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
| 8,753 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/ServerRuntimeException.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class ServerRuntimeException extends RuntimeException {
public ServerRuntimeException(Exception e) {
super(e);
}
public ServerRuntimeException(String message) {
super(message);
}
public ServerRuntimeException(String message, Exception e) {
super(message, e);
}
}
| 8,754 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/compute/ComputeRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.compute;
import org.apache.airavata.k8s.api.server.model.compute.ComputeResourceModel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ComputeRepository extends CrudRepository<ComputeResourceModel, Long> {
public Optional<ComputeResourceModel> findById(long id);
}
| 8,755 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/workflow/WorkflowRepository.java | package org.apache.airavata.k8s.api.server.repository.workflow;
import org.apache.airavata.k8s.api.server.model.workflow.Workflow;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface WorkflowRepository extends CrudRepository<Workflow, Long> {
public Optional<Workflow> findById(long id);
}
| 8,756 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskInputRepository.java | package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskInput;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskInputRepository extends CrudRepository<TaskInput, Long> {
}
| 8,757 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskModel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskRepository extends CrudRepository<TaskModel, Long> {
public Optional<TaskModel> findById(long id);
}
| 8,758 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskOutPortRepository.java | package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskOutPort;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskOutPortRepository extends CrudRepository<TaskOutPort, Long> {
Optional<TaskOutPort> findByName(String name);
Optional<TaskOutPort> findByReferenceIdAndTaskModel_Id(int referenceId, long taskId);
}
| 8,759 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskStatusRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskStatus;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskStatusRepository extends CrudRepository<TaskStatus, Long> {
public Optional<TaskStatus> findById(long id);
}
| 8,760 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskOutputRepository.java | package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskOutput;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskOutputRepository extends CrudRepository<TaskOutput, Long> {
}
| 8,761 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/TaskDAGRepository.java | package org.apache.airavata.k8s.api.server.repository.task;
import org.apache.airavata.k8s.api.server.model.task.TaskDAG;
import org.springframework.data.repository.CrudRepository;
import java.util.Iterator;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskDAGRepository extends CrudRepository<TaskDAG, Long> {
public Iterable<TaskDAG> findBysourceOutPort_taskModel_parentProcess_id(long processId);
}
| 8,762 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/type/TaskInputTypeRepository.java | package org.apache.airavata.k8s.api.server.repository.task.type;
import org.apache.airavata.k8s.api.server.model.task.type.TaskInputType;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskInputTypeRepository extends CrudRepository<TaskInputType, Long> {
}
| 8,763 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/type/TaskOutPortTypeRepository.java | package org.apache.airavata.k8s.api.server.repository.task.type;
import org.apache.airavata.k8s.api.server.model.task.type.TaskOutPortType;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskOutPortTypeRepository extends CrudRepository<TaskOutPortType, Long> {
}
| 8,764 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/type/TaskOutputTypeRepository.java | package org.apache.airavata.k8s.api.server.repository.task.type;
import org.apache.airavata.k8s.api.server.model.task.type.TaskOutputType;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskOutputTypeRepository extends CrudRepository<TaskOutputType, Long> {
}
| 8,765 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/task/type/TaskTypeRepository.java | package org.apache.airavata.k8s.api.server.repository.task.type;
import org.apache.airavata.k8s.api.server.model.task.type.TaskModelType;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskTypeRepository extends CrudRepository<TaskModelType, Long> {
Optional<TaskModelType> findById(long id);
Optional<TaskModelType> findByName(String name);
}
| 8,766 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/experiment/ExperimentInputDataRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.experiment;
import org.apache.airavata.k8s.api.server.model.experiment.ExperimentInputData;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ExperimentInputDataRepository extends CrudRepository<ExperimentInputData, Long> {
}
| 8,767 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/experiment/ExperimentStatusRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.experiment;
import org.apache.airavata.k8s.api.server.model.experiment.ExperimentStatus;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ExperimentStatusRepository extends CrudRepository<ExperimentStatus, Long> {
}
| 8,768 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/experiment/ExperimentOutputDataRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.experiment;
import org.apache.airavata.k8s.api.server.model.experiment.ExperimentOutputData;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ExperimentOutputDataRepository extends CrudRepository<ExperimentOutputData, Long> {
public Optional<ExperimentOutputData> findById(long id);
}
| 8,769 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/experiment/ExperimentRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.experiment;
import org.apache.airavata.k8s.api.server.model.experiment.Experiment;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ExperimentRepository extends CrudRepository<Experiment, Long> {
public Optional<Experiment> findById(long id);
}
| 8,770 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/application/ApplicationInputRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.application;
import org.apache.airavata.k8s.api.server.model.application.ApplicationInput;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ApplicationInputRepository extends CrudRepository<ApplicationInput, Long> {
}
| 8,771 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/application/ApplicationOutputRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.application;
import org.apache.airavata.k8s.api.server.model.application.ApplicationOutput;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ApplicationOutputRepository extends CrudRepository<ApplicationOutput, Long> {
}
| 8,772 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/application/ApplicationIfaceRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.application;
import org.apache.airavata.k8s.api.server.model.application.ApplicationInterface;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ApplicationIfaceRepository extends CrudRepository<ApplicationInterface, Long> {
public Optional<ApplicationInterface> findById(long id);
}
| 8,773 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/application/ApplicationModuleRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.application;
import org.apache.airavata.k8s.api.server.model.application.ApplicationModule;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ApplicationModuleRepository extends CrudRepository <ApplicationModule, Long> {
public Optional<ApplicationModule> findById(long id);
}
| 8,774 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/application/ApplicationDeploymentRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.application;
import org.apache.airavata.k8s.api.server.model.application.ApplicationDeployment;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ApplicationDeploymentRepository extends CrudRepository<ApplicationDeployment, Long> {
public Optional<ApplicationDeployment> findById(long id);
}
| 8,775 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/data/DataStoreRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.data;
import org.apache.airavata.k8s.api.server.model.data.DataStoreModel;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface DataStoreRepository extends CrudRepository<DataStoreModel, Long>{
List<DataStoreModel> findByTaskModel_ParentProcess_Id(long processId);
}
| 8,776 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/process/ProcessStatusRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.process;
import org.apache.airavata.k8s.api.server.model.process.ProcessStatus;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ProcessStatusRepository extends CrudRepository<ProcessStatus, Long> {
}
| 8,777 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/process/ProcessRepository.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.repository.process;
import org.apache.airavata.k8s.api.server.model.process.ProcessModel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ProcessRepository extends CrudRepository<ProcessModel, Long> {
Optional<ProcessModel> findById(long id);
}
| 8,778 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/repository/process/ProcessBootstrapDataRepository.java | package org.apache.airavata.k8s.api.server.repository.process;
import org.apache.airavata.k8s.api.server.model.process.ProcessBootstrapData;
import org.springframework.data.repository.CrudRepository;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface ProcessBootstrapDataRepository extends CrudRepository<ProcessBootstrapData, Long> {
}
| 8,779 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ApplicationInterfaceController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.application.ApplicationIfaceResource;
import org.apache.airavata.k8s.api.server.service.ApplicationIfaceService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/appiface")
public class ApplicationInterfaceController {
@Resource
private ApplicationIfaceService ifaceService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public Long createApplicationModule(@RequestBody ApplicationIfaceResource resource) {
return ifaceService.create(resource);
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ApplicationIfaceResource> getAllDepResources() {
return this.ifaceService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ApplicationIfaceResource findAppModuleById(@PathVariable("id") long id) {
return this.ifaceService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("App interface with id " + id + " can not be found"));
}
}
| 8,780 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/TaskController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.task.TaskDagResource;
import org.apache.airavata.k8s.api.resources.task.TaskResource;
import org.apache.airavata.k8s.api.resources.task.TaskStatusResource;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.server.service.task.TaskService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Set;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/task")
public class TaskController {
@Resource
private TaskService taskService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public long createTask(@RequestBody TaskResource resource) {
return taskService.create(resource);
}
@PostMapping( path = "{id}/status", consumes = MediaType.APPLICATION_JSON_VALUE)
public long addStatus(@PathVariable("id") long id, @RequestBody TaskStatusResource resource) {
return taskService.addTaskStatus(id, resource);
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public TaskResource findTaskById(@PathVariable("id") long id) {
return this.taskService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Task with id " + id + " not found"));
}
@GetMapping(path = "status/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public TaskStatusResource findTaskStatusById(@PathVariable("id") long id) {
return this.taskService.findTaskStatusById(id)
.orElseThrow(() -> new ServerRuntimeException("Task status with id " + id + " not found"));
}
@GetMapping(path = "dag/{process_id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Set<TaskDagResource> getDagForProcess(@PathVariable("process_id") long processId) {
return this.taskService.getDagForProcess(processId);
}
}
| 8,781 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ProcessController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.process.ProcessStatusResource;
import org.apache.airavata.k8s.api.resources.task.TaskDagResource;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.process.ProcessResource;
import org.apache.airavata.k8s.api.server.service.ProcessService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Set;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/process")
public class ProcessController {
@Resource
private ProcessService processService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public long createProcess(@RequestBody ProcessResource resource) {
return processService.create(resource);
}
@PostMapping( path = "{id}/status", consumes = MediaType.APPLICATION_JSON_VALUE)
public long addStatus(@PathVariable("id") long id, @RequestBody ProcessStatusResource resource) {
return processService.addProcessStatus(id, resource);
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ProcessResource findProcessById(@PathVariable("id") long id) {
return this.processService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Process with id " + id + " not found"));
}
}
| 8,782 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/DataStoreController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.data.DataEntryResource;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.server.service.data.DataStoreService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/data")
public class DataStoreController {
@Resource
private DataStoreService dataStoreService;
@PostMapping("{taskId}/{identifier}/upload")
public long uploadData(@RequestParam("file") MultipartFile file, @PathVariable("taskId") long taskId,
@PathVariable("identifier") String identifier, RedirectAttributes redirectAttributes) {
System.out.println("Received data for task id " + taskId + " and identifier " + identifier);
if (file.isEmpty()) {
throw new ServerRuntimeException("Data file is empty");
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
return this.dataStoreService.createEntry(taskId, identifier, bytes);
} catch (IOException e) {
e.printStackTrace();
throw new ServerRuntimeException("Failed to store file", e);
}
}
@GetMapping("process/{id}")
public List<DataEntryResource> getAllEntriesForProcess(@PathVariable("id") long processId) {
return this.dataStoreService.getEntriesForProcess(processId);
}
}
| 8,783 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ApplicationModuleController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.compute.ComputeResource;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.application.ApplicationModuleResource;
import org.apache.airavata.k8s.api.server.service.ApplicationModuleService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/appmodule")
public class ApplicationModuleController {
@Resource
private ApplicationModuleService applicationModuleService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public Long createApplicationModule(@RequestBody ApplicationModuleResource resource) {
return applicationModuleService.create(resource);
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ApplicationModuleResource> getAllAppModules() {
return this.applicationModuleService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ApplicationModuleResource findAppModuleById(@PathVariable("id") long id) {
return this.applicationModuleService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Compute resource with id " + id + " can not be found"));
}
}
| 8,784 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/TaskTypeController.java | package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.task.type.TaskTypeResource;
import org.apache.airavata.k8s.api.server.service.task.type.TaskTypeService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/taskType")
public class TaskTypeController {
@Resource
private TaskTypeService taskTypeService;
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<TaskTypeResource> getAll() {
return taskTypeService.getAll();
}
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public long createTask(@RequestBody TaskTypeResource resource) {
return taskTypeService.create(resource);
}
}
| 8,785 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ApplicationDeploymentController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.application.ApplicationDeploymentResource;
import org.apache.airavata.k8s.api.server.service.ApplicationDeploymentService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/appdep")
public class ApplicationDeploymentController {
@Resource
private ApplicationDeploymentService applicationDeploymentService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public Long createApplicationModule(@RequestBody ApplicationDeploymentResource resource) {
return applicationDeploymentService.create(resource);
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ApplicationDeploymentResource> getAllDepResources() {
return this.applicationDeploymentService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ApplicationDeploymentResource findAppModuleById(@PathVariable("id") long id) {
return this.applicationDeploymentService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("App deployment with id " + id + " can not be found"));
}
}
| 8,786 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ComputeResourceController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.compute.ComputeResource;
import org.apache.airavata.k8s.api.server.service.ComputeResourceService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/compute")
public class ComputeResourceController {
@Resource
private ComputeResourceService computeResourceService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public Long createComputeResource(@RequestBody ComputeResource resource) {
return computeResourceService.create(resource);
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ComputeResource> getAllComputeResources() {
return this.computeResourceService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ComputeResource findComputeResourceById(@PathVariable("id") long id) {
return this.computeResourceService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Compute resource with id " + id + " cab not be found"));
}
}
| 8,787 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/ExperimentController.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.resources.experiment.ExperimentResource;
import org.apache.airavata.k8s.api.server.service.ExperimentService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/experiment")
public class ExperimentController {
@Resource
private ExperimentService experimentService;
@PostMapping( path = "", consumes = MediaType.APPLICATION_JSON_VALUE)
public long createExperiment(@RequestBody ExperimentResource resource) {
return experimentService.create(resource);
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ExperimentResource> getAllExperiments() {
return this.experimentService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ExperimentResource findExperimentById(@PathVariable("id") long id) {
return this.experimentService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Experiment with id " + id + " not found"));
}
@GetMapping(path = "{id}/launch", produces = MediaType.APPLICATION_JSON_VALUE)
public long launchExperiment(@PathVariable("id") long id) {
return this.experimentService.launchExperiment(id);
}
}
| 8,788 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/controller/WorkflowController.java | package org.apache.airavata.k8s.api.server.controller;
import org.apache.airavata.k8s.api.resources.experiment.ExperimentResource;
import org.apache.airavata.k8s.api.resources.workflow.WorkflowResource;
import org.apache.airavata.k8s.api.server.ServerRuntimeException;
import org.apache.airavata.k8s.api.server.service.WorkflowService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@RestController
@RequestMapping(path="/workflow")
public class WorkflowController {
@Resource
private WorkflowService workflowService;
@PostMapping(path = "create/{name}")
public long createWorkflow(@PathVariable("name") String name, @RequestBody String workflowGraph) {
return this.workflowService.createWorkflow(new WorkflowResource().setName(name).setWorkflowGraphXML(workflowGraph));
}
@GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<WorkflowResource> getAllWorkflows() {
return this.workflowService.getAll();
}
@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public WorkflowResource findExperimentById(@PathVariable("id") long id) {
return this.workflowService.findById(id)
.orElseThrow(() -> new ServerRuntimeException("Workflow with id " + id + " not found"));
}
@GetMapping(path = "{id}/launch", produces = MediaType.APPLICATION_JSON_VALUE)
public long launchWorkflow(@PathVariable("id") long id) {
return this.workflowService.launchWorkflow(id, null);
}
@PostMapping(path = "{id}/launch", produces = MediaType.APPLICATION_JSON_VALUE)
public long launchWorkflow(@PathVariable("id") long id, @RequestBody Map<String, String> boostrapData) {
return this.workflowService.launchWorkflow(id, boostrapData);
}
}
| 8,789 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/commons/ErrorModel.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.model.commons;
import org.apache.airavata.k8s.api.server.model.task.TaskModel;
import javax.persistence.*;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
@Table(name = "ERROR_MODEL")
public class ErrorModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long creationTime;
private String actualErrorMessage;
private String userFriendlyMessage;
private boolean transientOrPersistent;
@ManyToOne
private TaskModel taskModel;
@OneToMany
private List<ErrorModel> rootCauseErrorList;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getCreationTime() {
return creationTime;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public String getActualErrorMessage() {
return actualErrorMessage;
}
public void setActualErrorMessage(String actualErrorMessage) {
this.actualErrorMessage = actualErrorMessage;
}
public String getUserFriendlyMessage() {
return userFriendlyMessage;
}
public void setUserFriendlyMessage(String userFriendlyMessage) {
this.userFriendlyMessage = userFriendlyMessage;
}
public boolean isTransientOrPersistent() {
return transientOrPersistent;
}
public void setTransientOrPersistent(boolean transientOrPersistent) {
this.transientOrPersistent = transientOrPersistent;
}
public List<ErrorModel> getRootCauseErrorList() {
return rootCauseErrorList;
}
public void setRootCauseErrorList(List<ErrorModel> rootCauseErrorList) {
this.rootCauseErrorList = rootCauseErrorList;
}
public TaskModel getTaskModel() {
return taskModel;
}
public ErrorModel setTaskModel(TaskModel taskModel) {
this.taskModel = taskModel;
return this;
}
}
| 8,790 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/compute/ComputeResourceModel.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.model.compute;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
@Table(name = "COMPUTE_RESOURCE")
public class ComputeResourceModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String host;
private String userName;
private String password;
private String communicationType;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHost() {
return host;
}
public ComputeResourceModel setHost(String host) {
this.host = host;
return this;
}
public String getUserName() {
return userName;
}
public ComputeResourceModel setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public ComputeResourceModel setPassword(String password) {
this.password = password;
return this;
}
public String getCommunicationType() {
return communicationType;
}
public ComputeResourceModel setCommunicationType(String communicationType) {
this.communicationType = communicationType;
return this;
}
}
| 8,791 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/workflow/Workflow.java | package org.apache.airavata.k8s.api.server.model.workflow;
import org.apache.airavata.k8s.api.server.model.process.ProcessModel;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class Workflow {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@Lob
@Column(length = 1000000, name = "CONTENT")
@Basic(fetch = FetchType.LAZY)
private byte[] workFlowGraph;
@OneToMany(mappedBy = "workflow", cascade = CascadeType.ALL)
private List<ProcessModel> processes = new ArrayList<>();
public long getId() {
return id;
}
public Workflow setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Workflow setName(String name) {
this.name = name;
return this;
}
public byte[] getWorkFlowGraph() {
return workFlowGraph;
}
public Workflow setWorkFlowGraph(byte[] workFlowGraph) {
this.workFlowGraph = workFlowGraph;
return this;
}
public List<ProcessModel> getProcesses() {
return processes;
}
public Workflow setProcesses(List<ProcessModel> processes) {
this.processes = processes;
return this;
}
}
| 8,792 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskDAG.java | package org.apache.airavata.k8s.api.server.model.task;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class TaskDAG {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
private TaskOutPort sourceOutPort;
@ManyToOne
private TaskModel targetTask;
public long getId() {
return id;
}
public TaskDAG setId(long id) {
this.id = id;
return this;
}
public TaskOutPort getSourceOutPort() {
return sourceOutPort;
}
public TaskDAG setSourceOutPort(TaskOutPort sourceOutPort) {
this.sourceOutPort = sourceOutPort;
return this;
}
public TaskModel getTargetTask() {
return targetTask;
}
public TaskDAG setTargetTask(TaskModel targetTask) {
this.targetTask = targetTask;
return this;
}
}
| 8,793 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskInput.java | package org.apache.airavata.k8s.api.server.model.task;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class TaskInput {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "TASK_INPUT_NAME")
private String name;
@Column(name = "TASK_INPUT_VALUE")
private String value;
@Column(name = "TASK_INPUT_TYPE")
private String type;
@Column(name = "IMPORT_FORM")
private String importFrom;
@ManyToOne
private TaskModel taskModel;
public long getId() {
return id;
}
public TaskInput setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public TaskInput setName(String name) {
this.name = name;
return this;
}
public String getValue() {
return value;
}
public TaskInput setValue(String value) {
this.value = value;
return this;
}
public String getType() {
return type;
}
public TaskInput setType(String type) {
this.type = type;
return this;
}
public TaskModel getTaskModel() {
return taskModel;
}
public TaskInput setTaskModel(TaskModel taskModel) {
this.taskModel = taskModel;
return this;
}
public String getImportFrom() {
return importFrom;
}
public TaskInput setImportFrom(String importFrom) {
this.importFrom = importFrom;
return this;
}
}
| 8,794 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskStatus.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.model.task;
import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
@Table(name = "TASK_STATUS")
public class TaskStatus {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private TaskState state; // required
private long timeOfStateChange; // optional
private String reason; // optional
@ManyToOne
private TaskModel taskModel;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public TaskState getState() {
return state;
}
public void setState(TaskState state) {
this.state = state;
}
public long getTimeOfStateChange() {
return timeOfStateChange;
}
public void setTimeOfStateChange(long timeOfStateChange) {
this.timeOfStateChange = timeOfStateChange;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public TaskModel getTaskModel() {
return taskModel;
}
public TaskStatus setTaskModel(TaskModel taskModel) {
this.taskModel = taskModel;
return this;
}
public enum TaskState {
CREATED(0),
SCHEDULED(1),
EXECUTING(2),
COMPLETED(3),
FAILED(4),
CANCELED(5);
private final int value;
private TaskState(int value) {
this.value = value;
}
private static Map<Integer, TaskState> map = new HashMap<>();
static {
for (TaskState state : TaskState.values()) {
map.put(state.value, state);
}
}
public static TaskState valueOf(int taskState) {
return map.get(taskState);
}
/**
* Get the integer value of this enum value, as defined in the Thrift IDL.
*/
public int getValue() {
return value;
}
}
}
| 8,795 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskModel.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.airavata.k8s.api.server.model.task;
import org.apache.airavata.k8s.api.server.model.commons.ErrorModel;
import org.apache.airavata.k8s.api.server.model.job.JobModel;
import org.apache.airavata.k8s.api.server.model.process.ProcessModel;
import org.apache.airavata.k8s.api.server.model.task.type.TaskModelType;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
@Table(name = "TASK_MODEL")
public class TaskModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private int referenceId; // to track workflows
private String name;
@ManyToOne
private TaskModelType taskType;
@ManyToOne
private ProcessModel parentProcess;
private long creationTime;
private long lastUpdateTime;
private int orderIndex;
private boolean startingTask;
private boolean stoppingTask;
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<TaskStatus> taskStatuses = new ArrayList<>();
private String taskDetail;
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<ErrorModel> taskErrors = new ArrayList<>();
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<JobModel> jobs = new ArrayList<>();
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<TaskInput> taskInputs = new ArrayList<>();
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<TaskOutput> taskOutputs = new ArrayList<>();
@OneToMany(mappedBy = "taskModel", cascade = CascadeType.ALL)
private List<TaskOutPort> taskOutPorts = new ArrayList<>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public ProcessModel getParentProcess() {
return parentProcess;
}
public void setParentProcess(ProcessModel parentProcess) {
this.parentProcess = parentProcess;
}
public long getCreationTime() {
return creationTime;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public long getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(long lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public List<TaskStatus> getTaskStatuses() {
return taskStatuses;
}
public void setTaskStatuses(List<TaskStatus> taskStatuses) {
this.taskStatuses = taskStatuses;
}
public String getTaskDetail() {
return taskDetail;
}
public void setTaskDetail(String taskDetail) {
this.taskDetail = taskDetail;
}
public List<ErrorModel> getTaskErrors() {
return taskErrors;
}
public void setTaskErrors(List<ErrorModel> taskErrors) {
this.taskErrors = taskErrors;
}
public List<JobModel> getJobs() {
return jobs;
}
public void setJobs(List<JobModel> jobs) {
this.jobs = jobs;
}
public List<TaskInput> getTaskInputs() {
return taskInputs;
}
public TaskModel setTaskInputs(List<TaskInput> taskInputs) {
this.taskInputs = taskInputs;
return this;
}
public List<TaskOutput> getTaskOutputs() {
return taskOutputs;
}
public TaskModel setTaskOutputs(List<TaskOutput> taskOutputs) {
this.taskOutputs = taskOutputs;
return this;
}
public TaskModelType getTaskType() {
return taskType;
}
public TaskModel setTaskType(TaskModelType taskType) {
this.taskType = taskType;
return this;
}
public boolean isStartingTask() {
return startingTask;
}
public TaskModel setStartingTask(boolean startingTask) {
this.startingTask = startingTask;
return this;
}
public boolean isStoppingTask() {
return stoppingTask;
}
public TaskModel setStoppingTask(boolean stoppingTask) {
this.stoppingTask = stoppingTask;
return this;
}
public int getOrderIndex() {
return orderIndex;
}
public TaskModel setOrderIndex(int orderIndex) {
this.orderIndex = orderIndex;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TaskOutPort> getTaskOutPorts() {
return taskOutPorts;
}
public void setTaskOutPorts(List<TaskOutPort> taskOutPorts) {
this.taskOutPorts = taskOutPorts;
}
public int getReferenceId() {
return referenceId;
}
public TaskModel setReferenceId(int referenceId) {
this.referenceId = referenceId;
return this;
}
}
| 8,796 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskOutPort.java | package org.apache.airavata.k8s.api.server.model.task;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class TaskOutPort {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int referenceId;
@ManyToOne
private TaskModel taskModel;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getReferenceId() {
return referenceId;
}
public TaskOutPort setReferenceId(int referenceId) {
this.referenceId = referenceId;
return this;
}
public TaskModel getTaskModel() {
return taskModel;
}
public void setTaskModel(TaskModel taskModel) {
this.taskModel = taskModel;
}
}
| 8,797 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/TaskOutput.java | package org.apache.airavata.k8s.api.server.model.task;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class TaskOutput {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "TASK_OUTPUT_NAME")
private String name;
@Column(name = "TASK_OUTPUT_VALUE")
private String value;
@Column(name = "TASK_OUTPUT_TYPE")
private String type;
@Column(name = "EXPORT_TO")
private String exportTo;
@ManyToOne
private TaskModel taskModel;
public long getId() {
return id;
}
public TaskOutput setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public TaskOutput setName(String name) {
this.name = name;
return this;
}
public String getValue() {
return value;
}
public TaskOutput setValue(String value) {
this.value = value;
return this;
}
public String getType() {
return type;
}
public TaskOutput setType(String type) {
this.type = type;
return this;
}
public String getExportTo() {
return exportTo;
}
public TaskOutput setExportTo(String exportTo) {
this.exportTo = exportTo;
return this;
}
public TaskModel getTaskModel() {
return taskModel;
}
public TaskOutput setTaskModel(TaskModel taskModel) {
this.taskModel = taskModel;
return this;
}
}
| 8,798 |
0 | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task | Create_ds/airavata-sandbox/airavata-kubernetes/modules/microservices/api-server/src/main/java/org/apache/airavata/k8s/api/server/model/task/type/TaskInputType.java | package org.apache.airavata.k8s.api.server.model.task.type;
import javax.persistence.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Entity
public class TaskInputType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String type;
private String defaultValue;
@ManyToOne
private TaskModelType taskModelType;
public long getId() {
return id;
}
public TaskInputType setId(long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public TaskInputType setName(String name) {
this.name = name;
return this;
}
public String getType() {
return type;
}
public TaskInputType setType(String type) {
this.type = type;
return this;
}
public String getDefaultValue() {
return defaultValue;
}
public TaskInputType setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public TaskModelType getTaskModelType() {
return taskModelType;
}
public TaskInputType setTaskModelType(TaskModelType taskModelType) {
this.taskModelType = taskModelType;
return this;
}
}
| 8,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.