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/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ExpCatParentDataType.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.registry.cpi;
public enum ExpCatParentDataType {
APPLiCATION_CATALOG,
GROUP,
USER,
PROJECT,
EXPERIMENT,
GATEWAY,
NOTIFICATION,
QUEUE_STATUS
}
| 1,100 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/AppCatalog.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.registry.cpi;
public interface AppCatalog {
/**
* Get ComputeResource interface
* @return ComputeResource interface
*/
ComputeResource getComputeResource() throws AppCatalogException;
/**
* Get StorageResource interface
* @return StorageResource interface
*/
StorageResource getStorageResource() throws AppCatalogException;
/**
* Get application interface
* @return application interface
*/
ApplicationInterface getApplicationInterface() throws AppCatalogException;
/**
* Get application deployment interface
* @return application deployment interface
*/
ApplicationDeployment getApplicationDeployment() throws AppCatalogException;
/**
* Get Gateway profile interface
* @return Gateway profile interface
* @throws AppCatalogException
*/
GwyResourceProfile getGatewayProfile() throws AppCatalogException;
/**
* Get Gateway profile interface
* @return User Resource profile interface
* @throws AppCatalogException
*/
UsrResourceProfile getUserResourceProfile() throws AppCatalogException;
/**
* Get workflow catalog interface
* @return workflow catalog interface
* @throws AppCatalogException
*/
WorkflowCatalog getWorkflowCatalog() throws AppCatalogException;
}
| 1,101 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ComputeResource.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.registry.cpi;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.data.movement.*;
import org.apache.airavata.model.data.movement.DMType;
import java.util.List;
import java.util.Map;
public interface ComputeResource {
/**
* This function will add a compute resource description to the database
* @param description compute resource description
* @return unique resource ID generated by airavata
*/
String addComputeResource (ComputeResourceDescription description) throws AppCatalogException;
/**
* This method will update compute resource
* @param computeResourceId unique compute resource id
* @param updatedComputeResource updated compute resource
*/
void updateComputeResource (String computeResourceId, ComputeResourceDescription updatedComputeResource) throws AppCatalogException;
/**
* This function will add a SSHJobSubmission to the database
* @param sshJobSubmission sshJobSubmission object
* @return unique submission ID generated by airavata
*/
String addSSHJobSubmission (SSHJobSubmission sshJobSubmission) throws AppCatalogException;
/**
* This function will add a SSHJobSubmission to the database
* @param sshJobSubmission sshJobSubmission object
* @return unique submission ID generated by airavata
*/
String addCloudJobSubmission (CloudJobSubmission sshJobSubmission) throws AppCatalogException;
String addResourceJobManager(ResourceJobManager resourceJobManager) throws AppCatalogException;
void updateResourceJobManager (String resourceJobManagerId, ResourceJobManager updatedResourceJobManager) throws AppCatalogException;
ResourceJobManager getResourceJobManager (String resourceJobManagerId) throws AppCatalogException;
void deleteResourceJobManager (String resourceJobManagerId) throws AppCatalogException;
/**
* This will add a SSHJobSubmission protocol to the database
* @param computeResourceId compute resource id
*/
String addJobSubmissionProtocol(String computeResourceId, JobSubmissionInterface jobSubmissionInterface) throws AppCatalogException;
String addLocalJobSubmission (LOCALSubmission localSubmission) throws AppCatalogException;
/**
* This method will add a GlobusJobSubmission to the database
* @param globusJobSubmission GSISSHJobSubmission object
* @return uniquely generated submission id
*/
String addGlobusJobSubmission (GlobusJobSubmission globusJobSubmission) throws AppCatalogException;
/**
* This method will add a UNICOREJobSubmission to the database
* @param unicoreJobSubmission
* @return uniquely generated submission id
*/
String addUNICOREJobSubmission (UnicoreJobSubmission unicoreJobSubmission) throws AppCatalogException;
String addLocalDataMovement (LOCALDataMovement localDataMovement) throws AppCatalogException;
/**
* This method will add a SCPData movement to the database
* @param scpDataMovement SCPData movement object
* @return uniquely generated data move id
*/
String addScpDataMovement (SCPDataMovement scpDataMovement) throws AppCatalogException;
String addUnicoreDataMovement (UnicoreDataMovement unicoreDataMovement) throws AppCatalogException;
/**
* This will add a SCPDataMovement protocol to the database
* @param resourceId compute resource id
*/
String addDataMovementProtocol (String resourceId, DMType dmType, DataMovementInterface dataMovementInterface) throws AppCatalogException;
/**
* This method will add a GridFTP Data movement to the database
* @param gridFTPDataMovement GridFTP Data movement object
* @return uniquely generated data move id
*/
String addGridFTPDataMovement (GridFTPDataMovement gridFTPDataMovement) throws AppCatalogException;
/**
* This method will retrieve compute resource object on given resource id
* @param resourceId unique resource id
* @return ComputeResource object
*/
ComputeResourceDescription getComputeResource (String resourceId) throws AppCatalogException;
/**
* This method will return a list of computeResource descriptions according to given search criteria
* @param filters map should be provided as the field name and it's value
* @return list of compute resources
*/
List<ComputeResourceDescription> getComputeResourceList (Map<String, String> filters) throws AppCatalogException;
/**
* This method will retrieve all the compute resources
* @return list of compute resources
* @throws AppCatalogException
*/
List<ComputeResourceDescription> getAllComputeResourceList () throws AppCatalogException;
/**
* This method will retrieve all the compute resource id with it's name
* @return map of compute resource ids + name
* @throws AppCatalogException
*/
Map<String, String> getAllComputeResourceIdList () throws AppCatalogException;
/**
* This method will retrieve all the enabled compute resource id with it's name
* @return
* @throws AppCatalogException
*/
Map<String, String> getAvailableComputeResourceIdList() throws AppCatalogException;
// /**
// * This method will retrieve GlobusJobSubmission object
// * @param submissionId unique submission id
// * @return GlobusJobSubmission object
// */
// GlobusJobSubmission getGlobusJobSubmission (String submissionId) throws AppCatalogException;
//
// /**
// * This method will return a list of GlobusJobSubmission objects according to given search criteria
// * @param filters map should be provided as the field name and it's value
// * @return list of GlobusJobSubmission objects
// */
// List<GlobusJobSubmission> getGlobusJobSubmissionList (Map<String, String> filters) throws AppCatalogException;
/**
* This method will retrieve GSISSHJobSubmission object
* @param submissionId unique submission id
* @return GSISSHSubmission object
*/
SSHJobSubmission getSSHJobSubmission (String submissionId) throws AppCatalogException;
/**
* This method will retrieve UnicoreJobSubmission object
* @param submissionId unique submission id
* @return UnicoreSubmission object
*/
UnicoreJobSubmission getUNICOREJobSubmission (String submissionId) throws AppCatalogException;
UnicoreDataMovement getUNICOREDataMovement (String dataMovementId) throws AppCatalogException;
/**
* This method will retrieve GSISSHJobSubmission object
* @param submissionId unique submission id
* @return GSISSHSubmission object
*/
CloudJobSubmission getCloudJobSubmission (String submissionId) throws AppCatalogException;
// /**
// * This method will return a list of GSISSHSubmission objects according to given search criteria
// * @param filters map should be provided as the field name and it's value
// * @return list of GSISSHSubmission objects
// */
// List<SSHJobSubmission> getSSHJobSubmissionList (Map<String, String> filters) throws AppCatalogException;
/**
* This method will retrieve SCP Data movement object
* @param dataMoveId unique data move id
* @return SCPDataMovement object
*/
SCPDataMovement getSCPDataMovement (String dataMoveId) throws AppCatalogException;
// /**
// * This method will return a list of SCPDataMovement objects according to given search criteria
// * @param filters map should be provided as the field name and it's value
// * @return list of SCPDataMovement objects
// */
// List<SCPDataMovement> getSCPDataMovementList (Map<String, String> filters) throws AppCatalogException;
/**
* This method will retrieve GridFTPDataMovement object
* @param dataMoveId unique data move id
* @return GridFTPDataMovement object
*/
GridFTPDataMovement getGridFTPDataMovement (String dataMoveId) throws AppCatalogException;
// /**
// * This method will return a list of GridFTPDataMovement objects according to given search criteria
// * @param filters map should be provided as the field name and it's value
// * @return list of GridFTPDataMovement objects
// */
// List<GridFTPDataMovement> getGridFTPDataMovementList (Map<String, String> filters) throws AppCatalogException;
/**
* This method will check whether the given resource already exists in the system
* @param resourceId unique resource id
* @return true or false
*/
boolean isComputeResourceExists (String resourceId) throws AppCatalogException;
/**
* This method will remove given resource from the system
* @param resourceId unique resource id
*/
void removeComputeResource (String resourceId) throws AppCatalogException;
/**
* This method will remove job submission interface
* @param jobSubmissionInterfaceId unique job submission interface id
* @throws AppCatalogException
*/
void removeJobSubmissionInterface(String computeResourceId, String jobSubmissionInterfaceId) throws AppCatalogException;
/**
* This method will remove data movement interface
* @param dataMovementInterfaceId unique data movement id
* @throws AppCatalogException
*/
void removeDataMovementInterface(String computeResourceId, String dataMovementInterfaceId) throws AppCatalogException;
void removeBatchQueue(String computeResourceId, String queueName) throws AppCatalogException;
LOCALSubmission getLocalJobSubmission(String submissionId) throws AppCatalogException;
LOCALDataMovement getLocalDataMovement(String datamovementId) throws AppCatalogException;
}
| 1,102 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ExpCatChildDataType.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.registry.cpi;
public enum ExpCatChildDataType {
EXPERIMENT_INPUT,
EXPERIMENT_OUTPUT,
EXPERIMENT_STATUS,
EXPERIMENT_ERROR,
USER_CONFIGURATION_DATA,
PROCESS,
PROCESS_INPUT,
PROCESS_OUTPUT,
PROCESS_STATUS,
PROCESS_ERROR,
PROCESS_RESOURCE_SCHEDULE,
TASK,
TASK_STATUS,
TASK_ERROR,
JOB,
JOB_STATUS,
PROCESS_WORKFLOW
} | 1,103 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/RegistryException.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.registry.cpi;
public class RegistryException extends Exception {
private static final long serialVersionUID = -2849422320139467602L;
public RegistryException(Throwable e) {
super(e);
}
public RegistryException(String message) {
super(message, null);
}
public RegistryException(String message, Throwable e) {
super(message, e);
}
}
| 1,104 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ResultOrderType.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.registry.cpi;/*
*
* 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.
*
*/
/**
* Enum to specify the order type for a specific column when
* retrieving results
*/
public enum ResultOrderType {
ASC,
DESC
}
| 1,105 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ReplicaCatalogException.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.registry.cpi;
public class ReplicaCatalogException extends RegistryException{
public ReplicaCatalogException(Throwable e) {
super(e);
}
public ReplicaCatalogException(String message) {
super(message, null);
}
public ReplicaCatalogException(String message, Throwable e) {
super(message, e);
}
}
| 1,106 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/DataReplicaLocationInterface.java | package org.apache.airavata.registry.cpi;
import org.apache.airavata.model.data.replica.DataReplicaLocationModel;
import java.util.List;
public interface DataReplicaLocationInterface {
String registerReplicaLocation(DataReplicaLocationModel dataReplicaLocationModel) throws ReplicaCatalogException;
boolean updateReplicaLocation(DataReplicaLocationModel dataReplicaLocationModel) throws ReplicaCatalogException;
DataReplicaLocationModel getReplicaLocation(String replicaId) throws ReplicaCatalogException;
List<DataReplicaLocationModel> getAllReplicaLocations(String productUri) throws ReplicaCatalogException;
boolean removeReplicaLocation(String replicaId) throws ReplicaCatalogException;
}
| 1,107 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/ExperimentCatalogException.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.registry.cpi;
public class ExperimentCatalogException extends Exception {
private static final long serialVersionUID = -2849422320139467602L;
public ExperimentCatalogException(Throwable e) {
super(e);
}
public ExperimentCatalogException(String message) {
super(message, null);
}
public ExperimentCatalogException(String message, Throwable e) {
super(message, e);
}
}
| 1,108 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/Registry.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.registry.cpi;
public interface Registry {
public ExperimentCatalog getExperimentCatalog() throws RegistryException;
public ExperimentCatalog getExperimentCatalog(String gatewayId, String username, String password) throws RegistryException;
public AppCatalog getAppCatalog() throws RegistryException;
public ReplicaCatalog getReplicaCatalog() throws RegistryException;
}
| 1,109 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/utils/StatusType.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.registry.cpi.utils;
public enum StatusType {
EXPERIMENT,
WORKFLOW_NODE,
TASK,
JOB,
DATA_TRANSFER,
APPLICATION
}
| 1,110 |
0 | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi | Create_ds/airavata/modules/registry/registry-cpi/src/main/java/org/apache/airavata/registry/cpi/utils/Constants.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.registry.cpi.utils;
public class Constants {
public final class FieldConstants {
public final class ProjectConstants {
public static final String PROJECT_ID = "projectID";
public static final String GATEWAY_ID = "gateway_id";
public static final String OWNER = "owner";
public static final String PROJECT_NAME = "name";
public static final String DESCRIPTION = "description";
public static final String CREATION_TIME = "creationTime";
}
public final class ExperimentConstants {
public static final String EXPERIMENT_ID = "experimentId";
public static final String PROJECT_ID = "projectId";
public static final String GATEWAY_ID = "gatewayId";
public static final String EXPERIMENT_TYPE = "experimentType";
public static final String USER_NAME = "userName";
public static final String EXPERIMENT_NAME = "experimentName";
public static final String CREATION_TIME = "creationTime";
public static final String DESCRIPTION = "description";
public static final String EXECUTION_ID = "executionId";
public static final String GATEWAY_EXECUTION_ID = "gatewayExecutionId";
public static final String ENABLE_EMAIL_NOTIFICATION = "enableEmailNotification";
public static final String EMAIL_ADDRESSES = "emailAddresses";
public static final String EXPERIMENT_INPUTS = "experimentInputs";
public static final String EXPERIMENT_OUTPUTS = "experimentOutputs";
public static final String EXPERIMENT_STATUS = "experimentStatus";
public static final String EXPERIMENT_ERRORS = "experimentErrors";
public static final String USER_CONFIGURATION_DATA = "userConfigurationData";
public static final String FROM_DATE = "fromDate";
public static final String TO_DATE = "toDate";
public static final String RESOURCE_HOST_ID = "resourceHostId";
}
public final class UserConfigurationDataConstants {
public static final String EXPERIMENT_ID = "experimentId";
public static final String AIRAVATA_AUTO_SCHEDULE = "airavataAutoSchedule";
public static final String OVERRIDE_MANUAL_PARAMS = "overrideManualScheduledParams";
public static final String SHARE_EXP = "shareExperimentPublicly";
public static final String COMPUTATIONAL_RESOURCE_SCHEDULING = "computationalResourceScheduling";
}
public final class ProcessConstants {
public static final String EXPERIMENT_ID = "experimentId";
public static final String PROCESS_ID = "processId";
public static final String PROCESS_STATUS = "processStatus";
public static final String PROCESS_ERROR = "processError";
public static final String PROCESS_INPUTS = "processInputs";
public static final String PROCESS_OUTPUTS = "processOutputs";
public static final String PROCESS_RESOURCE_SCHEDULE = "processResourceSchedule";
public static final String PROCESS_WORKFLOW = "processWorkflow";
}
public final class TaskConstants {
public static final String PARENT_PROCESS_ID = "parentProcessId";
public static final String TASK_ID = "taskId";
public static final String TASK_STATUS = "taskStatus";
public static final String TASK_ERROR = "taskError";
}
public final class JobConstants {
public static final String JOB_ID = "jobId";
public static final String PROCESS_ID = "processId";
public static final String TASK_ID = "taskId";
public static final String JOB_STATUS = "taskStatus";
}
}
}
| 1,111 |
0 | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform/monitoring/MonitoringServer.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.patform.monitoring;
import io.prometheus.client.exporter.HTTPServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class MonitoringServer {
private final static Logger logger = LoggerFactory.getLogger(MonitoringServer.class);
private String host;
private int port;
private HTTPServer httpServer;
public MonitoringServer(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws IOException {
try {
logger.info("Starting the monitoring server");
httpServer = new HTTPServer(host, port, true);
} catch (IOException e) {
logger.error("Failed to start the monitoring server on host {} na port {}", host, port, e);
}
}
public void stop() {
if (httpServer != null) {
logger.info("Stopping the monitor server");
httpServer.stop();
}
}
}
| 1,112 |
0 | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform/monitoring/GaugeMonitor.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.patform.monitoring;
import io.prometheus.client.Gauge;
public class GaugeMonitor {
private Gauge gauge;
public GaugeMonitor(String monitorName) {
gauge = Gauge.build().name(monitorName).help(monitorName).register();
}
public void inc() {
gauge.inc();
}
public void inc(double amount) {
gauge.inc(amount);
}
public void dec() {
gauge.dec();
}
public void dec(double amount) {
gauge.dec(amount);
}
}
| 1,113 |
0 | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform | Create_ds/airavata/modules/platform-monitoring/src/main/java/org/apache/airavata/patform/monitoring/CountMonitor.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.patform.monitoring;
import io.prometheus.client.Counter;
public class CountMonitor {
private Counter counter;
public CountMonitor(String monitorName) {
counter = Counter.build().name(monitorName).help(monitorName).register();
}
public CountMonitor(String monitorName, String... labelNames) {
counter = Counter.build().name(monitorName).help(monitorName).labelNames(labelNames).register();
}
public void inc() {
counter.inc();
}
public void inc(String... labelValues) {
counter.labels(labelValues).inc();
}
public void inc(double amount) {
counter.inc(amount);
}
public void inc(double amount, String... labelValues) {
counter.labels(labelValues).inc(amount);
}
}
| 1,114 |
0 | Create_ds/airavata/modules/db-event-manager/src/test | Create_ds/airavata/modules/db-event-manager/src/test/java/Test.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.
*/
/**
* Created by Ajinkya on 3/1/17.
*/
public class Test {
}
| 1,115 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/DBEventManagerRunner.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.db.event.manager;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.db.event.manager.messaging.DBEventManagerMessagingFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by Ajinkya on 3/29/17.
*/
public class DBEventManagerRunner implements IServer {
private static final Logger log = LogManager.getLogger(DBEventManagerRunner.class);
private static final String SERVER_NAME = "DB Event Manager";
private static final String SERVER_VERSION = "1.0";
private ServerStatus status;
/**
* Start required messaging utilities
*/
private void startDBEventManagerRunner() {
try{
log.info("Starting DB Event manager publisher");
DBEventManagerMessagingFactory.getDBEventPublisher();
log.debug("DB Event manager publisher is running");
log.info("Starting DB Event manager subscriber");
DBEventManagerMessagingFactory.getDBEventSubscriber();
log.debug("DB Event manager subscriber is listening");
} catch (AiravataException e) {
log.error("Error starting DB Event Manager.", e);
}
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
try {
Runnable runner = new Runnable() {
@Override
public void run() {
DBEventManagerRunner dBEventManagerRunner = new DBEventManagerRunner();
dBEventManagerRunner.startDBEventManagerRunner();
}
};
// start the worker thread
log.info("Starting the DB Event Manager runner.");
new Thread(runner).start();
} catch (Exception ex) {
log.error("Something went wrong with the DB Event Manager runner. Error: " + ex, ex);
}
}
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
@Override
public void start() throws Exception {
try {
Runnable runner = new Runnable() {
@Override
public void run() {
DBEventManagerRunner dBEventManagerRunner = new DBEventManagerRunner();
dBEventManagerRunner.startDBEventManagerRunner();
}
};
// start the worker thread
log.info("Starting the DB Event Manager runner.");
new Thread(runner).start();
setStatus(ServerStatus.STARTED);
} catch (Exception ex) {
log.error("Something went wrong with the DB Event Manager runner. Error: " + ex, ex);
setStatus(ServerStatus.FAILED);
}
}
@Override
public void stop() throws Exception {
// TODO: implement stopping the DBEventManager
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
private void setStatus(ServerStatus stat){
status=stat;
status.updateTime();
}
}
| 1,116 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/utils/DbEventManagerZkUtils.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.db.event.manager.utils;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.ServerSettings;
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;
import java.util.List;
/**
* Created by goshenoy on 3/21/17.
*/
public class DbEventManagerZkUtils {
private static final Logger logger = LoggerFactory.getLogger(DbEventManagerZkUtils.class);
private static CuratorFramework curatorClient;
/**
* Get curatorFramework instance
* @return
* @throws ApplicationSettingsException
*/
public static CuratorFramework getCuratorClient() throws ApplicationSettingsException {
if (curatorClient == null) {
synchronized (DbEventManagerZkUtils.class) {
if (curatorClient == null) {
String connectionSting = ServerSettings.getZookeeperConnection();
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy);
}
}
}
return curatorClient;
}
/**
* Create Zk node for db event manager
* @param curatorClient
* @param publisherNode
* @param subscriberNode
* @throws Exception
*/
public static void createDBEventMgrZkNode(CuratorFramework curatorClient, String publisherNode, String subscriberNode) throws Exception {
// get pub,sub queue names
// construct ZK paths for pub,sub
String publisherZkPath = ZKPaths.makePath(Constants.DB_EVENT_MGR_ZK_PATH, publisherNode);
String subscriberZkPath = ZKPaths.makePath(publisherZkPath, subscriberNode);
// construct byte-data(s) for pub, sub
byte[] publisherZkData = publisherNode.getBytes();
byte[] subscriberZkData = subscriberNode.getBytes();
// create zkNode: "/db-event-mgr/pubqueuename/subqueueename"
logger.debug("Creating Zk node for db-event-mgr: " + subscriberZkPath);
ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), subscriberZkPath);
// set zkNode data for pub,sub
curatorClient.setData().withVersion(-1 ).forPath(publisherZkPath, publisherZkData);
curatorClient.setData().withVersion(-1 ).forPath(subscriberZkPath, subscriberZkData);
}
/**
* Get list of subscribers for given publisher
* @param curatorClient
* @param publisherNode
* @return
* @throws Exception
*/
public static List<String> getSubscribersForPublisher(CuratorFramework curatorClient, String publisherNode) throws Exception {
// construct ZK path for pub
String publisherZkPath = ZKPaths.makePath(Constants.DB_EVENT_MGR_ZK_PATH, publisherNode);
// get children-list for pub
List<String> subscriberList = curatorClient.getChildren().forPath(publisherZkPath);
return subscriberList;
}
// public static void main(String[] args) {
// String connectionString = "localhost:2181";
// String userProfileService = DBEventManagerConstants.DBEventService.USER_PROFILE.toString();
// String sharingService = DBEventManagerConstants.DBEventService.SHARING.toString();
// String registryService = DBEventManagerConstants.DBEventService.REGISTRY.toString();
//
// RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
//
// CuratorFramework curatorClient = CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
// curatorClient.start();
// try {
// DbEventManagerZkUtils.createDBEventMgrZkNode(curatorClient, userProfileService, sharingService);
// DbEventManagerZkUtils.createDBEventMgrZkNode(curatorClient, userProfileService, registryService);
// System.out.println(DbEventManagerZkUtils.getSubscribersForPublisher(curatorClient, userProfileService));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// }
}
| 1,117 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/utils/Constants.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.db.event.manager.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Ajinkya on 3/1/17.
*/
public class Constants {
public static final String DB_EVENT_MGR_ZK_PATH = "db-event-mgr";
}
| 1,118 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/messaging/DBEventManagerMessagingFactory.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.db.event.manager.messaging;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.DBEventService;
import org.apache.airavata.db.event.manager.messaging.impl.DBEventMessageHandler;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by Ajinkya on 3/1/17.
*/
public class DBEventManagerMessagingFactory {
private final static Logger log = LoggerFactory.getLogger(DBEventManagerMessagingFactory.class);
private static Subscriber dbEventSubscriber;
private static Publisher dbEventPublisher;
/**
* Get DB Event subscriber
* @return
* @throws AiravataException
*/
public static Subscriber getDBEventSubscriber() throws AiravataException {
if(null == dbEventSubscriber){
synchronized (DBEventManagerMessagingFactory.class){
if(null == dbEventSubscriber){
log.info("Creating DB Event subscriber.....");
dbEventSubscriber = MessagingFactory.getDBEventSubscriber(new DBEventMessageHandler(), DBEventService.DB_EVENT.toString());
log.info("DB Event subscriber created");
}
}
}
return dbEventSubscriber;
}
public static Publisher getDBEventPublisher() throws AiravataException {
if(null == dbEventPublisher){
synchronized (DBEventManagerMessagingFactory.class){
if(null == dbEventPublisher){
log.info("Creating DB Event publisher.....");
dbEventPublisher = MessagingFactory.getDBEventPublisher();
log.info("DB Event publisher created");
}
}
}
return dbEventPublisher;
}
}
| 1,119 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/messaging/DBEventManagerException.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.db.event.manager.messaging;
/**
* Created by Ajinkya on 3/14/17.
*/
public class DBEventManagerException extends Exception {
private static final long serialVersionUID = -2849422320139467602L;
public DBEventManagerException(Throwable e) {
super(e);
}
public DBEventManagerException(String message) {
super(message, null);
}
public DBEventManagerException(String message, Throwable e) {
super(message, e);
}
}
| 1,120 |
0 | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/messaging | Create_ds/airavata/modules/db-event-manager/src/main/java/org/apache/airavata/db/event/manager/messaging/impl/DBEventMessageHandler.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.db.event.manager.messaging.impl;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.db.event.manager.messaging.DBEventManagerException;
import org.apache.airavata.db.event.manager.messaging.DBEventManagerMessagingFactory;
import org.apache.airavata.db.event.manager.utils.DbEventManagerZkUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.model.dbevent.DBEventMessage;
import org.apache.airavata.model.dbevent.DBEventMessageContext;
import org.apache.airavata.model.dbevent.DBEventType;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by Ajinkya on 3/14/17.
*/
public class DBEventMessageHandler implements MessageHandler {
private final static Logger log = LoggerFactory.getLogger(DBEventMessageHandler.class);
private CuratorFramework curatorClient;
public DBEventMessageHandler() throws ApplicationSettingsException {
startCuratorClient();
}
private void startCuratorClient() throws ApplicationSettingsException {
curatorClient = DbEventManagerZkUtils.getCuratorClient();
curatorClient.start();
}
@Override
public void onMessage(MessageContext messageContext) {
log.info("Incoming DB event message. Message Id : " + messageContext.getMessageId());
try {
byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent());
DBEventMessage dbEventMessage = new DBEventMessage();
ThriftUtils.createThriftFromBytes(bytes, dbEventMessage);
DBEventMessageContext dBEventMessageContext = dbEventMessage.getMessageContext();
switch (dbEventMessage.getDbEventType()){
case SUBSCRIBER:
log.info("Registering " + dBEventMessageContext.getSubscriber().getSubscriberService() + " subscriber for " + dbEventMessage.getPublisherService());
DbEventManagerZkUtils.createDBEventMgrZkNode(curatorClient, dbEventMessage.getPublisherService(), dBEventMessageContext.getSubscriber().getSubscriberService());
break;
case PUBLISHER:
List<String> subscribers = DbEventManagerZkUtils.getSubscribersForPublisher(curatorClient, dbEventMessage.getPublisherService());
if(subscribers.isEmpty()){
log.error("No Subscribers registered for the service");
throw new DBEventManagerException("No Subscribers registered for the service");
}
String routingKey = getRoutingKeyFromList(subscribers);
log.info("Publishing " + dbEventMessage.getPublisherService() + " db event to " + subscribers.toString());
MessageContext messageCtx = new MessageContext(dbEventMessage, MessageType.DB_EVENT, "", "");
messageCtx.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
DBEventManagerMessagingFactory.getDBEventPublisher().publish(messageCtx, routingKey);
break;
}
log.info("Sending ack. Message Delivery Tag : " + messageContext.getDeliveryTag());
DBEventManagerMessagingFactory.getDBEventSubscriber().sendAck(messageContext.getDeliveryTag());
} catch (Exception e) {
log.error("Error processing message.", e);
}
}
private String getRoutingKeyFromList(final List<String> subscribers){
StringBuilder sb = new StringBuilder();
Collections.sort(subscribers);
for(String subscriber : subscribers){
sb.append(subscriber).append(DBEventManagerConstants.ROUTING_KEY_SEPARATOR);
}
return sb.substring(0, sb.length() - 1);
}
}
| 1,121 |
0 | Create_ds/airavata/modules/cluster-monitoring/src/main/java/org/apache/airavata/cluster | Create_ds/airavata/modules/cluster-monitoring/src/main/java/org/apache/airavata/cluster/monitoring/ClusterStatusMonitorJob.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.cluster.monitoring;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.credential.store.cpi.CredentialStoreService;
import org.apache.airavata.model.credential.store.SSHCredential;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionInterface;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference;
import org.apache.airavata.model.status.QueueStatusModel;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ClusterStatusMonitorJob implements Job {
private final static Logger logger = LoggerFactory.getLogger(ClusterStatusMonitorJob.class);
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try{
String superTenantGatewayId = ServerSettings.getSuperTenantGatewayId();
RegistryService.Client registryClient = getRegistryClient();
List<ComputeResourceProfile> computeResourceProfiles = new ArrayList<>();
List<ComputeResourcePreference> computeResourcePreferences = null;
try{
computeResourcePreferences = registryClient.getAllGatewayComputeResourcePreferences(superTenantGatewayId);
}catch (Exception ex){
logger.warn("Could not find super tenant compute resources preferences for cluster status monitoring...");
}
if (computeResourcePreferences != null && computeResourcePreferences.size() > 0) {
computeResourcePreferences.stream().forEach(p -> {
try {
String computeResourceId = p.getComputeResourceId();
String credentialStoreToken = p.getResourceSpecificCredentialStoreToken();
String loginUserName = p.getLoginUserName();
String hostName = null;
if (credentialStoreToken == null || credentialStoreToken.equals("")) {
credentialStoreToken = registryClient.getGatewayResourceProfile(superTenantGatewayId).getCredentialStoreToken();
}
int port = -1;
ArrayList queueNames = new ArrayList<>();
ComputeResourceDescription computeResourceDescription = registryClient.getComputeResource(computeResourceId);
hostName = computeResourceDescription.getHostName();
//FIXME This should come from compute resource description
port = 22;
computeResourceDescription.getBatchQueues().stream().forEach(q -> {
queueNames.add(q.getQueueName());
});
List<JobSubmissionInterface> jobSubmissionInterfaces = computeResourceDescription.getJobSubmissionInterfaces();
if (jobSubmissionInterfaces != null && jobSubmissionInterfaces.size() > 0) {
if (jobSubmissionInterfaces.get(0).getJobSubmissionProtocol().equals(JobSubmissionProtocol.SSH)) {
String resourceManagerType = registryClient.getSSHJobSubmission(jobSubmissionInterfaces.get(0)
.getJobSubmissionInterfaceId()).getResourceJobManager().getResourceJobManagerType().name();
ComputeResourceProfile computeResourceProfile = new ComputeResourceProfile(hostName,
loginUserName, port, credentialStoreToken, queueNames, resourceManagerType);
computeResourceProfiles.add(computeResourceProfile);
}
}
} catch (TException e) {
logger.error(e.getMessage());
}
});
}
ArrayList<QueueStatusModel> queueStatuses = new ArrayList<>();
for (ComputeResourceProfile computeResourceProfile : computeResourceProfiles) {
String userName = computeResourceProfile.getUserName();
String hostName = computeResourceProfile.getHostName();
int port = computeResourceProfile.getPort();
try {
JSch jsch = new JSch();
CredentialStoreService.Client credentialClient = getCredentialStoreClient();
SSHCredential sshCredential = credentialClient.getSSHCredential(computeResourceProfile.getCredentialStoreToken(), superTenantGatewayId);
jsch.addIdentity(hostName, sshCredential.getPrivateKey().getBytes(), sshCredential.getPublicKey().getBytes(), sshCredential.getPassphrase().getBytes());
Session session = jsch.getSession(userName, hostName, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
logger.debug("Connected to " + hostName);
session.connect();
for (String queue : computeResourceProfile.getQueueNames()) {
String command = "";
if (computeResourceProfile.getResourceManagerType().equals("SLURM"))
command = "sinfo -s -p " + queue + " -o \"%a %F\" | tail -1";
else if (computeResourceProfile.getResourceManagerType().equals("PBS"))
command = "qstat -Q " + queue + "| tail -1";
if (command.equals("")) {
logger.warn("No matching resource manager type found for " + computeResourceProfile.getResourceManagerType());
continue;
}
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
String result = "";
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
result += new String(tmp, 0, i);
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
logger.debug(hostName + " " + queue + " " + "exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
if (result != null && result.length() > 0) {
QueueStatusModel queueStatus = null;
if (computeResourceProfile.getResourceManagerType().equals("SLURM")) {
String[] sparts = result.split(" ");
boolean isUp = sparts[0].equalsIgnoreCase("up");
String knts = sparts[1];
sparts = knts.split("/");
int running = Integer.parseInt(sparts[0].trim());
int queued = Integer.parseInt(sparts[1].trim());
queueStatus = new QueueStatusModel(hostName, queue, isUp, running, queued, System.currentTimeMillis());
} else if (computeResourceProfile.getResourceManagerType().equals("PBS")) {
result = result.replaceAll("\\s+", " ");
String[] sparts = result.split(" ");
boolean isUp = sparts[3].equalsIgnoreCase("yes");
int running = Integer.parseInt(sparts[6].trim());
int queued = Integer.parseInt(sparts[5].trim());
queueStatus = new QueueStatusModel(hostName, queue, isUp, running, queued, System.currentTimeMillis());
}
if (queueStatus != null)
queueStatuses.add(queueStatus);
}
}
session.disconnect();
} catch (Exception ex) {
logger.error("Failed to get cluster status from " + computeResourceProfile.getHostName());
logger.error(ex.getMessage(), ex);
}
}
if(queueStatuses != null && queueStatuses.size() > 0){
registryClient.registerQueueStatuses(queueStatuses);
}
}catch (Exception e){
throw new JobExecutionException(e);
}
}
private static RegistryService.Client getRegistryClient() throws TTransportException, ApplicationSettingsException {
TTransport transport = new TSocket(ServerSettings.getRegistryServerHost(), Integer.parseInt(ServerSettings.getRegistryServerPort()));
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
RegistryService.Client registryClient = new RegistryService.Client(protocol);
return registryClient;
}
private static CredentialStoreService.Client getCredentialStoreClient() throws TTransportException, ApplicationSettingsException {
TTransport transport = new TSocket(ServerSettings.getCredentialStoreServerHost(), Integer.parseInt(ServerSettings.getCredentialStoreServerPort()));
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
CredentialStoreService.Client credentialServiceClient = new CredentialStoreService.Client(protocol);
return credentialServiceClient;
}
private static class ComputeResourceProfile {
private String hostName;
private String userName;
private int port;
private String credentialStoreToken;
private List<String> queueNames;
private String resourceManagerType;
public ComputeResourceProfile(String hostName, String userName, int port, String credentialStoreToken, List<String> queueNames, String resourceManagerType) {
this.hostName = hostName;
this.userName = userName;
this.port = port;
this.credentialStoreToken = credentialStoreToken;
this.queueNames = queueNames;
this.resourceManagerType = resourceManagerType;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getCredentialStoreToken() {
return credentialStoreToken;
}
public void setCredentialStoreToken(String credentialStoreToken) {
this.credentialStoreToken = credentialStoreToken;
}
public List<String> getQueueNames() {
return queueNames;
}
public void setQueueNames(List<String> queueNames) {
this.queueNames = queueNames;
}
public String getResourceManagerType() {
return resourceManagerType;
}
public void setResourceManagerType(String resourceManagerType) {
this.resourceManagerType = resourceManagerType;
}
}
} | 1,122 |
0 | Create_ds/airavata/modules/cluster-monitoring/src/main/java/org/apache/airavata/cluster | Create_ds/airavata/modules/cluster-monitoring/src/main/java/org/apache/airavata/cluster/monitoring/ClusterStatusMonitorJobScheduler.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.cluster.monitoring;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.*;
import static org.quartz.SimpleScheduleBuilder.*;
public class ClusterStatusMonitorJobScheduler {
private final static Logger logger = LoggerFactory.getLogger(ClusterStatusMonitorJobScheduler.class);
Scheduler scheduler;
public ClusterStatusMonitorJobScheduler() throws SchedulerException {
scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
}
public void scheduleClusterStatusMonitoring() throws SchedulerException, ApplicationSettingsException {
// define the job and tie it to our MyJob class
JobDetail job = newJob(ClusterStatusMonitorJob.class)
.withIdentity("cluster-status-monitoring", "airavata")
.build();
// Trigger the job to run now, and then repeat every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("cluster-status-monitoring-trigger", "airavata")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(Integer.parseInt(ServerSettings.getClusterStatusMonitoringRepeatTime()))
.repeatForever())
.build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
}
public static void main(String[] args) throws SchedulerException, ApplicationSettingsException {
ClusterStatusMonitorJobScheduler jobScheduler = new ClusterStatusMonitorJobScheduler();
jobScheduler.scheduleClusterStatusMonitoring();
}
} | 1,123 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/utils/Utils.java | package org.apache.airavata.metascheduler.core.utils;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessIdentifier;
import org.apache.airavata.model.messaging.event.ProcessStatusChangeEvent;
import org.apache.airavata.model.status.ProcessState;
import org.apache.airavata.model.status.ProcessStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.thrift.TException;
/**
* This class contains all utility methods across scheduler sub projects
*/
public class Utils {
private static ThriftClientPool<RegistryService.Client> registryClientPool;
private static Publisher statusPublisher;
/**
* Provides registry client to access databases
*
* @return RegistryService.Client
*/
public static synchronized ThriftClientPool<RegistryService.Client> getRegistryServiceClientPool() {
if (registryClientPool != null) {
return registryClientPool;
}
try {
// final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
// final String serverHost = ServerSettings.getRegistryServerHost();
registryClientPool = new ThriftClientPool<RegistryService.Client>(
tProtocol -> new RegistryService.Client(tProtocol),
Utils.<RegistryService.Client>createGenericObjectPoolConfig(),
ServerSettings.getRegistryServerHost(),
Integer.parseInt(ServerSettings.getRegistryServerPort()));
return registryClientPool;
} catch (Exception e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
private static <T> GenericObjectPoolConfig<T> createGenericObjectPoolConfig() {
GenericObjectPoolConfig<T> poolConfig = new GenericObjectPoolConfig<T>();
poolConfig.setMaxTotal(100);
poolConfig.setMinIdle(5);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestWhileIdle(true);
// must set timeBetweenEvictionRunsMillis since eviction doesn't run unless that is positive
poolConfig.setTimeBetweenEvictionRunsMillis(5L * 60L * 1000L);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setMaxWaitMillis(3000);
return poolConfig;
}
public static void saveAndPublishProcessStatus(ProcessState processState, String processId,
String experimentId, String gatewayId)
throws RegistryServiceException, TException, AiravataException {
RegistryService.Client registryClient = null;
try {
registryClient = registryClientPool.getResource();
ProcessStatus processStatus = new ProcessStatus(processState);
processStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
registryClientPool.getResource().addProcessStatus(processStatus, processId);
ProcessIdentifier identifier = new ProcessIdentifier(processId, experimentId, gatewayId);
ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent(processState, identifier);
MessageContext msgCtx = new MessageContext(processStatusChangeEvent, MessageType.PROCESS,
AiravataUtils.getId(MessageType.PROCESS.name()), gatewayId);
msgCtx.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
getStatusPublisher().publish(msgCtx);
} catch (Exception ex){
if (registryClient != null) {
registryClientPool.returnBrokenResource(registryClient);
registryClient = null;
}
} finally {
if (registryClient != null) {
registryClientPool.returnResource(registryClient);
}
}
}
public static void updateProcessStatusAndPublishStatus(ProcessState processState, String processId,
String experimentId, String gatewayId)
throws RegistryServiceException, TException, AiravataException {
RegistryService.Client registryClient = null;
try {
ProcessStatus processStatus = new ProcessStatus(processState);
processStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
registryClientPool.getResource().updateProcessStatus(processStatus, processId);
ProcessIdentifier identifier = new ProcessIdentifier(processId, experimentId, gatewayId);
ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent(processState, identifier);
MessageContext msgCtx = new MessageContext(processStatusChangeEvent, MessageType.PROCESS,
AiravataUtils.getId(MessageType.PROCESS.name()), gatewayId);
msgCtx.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
getStatusPublisher().publish(msgCtx);
} catch (Exception ex) {
if (registryClient != null) {
registryClientPool.returnBrokenResource(registryClient);
registryClient = null;
}
} finally {
if (registryClient != null) {
registryClientPool.returnResource(registryClient);
}
}
}
public static synchronized Publisher getStatusPublisher() throws AiravataException {
if (statusPublisher == null) {
statusPublisher = MessagingFactory.getPublisher(Type.STATUS);
}
return statusPublisher;
}
}
| 1,124 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/api/ProcessScheduler.java | package org.apache.airavata.metascheduler.core.api;
import org.apache.airavata.model.process.ProcessModel;
import java.util.Optional;
/**
* Provides interfaces for Process related scheduling operations
*/
public interface ProcessScheduler {
/**
* This method checks experiment can be instantly scheduled to a computer resource,
* If it can be scheduled, Processes are updated with selected Scheduling resource otherwise all are
* moved to Queued state
* @param experimentId
* @return boolean
*/
boolean canLaunch(String experimentId);
/**
* This method can be used to reschedule a failed experiment.
* If experiment can be scheduled instantly, Processes are updated with scheduling resources, otherwise
* is moved to Queued state
* @param experimentId
* @return boolean
*/
boolean reschedule(String experimentId);
}
| 1,125 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/engine/DataAnalyzer.java | package org.apache.airavata.metascheduler.core.engine;
import org.quartz.Job;
public interface DataAnalyzer extends Job {
}
| 1,126 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/engine/ProcessScanner.java | package org.apache.airavata.metascheduler.core.engine;
import org.quartz.Job;
/**
* This class scans all queued processes and relaunch them based on
* activated rescheduling algorithm
*/
public interface ProcessScanner extends Job {
}
| 1,127 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/engine/ComputeResourceSelectionPolicy.java | package org.apache.airavata.metascheduler.core.engine;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import java.util.Optional;
/**
* This interface provides apis to implement for select compute resources
* from compute resource pool according to different selection strategies
*/
public interface ComputeResourceSelectionPolicy {
/**
* This interface implements compute resource selection
* @param experimentId
* @return Optional<ComputationalResourceSchedulingModel>
*/
Optional<ComputationalResourceSchedulingModel> selectComputeResource(String processId);
}
| 1,128 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core | Create_ds/airavata/modules/airavata-metascheduler/metascheduler-core/src/main/java/org/apache/airavata/metascheduler/core/engine/ReScheduler.java | package org.apache.airavata.metascheduler.core.engine;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.status.ProcessState;
/**
* This is the interface class for ReScheduling
* algorithm.
*/
public interface ReScheduler {
void reschedule(ProcessModel processModel, ProcessState processState);
}
| 1,129 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/utils/Constants.java | package org.apache.airavata.metascheduler.process.scheduling.utils;
public class Constants {
public static final String PROCESS_SCANNER_GROUP = "process.scanner.group";
public static final String PROCESS_SCANNER_TRIGGER = "prcoess.scanner.trigger";
public static final String PROCESS_SCANNER_JOB = "process.scanner.job";
}
| 1,130 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/api/ProcessSchedulerImpl.java | package org.apache.airavata.metascheduler.process.scheduling.api;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.api.ProcessScheduler;
import org.apache.airavata.metascheduler.core.engine.ComputeResourceSelectionPolicy;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.ProcessState;
import org.apache.airavata.model.status.ProcessStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* This class provides implementation of the ProcessSchedule Interface
*/
public class ProcessSchedulerImpl implements ProcessScheduler {
private static Logger LOGGER = LoggerFactory.getLogger(ProcessSchedulerImpl.class);
private ThriftClientPool<RegistryService.Client> registryClientPool;
public ProcessSchedulerImpl() {
try {
registryClientPool = Utils.getRegistryServiceClientPool();
} catch (Exception e) {
LOGGER.error("Error occurred while fetching registry client pool", e);
}
}
@Override
public boolean canLaunch(String experimentId) {
final RegistryService.Client registryClient = this.registryClientPool.getResource();
try {
List<ProcessModel> processModels = registryClient.getProcessList(experimentId);
ExperimentModel experiment = registryClient.getExperiment(experimentId);
boolean allProcessesScheduled = true;
String selectionPolicyClass = ServerSettings.getComputeResourceSelectionPolicyClass();
ComputeResourceSelectionPolicy policy = (ComputeResourceSelectionPolicy) Class.forName(selectionPolicyClass).newInstance();
for(ProcessModel processModel:processModels) {
ProcessStatus processStatus = registryClient.getProcessStatus(processModel.getProcessId());
if (processStatus.getState().equals(ProcessState.CREATED) || processStatus.getState().equals(ProcessState.VALIDATED)) {
Optional<ComputationalResourceSchedulingModel> computationalResourceSchedulingModel = policy.
selectComputeResource(processModel.getProcessId());
if (computationalResourceSchedulingModel.isPresent()) {
ComputationalResourceSchedulingModel resourceSchedulingModel = computationalResourceSchedulingModel.get();
List<InputDataObjectType> inputDataObjectTypeList = experiment.getExperimentInputs();
inputDataObjectTypeList.forEach(obj->{
if (obj.getName().equals("Wall_Time")){
obj.setValue("-walltime="+resourceSchedulingModel.getWallTimeLimit());
}
if (obj.getName().equals("Parallel_Group_Count")){
obj.setValue("-mgroupcount="+resourceSchedulingModel.getMGroupCount());
}
});
experiment.setExperimentInputs(inputDataObjectTypeList);
//update experiment model with selected compute resource
experiment.setProcesses(new ArrayList<>()); // avoid duplication issues
UserConfigurationDataModel userConfigurationDataModel = experiment.getUserConfigurationData();
userConfigurationDataModel.setComputationalResourceScheduling(resourceSchedulingModel);
experiment.setUserConfigurationData(userConfigurationDataModel);
registryClient.updateExperiment(experimentId,experiment);
List<InputDataObjectType> processInputDataObjectTypeList = processModel.getProcessInputs();
processInputDataObjectTypeList.forEach(obj->{
if (obj.getName().equals("Wall_Time")){
obj.setValue("-walltime="+resourceSchedulingModel.getWallTimeLimit());
}
if (obj.getName().equals("Parallel_Group_Count")){
obj.setValue("-mgroupcount="+resourceSchedulingModel.getMGroupCount());
}
});
processModel.setProcessInputs(processInputDataObjectTypeList);
processModel.setProcessResourceSchedule(resourceSchedulingModel);
processModel.setComputeResourceId(resourceSchedulingModel.getResourceHostId());
registryClient.updateProcess(processModel, processModel.getProcessId());
} else {
ProcessStatus newProcessStatus = new ProcessStatus();
newProcessStatus.setState(ProcessState.QUEUED);
registryClient.updateProcessStatus(newProcessStatus,processModel.getProcessId());
allProcessesScheduled = false;
}
}
}
return allProcessesScheduled;
} catch (Exception exception) {
LOGGER.error(" Exception occurred while scheduling experiment with Id {}", experimentId, exception);
} finally {
this.registryClientPool.returnResource(registryClient);
}
return false;
}
@Override
public boolean reschedule(String experimentId) {
return false;
}
}
| 1,131 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr/selection/ComputeResourceSelectionPolicyImpl.java | package org.apache.airavata.metascheduler.process.scheduling.engine.cr.selection;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.engine.ComputeResourceSelectionPolicy;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
public abstract class ComputeResourceSelectionPolicyImpl implements ComputeResourceSelectionPolicy {
protected ThriftClientPool<RegistryService.Client> registryClientPool;
public ComputeResourceSelectionPolicyImpl() {
this.registryClientPool = Utils.getRegistryServiceClientPool();
}
public GroupComputeResourcePreference getGroupComputeResourcePreference(String computeResourcId, String groupResourceProfileId) throws Exception {
RegistryService.Client client = this.registryClientPool.getResource();
try {
if (client.isGroupComputeResourcePreferenceExists(computeResourcId,
groupResourceProfileId)) {
return client.getGroupComputeResourcePreference(
computeResourcId,
groupResourceProfileId);
}
return null;
} finally {
this.registryClientPool.returnResource(client);
}
}
}
| 1,132 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr/selection/MultipleComputeResourcePolicy.java | package org.apache.airavata.metascheduler.process.scheduling.engine.cr.selection;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.QueueStatusModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
/**
* This class implements selecting one compute resource out of enabled multiple compute resource polices.
* //TODO: implemented for load testing, for proper usecases airavata should enable multiple compute resources in Experiment creation
*/
public class MultipleComputeResourcePolicy extends ComputeResourceSelectionPolicyImpl {
private static final Logger LOGGER = LoggerFactory.getLogger(MultipleComputeResourcePolicy.class);
@Override
public Optional<ComputationalResourceSchedulingModel> selectComputeResource(String processId) {
RegistryService.Client registryClient = super.registryClientPool.getResource();
try {
ProcessModel processModel = registryClient.getProcess(processId);
ExperimentModel experiment = registryClient.getExperiment(processModel.getExperimentId());
UserConfigurationDataModel userConfigurationDataModel = experiment.getUserConfigurationData();
List<ComputationalResourceSchedulingModel> resourceSchedulingModels =
userConfigurationDataModel.getAutoScheduledCompResourceSchedulingList();
List<String> retries = new ArrayList<>();
while (retries.size()<resourceSchedulingModels.size()) {
Random rand = new Random();
int upperbound = resourceSchedulingModels.size();
int int_random = rand.nextInt(upperbound);
ComputationalResourceSchedulingModel resourceSchedulingModel = resourceSchedulingModels.get(int_random);
String key = resourceSchedulingModel.getResourceHostId()+"_"+resourceSchedulingModel.getQueueName();
if(!retries.contains(key)){
ComputeResourceDescription comResourceDes = registryClient.getComputeResource(resourceSchedulingModel.getResourceHostId());
QueueStatusModel queueStatusModel = registryClient.getQueueStatus(comResourceDes.getHostName(),
resourceSchedulingModel.getQueueName());
if (queueStatusModel.isQueueUp()) {
return Optional.of(resourceSchedulingModel);
}else{
retries.add(key);
}
}
}
} catch (Exception exception) {
LOGGER.error(" Exception occurred while scheduling Process with Id {}", processId, exception);
this.registryClientPool.returnBrokenResource(registryClient);
registryClient = null;
} finally {
if (registryClient != null) {
this.registryClientPool.returnResource(registryClient);
}
}
return Optional.empty();
}
}
| 1,133 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/cr/selection/DefaultComputeResourceSelectionPolicy.java | package org.apache.airavata.metascheduler.process.scheduling.engine.cr.selection;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.QueueStatusModel;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
/**
* This class implements selecting compute resource defined in USER_CONFIGURATION_DATA and assumes only one
* compute resource is selected for experiment.
* This checks whether defined CR is live
*/
public class DefaultComputeResourceSelectionPolicy extends ComputeResourceSelectionPolicyImpl {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultComputeResourceSelectionPolicy.class);
@Override
public Optional<ComputationalResourceSchedulingModel> selectComputeResource(String processId) {
RegistryService.Client registryClient = this.registryClientPool.getResource();
try {
ProcessModel processModel = registryClient.getProcess(processId);
ExperimentModel experiment = registryClient.getExperiment(processModel.getExperimentId());
UserConfigurationDataModel userConfigurationDataModel = experiment.getUserConfigurationData();
// Assume scheduling data is populated in USER_CONFIGURATION_DATA_MODEL
ComputationalResourceSchedulingModel computationalResourceSchedulingModel = userConfigurationDataModel
.getComputationalResourceScheduling();
String computeResourceId = computationalResourceSchedulingModel.getResourceHostId();
ComputeResourceDescription comResourceDes = registryClient.getComputeResource(computeResourceId);
GroupComputeResourcePreference computeResourcePreference = getGroupComputeResourcePreference(computeResourceId,
processModel.getGroupResourceProfileId());
String hostName = comResourceDes.getHostName();
String queueName = computationalResourceSchedulingModel.getQueueName();
QueueStatusModel queueStatusModel = registryClient.getQueueStatus(hostName, queueName);
if (queueStatusModel.isQueueUp()) {
return Optional.of(computationalResourceSchedulingModel);
}
} catch (Exception exception) {
LOGGER.error(" Exception occurred while scheduling Process with Id {}", processId, exception);
this.registryClientPool.returnBrokenResource(registryClient);
registryClient = null;
} finally {
if(registryClient != null) {
this.registryClientPool.returnResource(registryClient);
}
}
return Optional.empty();
}
public static void main(String[] args) {
DefaultComputeResourceSelectionPolicy defaultComputeResourceSelectionPolicy = new DefaultComputeResourceSelectionPolicy();
defaultComputeResourceSelectionPolicy.selectComputeResource("PROCESS_5dd4f56b-f0fd-41d0-9437-693ad25f4a1d");
}
}
| 1,134 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/rescheduler/ExponentialBackOffReScheduler.java | package org.apache.airavata.metascheduler.process.scheduling.engine.rescheduler;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.engine.ComputeResourceSelectionPolicy;
import org.apache.airavata.metascheduler.core.engine.ReScheduler;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.error.ExperimentNotFoundException;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.ProcessState;
import org.apache.airavata.model.status.ProcessStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class ExponentialBackOffReScheduler implements ReScheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(ExponentialBackOffReScheduler.class);
protected ThriftClientPool<RegistryService.Client> registryClientPool = Utils.getRegistryServiceClientPool();
@Override
public void reschedule(ProcessModel processModel, ProcessState processState) {
RegistryService.Client client = null;
try {
client = this.registryClientPool.getResource();
int maxReschedulingCount = ServerSettings.getMetaschedulerReschedulingThreshold();
List<ProcessStatus> processStatusList = processModel.getProcessStatuses();
ExperimentModel experimentModel = client.getExperiment(processModel.getExperimentId());
LOGGER.info("Rescheduling process with Id " + processModel.getProcessId() + " experimentId " +
processModel.getExperimentId());
String selectionPolicyClass = ServerSettings.getComputeResourceSelectionPolicyClass();
ComputeResourceSelectionPolicy policy = (ComputeResourceSelectionPolicy) Class.forName(selectionPolicyClass)
.newInstance();
if (processState.equals(ProcessState.QUEUED)) {
Optional<ComputationalResourceSchedulingModel> computationalResourceSchedulingModel = policy.
selectComputeResource(processModel.getProcessId());
if (computationalResourceSchedulingModel.isPresent()) {
updateResourceSchedulingModel(processModel,experimentModel,client);
Utils.updateProcessStatusAndPublishStatus(ProcessState.DEQUEUING, processModel.getProcessId(),
processModel.getExperimentId(),
experimentModel.getGatewayId());
}
} else if (processState.equals(ProcessState.REQUEUED)) {
int currentCount = getRequeuedCount(processStatusList);
if (currentCount >= maxReschedulingCount) {
Utils.updateProcessStatusAndPublishStatus(ProcessState.FAILED, processModel.getProcessId(),
processModel.getExperimentId(),
experimentModel.getGatewayId());
} else {
client.deleteJobs(processModel.getProcessId());
LOGGER.debug("Cleaned up current job stack for process " + processModel.getProcessId() +
" experimentId " + processModel.getExperimentId());
ProcessStatus processStatus = client.getProcessStatus(processModel.getProcessId());
long pastValue = processStatus.getTimeOfStateChange();
int value = fib(currentCount);
long currentTime = System.currentTimeMillis();
double scanningInterval = ServerSettings.getMetaschedulerJobScanningInterval();
if (currentTime >= (pastValue + value * scanningInterval * 1000)) {
updateResourceSchedulingModel(processModel,experimentModel,client);
Utils.saveAndPublishProcessStatus(ProcessState.DEQUEUING, processModel.getProcessId(),
processModel.getExperimentId(),
experimentModel.getGatewayId());
}
}
}
return;
} catch (Exception exception) {
if (client != null) {
registryClientPool.returnBrokenResource(client);
client = null;
}
} finally {
if (client != null) {
registryClientPool.returnResource(client);
}
}
}
private int getRequeuedCount(List<ProcessStatus> processStatusList) {
return (int) processStatusList.stream().filter(x -> {
if (x.getState().equals(ProcessState.REQUEUED)) {
return true;
}
return false;
}).count();
}
private int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
private void updateResourceSchedulingModel(ProcessModel processModel, ExperimentModel experimentModel,
RegistryService.Client registryClient) throws
TException, ExperimentNotFoundException,ApplicationSettingsException, ClassNotFoundException, IllegalAccessException, InstantiationException, RegistryServiceException {
String selectionPolicyClass = ServerSettings.getComputeResourceSelectionPolicyClass();
ComputeResourceSelectionPolicy policy = (ComputeResourceSelectionPolicy) Class.forName(selectionPolicyClass)
.newInstance();
Optional<ComputationalResourceSchedulingModel> computationalResourceSchedulingModel = policy.
selectComputeResource(processModel.getProcessId());
if (computationalResourceSchedulingModel.isPresent()) {
ComputationalResourceSchedulingModel resourceSchedulingModel = computationalResourceSchedulingModel.get();
List<InputDataObjectType> inputDataObjectTypeList = experimentModel.getExperimentInputs();
inputDataObjectTypeList.forEach(obj -> {
if (obj.getName().equals("Wall_Time")) {
obj.setValue("-walltime=" + resourceSchedulingModel.getWallTimeLimit());
}
if (obj.getName().equals("Parallel_Group_Count")) {
obj.setValue("-mgroupcount=" + resourceSchedulingModel.getMGroupCount());
}
});
List<InputDataObjectType> processInputDataObjectTypeList = processModel.getProcessInputs();
processInputDataObjectTypeList.forEach(obj->{
if (obj.getName().equals("Wall_Time")){
obj.setValue("-walltime="+resourceSchedulingModel.getWallTimeLimit());
}
if (obj.getName().equals("Parallel_Group_Count")){
obj.setValue("-mgroupcount="+resourceSchedulingModel.getMGroupCount());
}
});
processModel.setProcessInputs(processInputDataObjectTypeList);
experimentModel.setExperimentInputs(inputDataObjectTypeList);
//update experiment model with selected compute resource
experimentModel.setProcesses(new ArrayList<>()); // avoid duplication issues
UserConfigurationDataModel userConfigurationDataModel = experimentModel.getUserConfigurationData();
userConfigurationDataModel.setComputationalResourceScheduling(resourceSchedulingModel);
experimentModel.setUserConfigurationData(userConfigurationDataModel);
registryClient.updateExperiment(processModel.getExperimentId(),experimentModel);
processModel.setProcessResourceSchedule(resourceSchedulingModel);
processModel.setComputeResourceId(resourceSchedulingModel.getResourceHostId());
registryClient.updateProcess(processModel, processModel.getProcessId());
}
}
}
| 1,135 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/rescheduler/ProcessReschedulingService.java | package org.apache.airavata.metascheduler.process.scheduling.engine.rescheduler;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.metascheduler.process.scheduling.utils.Constants;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Process rescheduling service to scann the Queue or Requeued services and relaunch them.
*/
public class ProcessReschedulingService implements IServer {
private final static Logger logger = LoggerFactory.getLogger(ProcessReschedulingService.class);
private static final String SERVER_NAME = "Airavata Process Rescheduling Service";
private static final String SERVER_VERSION = "1.0";
private static ServerStatus status;
private static Scheduler scheduler;
private static Map<JobDetail, Trigger> jobTriggerMap = new HashMap<>();
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
@Override
public void start() throws Exception {
jobTriggerMap.clear();
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
final int parallelJobs = ServerSettings.getMetaschedulerNoOfScanningParallelJobs();
final double scanningInterval = ServerSettings.getMetaschedulerJobScanningInterval();
for (int i = 0; i < parallelJobs; i++) {
String name = Constants.PROCESS_SCANNER_TRIGGER + "_" + i;
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(name, Constants.PROCESS_SCANNER_GROUP)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds((int) scanningInterval)
.repeatForever())
.build();
String jobName = Constants.PROCESS_SCANNER_JOB + "_" + i;
JobDetail jobC = JobBuilder
.newJob(ProcessScannerImpl.class)
.withIdentity(jobName, Constants.PROCESS_SCANNER_JOB)
.build();
jobTriggerMap.put(jobC, trigger);
}
scheduler.start();
jobTriggerMap.forEach((x, v) -> {
try {
scheduler.scheduleJob(x, v);
} catch (SchedulerException e) {
logger.error("Error occurred while scheduling job " + x.getKey().getName());
}
});
}
@Override
public void stop() throws Exception {
scheduler.unscheduleJobs(new ArrayList(jobTriggerMap.values()));
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
public void setServerStatus(ServerStatus status) {
this.status = status;
}
}
| 1,136 |
0 | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine | Create_ds/airavata/modules/airavata-metascheduler/process-scheduler/src/main/java/org/apache/airavata/metascheduler/process/scheduling/engine/rescheduler/ProcessScannerImpl.java | package org.apache.airavata.metascheduler.process.scheduling.engine.rescheduler;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.engine.ProcessScanner;
import org.apache.airavata.metascheduler.core.engine.ReScheduler;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.status.ProcessState;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.impl.JobExecutionContextImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class ProcessScannerImpl implements ProcessScanner {
private static final Logger LOGGER = LoggerFactory.getLogger(ProcessScannerImpl.class);
protected static ThriftClientPool<RegistryService.Client> registryClientPool = Utils.getRegistryServiceClientPool();
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
RegistryService.Client client = null;
try {
LOGGER.debug("Executing Process scanner ....... ");
client = this.registryClientPool.getResource();
ProcessState state = ProcessState.QUEUED;
List<ProcessModel> processModelList = client.getProcessListInState(state);
String reSchedulerPolicyClass = ServerSettings.getReSchedulerPolicyClass();
ReScheduler reScheduler = (ReScheduler) Class.forName(reSchedulerPolicyClass).newInstance();
for (ProcessModel processModel : processModelList) {
reScheduler.reschedule(processModel, state);
}
ProcessState ReQueuedState = ProcessState.REQUEUED;
List<ProcessModel> reQueuedProcessModels = client.getProcessListInState(ReQueuedState);
for (ProcessModel processModel : reQueuedProcessModels) {
reScheduler.reschedule(processModel, ReQueuedState);
}
} catch (Exception ex) {
String msg = "Error occurred while executing job" + ex.getMessage();
LOGGER.error(msg, ex);
if (client != null) {
this.registryClientPool.returnBrokenResource(client);
}
client = null;
} finally {
if (client != null) {
this.registryClientPool.returnResource(client);
}
}
}
}
| 1,137 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata/analyzer/DataInterpreterService.java | package org.apache.airavata.metascheduler.metadata.analyzer;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.metascheduler.metadata.analyzer.impl.DataAnalyzerImpl;
import org.apache.airavata.metascheduler.metadata.analyzer.utils.Constants;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DataInterpreterService implements IServer {
private final static Logger logger = LoggerFactory.getLogger(DataInterpreterService.class);
private static final String SERVER_NAME = "Data Interpreter Service";
private static final String SERVER_VERSION = "1.0";
private static ServerStatus status;
private static Scheduler scheduler;
private static Map<JobDetail, Trigger> jobTriggerMap = new HashMap<>();
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
@Override
public void start() throws Exception {
jobTriggerMap.clear();
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
final int parallelJobs = ServerSettings.getDataAnalyzerNoOfScanningParallelJobs();
final double scanningInterval = ServerSettings.getDataAnalyzerScanningInterval();
for (int i = 0; i < parallelJobs; i++) {
String name = Constants.METADATA_SCANNER_TRIGGER + "_" + i;
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(name, Constants.METADATA_SCANNER_GROUP)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds((int) scanningInterval)
.repeatForever())
.build();
String jobName = Constants.METADATA_SCANNER_JOB + "_" + i;
JobDetail jobC = JobBuilder
.newJob(DataAnalyzerImpl.class)
.withIdentity(jobName, Constants.METADATA_SCANNER_JOB)
.build();
jobTriggerMap.put(jobC, trigger);
}
scheduler.start();
jobTriggerMap.forEach((x, v) -> {
try {
scheduler.scheduleJob(x, v);
} catch (SchedulerException e) {
logger.error("Error occurred while scheduling job " + x.getKey().getName());
}
});
}
@Override
public void stop() throws Exception {
scheduler.unscheduleJobs(new ArrayList(jobTriggerMap.values()));
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
public void setServerStatus(ServerStatus status) {
this.status = status;
}
}
| 1,138 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata/analyzer | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata/analyzer/impl/DataAnalyzerImpl.java | package org.apache.airavata.metascheduler.metadata.analyzer.impl;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.engine.DataAnalyzer;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.status.JobState;
import org.apache.airavata.model.status.JobStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class DataAnalyzerImpl implements DataAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(DataAnalyzerImpl.class);
protected static ThriftClientPool<RegistryService.Client> registryClientPool = Utils.getRegistryServiceClientPool();
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
RegistryService.Client client = null;
try {
LOGGER.debug("Executing Data Analyzer ....... ");
client = this.registryClientPool.getResource();
//TODO: handle multiple gateways
String gateway = ServerSettings.getDataAnalyzingEnabledGateways();
JobState state = JobState.SUBMITTED;
JobStatus jobStatus = new JobStatus();
jobStatus.setJobState(state);
double time = ServerSettings.getDataAnalyzerTimeStep();
int fiveMinuteCount = client.getJobCount(jobStatus, gateway, 5);
int tenMinuteCount = client.getJobCount(jobStatus, gateway, 10);
int fifteenMinuteCount = client.getJobCount(jobStatus, gateway, 15);
double fiveMinuteAverage = fiveMinuteCount * time / (5 * 60);
double tenMinuteAverage = tenMinuteCount * time / (10 * 60);
double fifteenMinuteAverage = fifteenMinuteCount * time / (10 * 60);
LOGGER.info("service rate: 5 min avg " + fiveMinuteAverage + " 10 min avg "
+ tenMinuteAverage + " 15 min avg " + fifteenMinuteAverage);
Map<String, Double> timeDistribution = client.getAVGTimeDistribution(gateway,15);
String msg ="";
for(Map.Entry<String, Double> entry: timeDistribution.entrySet()){
msg = msg+ " avg time "+entry.getKey()+" : "+entry.getValue();
}
LOGGER.info(msg);
} catch (Exception ex) {
String msg = "Error occurred while executing data analyzer" + ex.getMessage();
LOGGER.error(msg, ex);
if (client != null) {
this.registryClientPool.returnBrokenResource(client);
}
client = null;
} finally {
if (client != null) {
this.registryClientPool.returnResource(client);
}
}
}
}
| 1,139 |
0 | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata/analyzer | Create_ds/airavata/modules/airavata-metascheduler/metadata-analyzer/src/main/java/org/apache/airavata/metascheduler/metadata/analyzer/utils/Constants.java | package org.apache.airavata.metascheduler.metadata.analyzer.utils;
public class Constants {
public static final String METADATA_SCANNER_GROUP = "metadata.scanner.group";
public static final String METADATA_SCANNER_TRIGGER = "metadata.scanner.trigger";
public static final String METADATA_SCANNER_JOB = "metadata.scanner.job";
}
| 1,140 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/ComputationalResourceMonitoringService.java | package org.apache.airavata.compute.resource.monitoring;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.compute.resource.monitoring.job.MonitoringJob;
import org.apache.airavata.compute.resource.monitoring.utils.Constants;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Computational Resource Monitoring Service
*/
public class ComputationalResourceMonitoringService implements IServer {
private final static Logger logger = LoggerFactory.getLogger(ComputationalResourceMonitoringService.class);
private static final String SERVER_NAME = "Airavata Compute Resource Monitoring Service";
private static final String SERVER_VERSION = "1.0";
private static ServerStatus status;
private static Scheduler scheduler;
private static Map<JobDetail, Trigger> jobTriggerMap = new HashMap<>();
@Override
public String getName() {
return null;
}
@Override
public String getVersion() {
return null;
}
@Override
public void start() throws Exception {
jobTriggerMap.clear();
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
scheduler = schedulerFactory.getScheduler();
final String metaUsername = ServerSettings.getMetaschedulerUsername();
final String metaGatewayId = ServerSettings.getMetaschedulerGateway();
final String metaGroupResourceProfileId = ServerSettings.getMetaschedulerGrpId();
final int parallelJobs = ServerSettings.getMetaschedulerNoOfScanningParallelJobs();
final double scanningInterval = ServerSettings.getMetaschedulerClusterScanningInterval();
for (int i = 0; i < parallelJobs; i++) {
String name = Constants.COMPUTE_RESOURCE_SCANNER_TRIGGER + "_" + i;
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(name, Constants.COMPUTE_RESOURCE_SCANNER_GROUP)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds((int) scanningInterval)
.repeatForever())
.build();
String jobName = Constants.COMPUTE_RESOURCE_SCANNER_JOB + "_" + i;
JobDetail jobC = JobBuilder
.newJob(MonitoringJob.class)
.withIdentity(jobName, Constants.COMPUTE_RESOURCE_SCANNER_JOB)
.usingJobData(Constants.METASCHEDULER_SCANNING_JOBS, parallelJobs)
.usingJobData(Constants.METASCHEDULER_SCANNING_JOB_ID, i)
.usingJobData(Constants.METASCHEDULER_USERNAME, metaUsername)
.usingJobData(Constants.METASCHEDULER_GATEWAY, metaGatewayId)
.usingJobData(Constants.METASCHEDULER_GRP_ID, metaGroupResourceProfileId)
.build();
jobTriggerMap.put(jobC, trigger);
}
scheduler.start();
jobTriggerMap.forEach((x, v) -> {
try {
scheduler.scheduleJob(x, v);
} catch (SchedulerException e) {
logger.error("Error occurred while scheduling job " + x.getKey().getName());
}
});
}
@Override
public void stop() throws Exception {
scheduler.unscheduleJobs(jobTriggerMap.values().stream().map(trigger -> {
return trigger.getKey();
}).collect(Collectors.toList()));
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
}
@Override
public ServerStatus getStatus() throws Exception {
return status;
}
public void setServerStatus(ServerStatus status){
this.status = status;
}
}
| 1,141 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/utils/Constants.java | package org.apache.airavata.compute.resource.monitoring.utils;
public class Constants {
public static final String METASCHEDULER_GATEWAY = "metascheduler.gateway";
public static final String METASCHEDULER_GRP_ID = "metascheduler.group.resource.profile";
public static final String METASCHEDULER_SCANNING_JOBS = "metascheduler.scanning.jobs";
public static final String METASCHEDULER_SCANNING_JOB_ID = "metascheduler.scanning.jobs.id";
public static final String METASCHEDULER_USERNAME = "metascheduler.username";
public static final String RUNNING_JOBS= "running.jobs";
public static final String PENDING_JOBS = "pending.jobs";
public static final String COMPUTE_RESOURCE_SCANNER_GROUP = "compute.resource.scanner.group";
public static final String COMPUTE_RESOURCE_SCANNER_TRIGGER = "compute.resource.scanner.trigger";
public static final String COMPUTE_RESOURCE_SCANNER_JOB = "compute.resource.scanner.job";
public static final String JOB_SUBMISSION_PROTOCOL_SLURM = "SLURM";
}
| 1,142 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job/MonitoringJob.java | package org.apache.airavata.compute.resource.monitoring.job;
import org.apache.airavata.agents.api.AgentAdaptor;
import org.apache.airavata.agents.api.CommandOutput;
import org.apache.airavata.compute.resource.monitoring.job.output.OutputParser;
import org.apache.airavata.compute.resource.monitoring.job.output.OutputParserImpl;
import org.apache.airavata.compute.resource.monitoring.utils.Constants;
import org.apache.airavata.helix.core.support.adaptor.AdaptorSupportImpl;
import org.apache.airavata.helix.impl.task.submission.config.JobFactory;
import org.apache.airavata.helix.task.api.support.AdaptorSupport;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile;
import org.apache.airavata.model.status.QueueStatusModel;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This class is responsible to execute CR monitoring code
*/
public class MonitoringJob extends ComputeResourceMonitor implements Job {
private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringJob.class);
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
RegistryService.Client client = null;
try {
LOGGER.debug("Executing ComputeResources Monitoring Job....... ");
client = this.registryClientPool.getResource();
JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
String metaSchedulerGateway = jobDataMap.getString(Constants.METASCHEDULER_GATEWAY);
String metaSchedulerGRP = jobDataMap.getString(Constants.METASCHEDULER_GRP_ID);
String username = jobDataMap.getString(Constants.METASCHEDULER_USERNAME);
int jobId = jobDataMap.getInt(Constants.METASCHEDULER_SCANNING_JOB_ID);
int parallelJobs = jobDataMap.getInt(Constants.METASCHEDULER_SCANNING_JOBS);
LOGGER.debug("Main Gateway:"+metaSchedulerGateway+" Group Resource Profile: "
+metaSchedulerGRP+" username: "+username+" jobId: "+jobId+" parallellJobs: "+parallelJobs);
executeComputeResourceMonitoring(client, metaSchedulerGateway, username, metaSchedulerGRP, parallelJobs, jobId);
} catch (Exception ex) {
String msg = "Error occurred while executing job" + ex.getMessage();
LOGGER.error(msg, ex);
if (client != null) {
registryClientPool.returnBrokenResource(client);
}
client = null;
} finally {
if (client != null) {
registryClientPool.returnResource(client);
}
}
}
private void executeComputeResourceMonitoring(RegistryService.Client client, String metaSchedulerGateway, String username,
String metaSchedulerGRP, int parallelJobs, int jobId) throws Exception {
AdaptorSupportImpl adaptorSupport = AdaptorSupportImpl.getInstance();
GroupResourceProfile groupResourceProfile = getGroupResourceProfile(metaSchedulerGRP);
// List<GroupComputeResourcePreference> computeResourcePreferenceList = groupResourceProfile.getComputePreferences();
int size = groupResourceProfile.getComputeResourcePoliciesSize();
int chunkSize = size / parallelJobs;
int startIndex = jobId * chunkSize;
int endIndex = (jobId + 1) * chunkSize;
if (jobId == parallelJobs - 1) {
endIndex = size;
}
List<ComputeResourcePolicy> computeResourcePolicyList = groupResourceProfile.getComputeResourcePolicies().
subList(startIndex, endIndex);
for (ComputeResourcePolicy computeResourcePolicy : computeResourcePolicyList) {
updateComputeResource(client, adaptorSupport, metaSchedulerGateway, username, computeResourcePolicy);
}
}
private void updateComputeResource(RegistryService.Client client, AdaptorSupport adaptorSupport,
String gatewayId,
String username,
ComputeResourcePolicy computeResourcePolicy) throws Exception {
String computeResourceId = computeResourcePolicy.getComputeResourceId();
ComputeResourceDescription comResourceDes = client.getComputeResource(computeResourceId);
List<JobSubmissionInterface> jobSubmissionInterfaces = comResourceDes.getJobSubmissionInterfaces();
Collections.sort(jobSubmissionInterfaces, Comparator.comparingInt(JobSubmissionInterface::getPriorityOrder));
JobSubmissionInterface jobSubmissionInterface = jobSubmissionInterfaces.get(0);
JobSubmissionProtocol jobSubmissionProtocol = jobSubmissionInterface.getJobSubmissionProtocol();
ResourceJobManager resourceJobManager = JobFactory.getResourceJobManager(client, jobSubmissionProtocol, jobSubmissionInterface);
//TODO: intial phase we are only supporting SLURM
if (resourceJobManager.getResourceJobManagerType().name().equals("SLURM")) {
String baseCommand = "sinfo";
if (resourceJobManager.getJobManagerCommands().containsKey(JobManagerCommand.SHOW_CLUSTER_INFO)) {
baseCommand = resourceJobManager.getJobManagerCommands().get(JobManagerCommand.SHOW_CLUSTER_INFO);
}
List<String> allowedBatchQueues = computeResourcePolicy.getAllowedBatchQueues();
List<QueueStatusModel> queueStatusModels = new ArrayList<>();
for (String queue : allowedBatchQueues) {
String finalCommand = baseCommand + " -p " + queue;
String computeResourceToken = getComputeResourceCredentialToken(
gatewayId,
username,
computeResourceId,
false,
true,
computeResourcePolicy.getGroupResourceProfileId());
String loginUsername = getComputeResourceLoginUserName(gatewayId,
username,
computeResourceId,
false,
true,
computeResourcePolicy.getGroupResourceProfileId(),
null);
AgentAdaptor adaptor = adaptorSupport.fetchAdaptor(gatewayId,
computeResourceId,
jobSubmissionProtocol,
computeResourceToken,
loginUsername);
CommandOutput commandOutput = adaptor.executeCommand(finalCommand, null);
OutputParser outputParser = new OutputParserImpl();
boolean queueStatus = false;
int runningJobs = 0;
int pendingJobs = 0;
if (outputParser.isComputeResourceAvailable(commandOutput,Constants.JOB_SUBMISSION_PROTOCOL_SLURM)) {
queueStatus = true;
String runningJobCommand = "squeue";
String pendingJobCommand = "squeue";
if (resourceJobManager.getJobManagerCommands().containsKey(JobManagerCommand.SHOW_NO_OF_RUNNING_JOBS)) {
runningJobCommand = resourceJobManager.getJobManagerCommands().get(JobManagerCommand.SHOW_NO_OF_RUNNING_JOBS);
}
if (resourceJobManager.getJobManagerCommands().containsKey(JobManagerCommand.SHOW_NO_OF_PENDING_JOBS)) {
pendingJobCommand = resourceJobManager.getJobManagerCommands().get(JobManagerCommand.SHOW_NO_OF_PENDING_JOBS);
}
String runningJobsCommand = runningJobCommand + "-h -t running -r | wc -l";
String pendingJobsCommand = pendingJobCommand + "-h -t pending -r | wc -l";
CommandOutput runningJobsCommandOutput = adaptor.executeCommand(runningJobsCommand, null);
CommandOutput pendingJobsCommandOutput = adaptor.executeCommand(pendingJobsCommand, null);
runningJobs = outputParser.getNumberofJobs(runningJobsCommandOutput,Constants.JOB_SUBMISSION_PROTOCOL_SLURM);
pendingJobs = outputParser.getNumberofJobs(pendingJobsCommandOutput,Constants.JOB_SUBMISSION_PROTOCOL_SLURM);
}
QueueStatusModel queueStatusModel = new QueueStatusModel();
queueStatusModel.setHostName(comResourceDes.getHostName());
queueStatusModel.setQueueName(queue);
queueStatusModel.setQueueUp(queueStatus);
queueStatusModel.setRunningJobs(runningJobs);
queueStatusModel.setQueuedJobs(pendingJobs);
queueStatusModels.add(queueStatusModel);
queueStatusModel.setTime(System.currentTimeMillis());
}
client.registerQueueStatuses(queueStatusModels);
}
}
}
| 1,143 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job/ComputeResourceMonitor.java | package org.apache.airavata.compute.resource.monitoring.job;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.metascheduler.core.engine.ComputeResourceSelectionPolicy;
import org.apache.airavata.metascheduler.core.utils.Utils;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserResourceProfile;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.RegistryService.Client;
public abstract class ComputeResourceMonitor {
protected ThriftClientPool<RegistryService.Client> registryClientPool;
public ComputeResourceMonitor() {
this.registryClientPool = Utils.getRegistryServiceClientPool();
}
private boolean isValid(String str) {
return str != null && !str.trim().isEmpty();
}
public UserResourceProfile getUserResourceProfile(String username, String gatewayId) throws Exception {
RegistryService.Client client = this.registryClientPool.getResource();
try {
if (client.isUserResourceProfileExists(username, gatewayId)) {
return client.getUserResourceProfile(username, gatewayId);
}
return null;
} finally {
this.registryClientPool.returnResource(client);
}
}
private UserComputeResourcePreference getUserComputeResourcePreference(String gatewayId, String username,
String computeResourceId) throws Exception {
RegistryService.Client client = this.registryClientPool.getResource();
try {
if (client.isUserComputeResourcePreferenceExists(username, gatewayId, computeResourceId)){
return client.getUserComputeResourcePreference(username, gatewayId, computeResourceId);
}
return null;
} finally {
this.registryClientPool.returnResource(client);
}
}
public String getComputeResourceCredentialToken(String gatewayId,
String username, String computeResourceId, boolean isUseUserCRPref,
boolean isSetGroupResourceProfileId, String groupResourceProfileId) throws Exception {
if (isUseUserCRPref) {
if (getUserComputeResourcePreference(gatewayId, username, computeResourceId) != null &&
isValid(getUserComputeResourcePreference(gatewayId, username, computeResourceId).getResourceSpecificCredentialStoreToken())) {
return getUserComputeResourcePreference(gatewayId, username, computeResourceId).getResourceSpecificCredentialStoreToken();
} else {
return getUserResourceProfile(username, gatewayId).getCredentialStoreToken();
}
} else if (isSetGroupResourceProfileId &&
getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId) != null &&
isValid(getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId).getResourceSpecificCredentialStoreToken())) {
return getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId).getResourceSpecificCredentialStoreToken();
} else {
return getGroupResourceProfile(groupResourceProfileId).getDefaultCredentialStoreToken();
}
}
public GroupComputeResourcePreference getGroupComputeResourcePreference(String computeResourcId, String groupResourceProfileId) throws Exception {
RegistryService.Client client = this.registryClientPool.getResource();
try {
if (client.isGroupComputeResourcePreferenceExists(computeResourcId,
groupResourceProfileId)) {
return client.getGroupComputeResourcePreference(
computeResourcId,
groupResourceProfileId);
}
return null;
} finally {
this.registryClientPool.returnResource(client);
}
}
public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) throws Exception {
RegistryService.Client client = this.registryClientPool.getResource();
try {
if (client.isGroupResourceProfileExists(groupResourceProfileId)) {
return client.getGroupResourceProfile(groupResourceProfileId);
}
return null;
} finally {
this.registryClientPool.returnResource(client);
}
}
public String getComputeResourceLoginUserName(String gatewayId,
String username, String computeResourceId, boolean isUseUserCRPref,
boolean isSetGroupResourceProfileId, String groupResourceProfileId,
String overrideLoginUsername) throws Exception {
if (isUseUserCRPref &&
getUserComputeResourcePreference(gatewayId, username, computeResourceId) != null &&
isValid(getUserComputeResourcePreference(gatewayId, username, computeResourceId).getLoginUserName())) {
return getUserComputeResourcePreference(gatewayId, username, computeResourceId).getLoginUserName();
} else if (isValid(overrideLoginUsername)) {
return overrideLoginUsername;
} else if (isSetGroupResourceProfileId &&
getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId) != null &&
isValid(getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId).getLoginUserName())) {
return getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId).getLoginUserName();
}
throw new RuntimeException("Can't find login username for compute resource");
}
}
| 1,144 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job/output/OutputParserImpl.java | package org.apache.airavata.compute.resource.monitoring.job.output;
import org.apache.airavata.agents.api.CommandOutput;
import org.apache.airavata.compute.resource.monitoring.utils.Constants;
import java.util.Scanner;
/**
* This is parser output implementation
*/
public class OutputParserImpl implements OutputParser {
@Override
public boolean isComputeResourceAvailable(CommandOutput commandOutput, String type) {
if (commandOutput.getStdOut() != null && !commandOutput.getStdOut().isEmpty()) {
if (type.equals(Constants.JOB_SUBMISSION_PROTOCOL_SLURM)) {
Scanner scanner = new Scanner(commandOutput.getStdOut());
if (scanner.hasNextLine()) {
String firstLine = scanner.nextLine();
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] splittedString = line.split(" ");
for (String splitted : splittedString) {
if (splitted.trim().equals("up")) {
return true;
}
}
}
}
}
return false;
}
@Override
public int getNumberofJobs(CommandOutput commandOutput, String type) {
if (commandOutput.getStdOut() != null && !commandOutput.getStdOut().isEmpty()) {
if (type.equals(Constants.JOB_SUBMISSION_PROTOCOL_SLURM)) {
return Integer.parseInt(commandOutput.getStdOut().trim());
}
}
return 0;
}
}
| 1,145 |
0 | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job | Create_ds/airavata/modules/computer-resource-monitoring-service/src/main/java/org/apache/airavata/compute/resource/monitoring/job/output/OutputParser.java | package org.apache.airavata.compute.resource.monitoring.job.output;
import org.apache.airavata.agents.api.CommandOutput;
/**
* This interface is responsible for parsing output of agent adaptors and derive decisions
*/
public interface OutputParser {
boolean isComputeResourceAvailable(CommandOutput commandOutput, String type);
int getNumberofJobs(CommandOutput commandOutput, String type);
}
| 1,146 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/Type.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.messaging.core;
public enum Type {
EXPERIMENT_LAUNCH,
PROCESS_LAUNCH,
STATUS
}
| 1,147 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/TestClient.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.messaging.core;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class TestClient {
public static final String RABBITMQ_BROKER_URL = "rabbitmq.broker.url";
public static final String RABBITMQ_EXCHANGE_NAME = "rabbitmq.exchange.name";
private final static Logger logger = LoggerFactory.getLogger(TestClient.class);
private final static String experimentId = "*";
public static void main(String[] args) {
try {
List<String> routingKeys = new ArrayList<>();
routingKeys.add(experimentId);
routingKeys.add(experimentId + ".*");
MessagingFactory.getSubscriber(getMessageHandler(),routingKeys, Type.STATUS);
} catch (ApplicationSettingsException e) {
logger.error("Error reading airavata server properties", e);
}catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private static MessageHandler getMessageHandler(){
return message -> {
if (message.getType().equals(MessageType.EXPERIMENT)){
try {
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent();
TBase messageEvent = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(messageEvent);
ThriftUtils.createThriftFromBytes(bytes, event);
System.out.println(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getType() + "' and with state : '" + event.getState().toString());
} catch (TException e) {
logger.error(e.getMessage(), e);
}
}
};
}
}
| 1,148 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/Subscriber.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.messaging.core;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import org.apache.airavata.common.exception.AiravataException;
import java.util.List;
import java.util.function.BiFunction;
/**
* This is the basic consumer
*/
public interface Subscriber {
/**
* Start listening for messages, The binding properties are specified in the handler.
* Returns and unique id to this Subscriber. This id can be used to stop the listening
* @param supplier - return RabbitMQ Consumer
* @return string id
* @throws AiravataException
*/
String listen(BiFunction<Connection, Channel, Consumer> supplier,
String queueName,
List<String> routingKeys) throws AiravataException;
void stopListen(final String id) throws AiravataException;
void sendAck(long deliveryTag);
}
| 1,149 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/MessageContext.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.messaging.core;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.thrift.TBase;
import java.sql.Timestamp;
public class MessageContext {
private final TBase event;
private final MessageType type;
private final String messageId;
private final String gatewayId;
private Timestamp updatedTime;
private long deliveryTag;
private boolean isRedeliver;
public MessageContext(TBase event, MessageType type, String messageId, String gatewayId) {
this.event = event;
this.type = type;
this.messageId = messageId;
this.gatewayId = gatewayId;
}
public MessageContext(TBase event, MessageType type, String messageId, String gatewayId, long deliveryTag) {
this.event = event;
this.type = type;
this.messageId = messageId;
this.gatewayId = gatewayId;
this.deliveryTag = deliveryTag;
}
public TBase getEvent() {
return event;
}
public MessageType getType() {
return type;
}
public Timestamp getUpdatedTime() {
return updatedTime;
}
public String getMessageId() {
return messageId;
}
public void setUpdatedTime(Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
public String getGatewayId() {
return gatewayId;
}
public long getDeliveryTag() {
return deliveryTag;
}
public void setDeliveryTag(long deliveryTag) {
this.deliveryTag = deliveryTag;
}
public void setIsRedeliver(boolean isRedeliver) {
this.isRedeliver = isRedeliver;
}
public boolean isRedeliver() {
return isRedeliver;
}
}
| 1,150 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/RabbitMQProperties.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.messaging.core;
public class RabbitMQProperties {
private String brokerUrl;
private EXCHANGE_TYPE exchangeType;
private String exchangeName;
private int prefetchCount;
private boolean durable;
private String queueName;
private String consumerTag = "default";
private boolean autoRecoveryEnable;
private boolean autoAck;
public String getBrokerUrl() {
return brokerUrl;
}
public RabbitMQProperties setBrokerUrl(String brokerUrl) {
this.brokerUrl = brokerUrl;
return this;
}
public boolean isDurable() {
return durable;
}
public RabbitMQProperties setDurable(boolean durable) {
this.durable = durable;
return this;
}
public String getExchangeName() {
return exchangeName;
}
public RabbitMQProperties setExchangeName(String exchangeName) {
this.exchangeName = exchangeName;
return this;
}
public int getPrefetchCount() {
return prefetchCount;
}
public RabbitMQProperties setPrefetchCount(int prefetchCount) {
this.prefetchCount = prefetchCount;
return this;
}
public String getQueueName() {
return queueName;
}
public RabbitMQProperties setQueueName(String queueName) {
this.queueName = queueName;
return this;
}
public String getConsumerTag() {
return consumerTag;
}
public RabbitMQProperties setConsumerTag(String consumerTag) {
this.consumerTag = consumerTag;
return this;
}
public boolean isAutoRecoveryEnable() {
return autoRecoveryEnable;
}
public RabbitMQProperties setAutoRecoveryEnable(boolean autoRecoveryEnable) {
this.autoRecoveryEnable = autoRecoveryEnable;
return this;
}
public String getExchangeType() {
return exchangeType.type;
}
public RabbitMQProperties setExchangeType(EXCHANGE_TYPE exchangeType) {
this.exchangeType = exchangeType;
return this;
}
public boolean isAutoAck() {
return autoAck;
}
public RabbitMQProperties setAutoAck(boolean autoAck) {
this.autoAck = autoAck;
return this;
}
public enum EXCHANGE_TYPE{
TOPIC("topic"),
FANOUT("fanout");
private String type;
EXCHANGE_TYPE(String type) {
this.type = type;
}
}
}
| 1,151 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/MessageHandler.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.messaging.core;
@FunctionalInterface
public interface MessageHandler {
void onMessage(MessageContext messageContext);
}
| 1,152 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/PublisherFactory.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.
*/
///*
// *
// * 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.messaging.core;
//
//import org.apache.airavata.common.exception.AiravataException;
//import org.apache.airavata.common.utils.ServerSettings;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class PublisherFactory {
// private static Logger log = LoggerFactory.getLogger(PublisherFactory.class);
//
// public static Publisher createActivityPublisher() throws AiravataException {
// String activityPublisher = ServerSettings.getStatusPublisher();
//
// if (activityPublisher == null) {
// String s = "Activity publisher is not specified";
// log.error(s);
// throw new AiravataException(s);
// }
//
// try {
// Class<? extends Publisher> aPublisher = Class.forName(activityPublisher).asSubclass(Publisher.class);
// return aPublisher.newInstance();
// } catch (Exception e) {
// String msg = "Failed to load the publisher from the publisher class property: " + activityPublisher;
// log.error(msg, e);
// throw new AiravataException(msg, e);
// }
// }
//
// public static Publisher createTaskLaunchPublisher() throws AiravataException {
// String taskLaunchPublisher = ServerSettings.getTaskLaunchPublisher();
//
// if (taskLaunchPublisher == null) {
// String s = "Task launch publisher is not specified";
// log.error(s);
// throw new AiravataException(s);
// }
//
// try {
// Class<? extends Publisher> aPublisher = Class.forName(taskLaunchPublisher).asSubclass(Publisher.class);
// return aPublisher.newInstance();
// } catch (Exception e) {
// String msg = "Failed to load the publisher from the publisher class property: " + taskLaunchPublisher;
// log.error(msg, e);
// throw new AiravataException(msg, e);
// }
// }
//}
| 1,153 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/MessagingFactory.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.messaging.core;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.messaging.core.impl.*;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.JobIdentifier;
import org.apache.airavata.model.messaging.event.JobStatusChangeEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessIdentifier;
import org.apache.airavata.model.messaging.event.ProcessStatusChangeEvent;
import org.apache.airavata.model.messaging.event.TaskOutputChangeEvent;
import org.apache.airavata.model.messaging.event.TaskStatusChangeEvent;
import java.util.ArrayList;
import java.util.List;
public class MessagingFactory {
public static Subscriber getSubscriber(final MessageHandler messageHandler,List<String> routingKeys, Type type) throws AiravataException {
Subscriber subscriber = null;
RabbitMQProperties rProperties = getProperties();
switch (type) {
case EXPERIMENT_LAUNCH:
subscriber = getExperimentSubscriber(rProperties);
subscriber.listen(((connection, channel) -> new ExperimentConsumer(messageHandler, connection, channel)),
rProperties.getQueueName(),
routingKeys);
break;
case PROCESS_LAUNCH:
subscriber = getProcessSubscriber(rProperties);
subscriber.listen((connection ,channel) -> new ProcessConsumer(messageHandler, connection, channel),
rProperties.getQueueName(),
routingKeys);
break;
case STATUS:
subscriber = getStatusSubscriber(rProperties);
subscriber.listen((connection, channel) -> new StatusConsumer(messageHandler, connection, channel),
rProperties.getQueueName(),
routingKeys);
break;
default:
break;
}
return subscriber;
}
public static Subscriber getDBEventSubscriber(final MessageHandler messageHandler, String serviceName) throws AiravataException {
RabbitMQProperties rProperties = getProperties();
//FIXME: Set autoAck to false and handle possible situations
rProperties.setExchangeName(DBEventManagerConstants.DB_EVENT_EXCHANGE_NAME)
.setQueueName(DBEventManagerConstants.getQueueName(serviceName))
.setAutoAck(false);
Subscriber subscriber = new RabbitMQSubscriber(rProperties);
subscriber.listen(((connection, channel) -> new MessageConsumer(messageHandler, connection, channel)),
rProperties.getQueueName(),
new ArrayList<String>(){{add(DBEventManagerConstants.getRoutingKey(serviceName));}});
return subscriber;
}
public static Publisher getPublisher(Type type) throws AiravataException {
RabbitMQProperties rProperties = getProperties();
Publisher publiser = null;
switch (type) {
case EXPERIMENT_LAUNCH:
publiser = getExperimentPublisher(rProperties);
break;
case PROCESS_LAUNCH:
publiser = gerProcessPublisher(rProperties);
break;
case STATUS:
publiser = getStatusPublisher(rProperties);
break;
default:
throw new IllegalArgumentException("Publisher " + type + " is not handled");
}
return publiser;
}
public static Publisher getDBEventPublisher() throws AiravataException {
RabbitMQProperties rProperties = getProperties();
rProperties.setExchangeName(DBEventManagerConstants.DB_EVENT_EXCHANGE_NAME);
return new RabbitMQPublisher(rProperties);
}
private static Publisher getExperimentPublisher(RabbitMQProperties rProperties) throws AiravataException {
rProperties.setExchangeName(ServerSettings.getRabbitmqExperimentExchangeName());
return new RabbitMQPublisher(rProperties, messageContext -> rProperties.getExchangeName());
}
private static Publisher getStatusPublisher(RabbitMQProperties rProperties) throws AiravataException {
rProperties.setExchangeName(ServerSettings.getRabbitmqStatusExchangeName());
return new RabbitMQPublisher(rProperties, MessagingFactory::statusRoutingkey);
}
private static Publisher gerProcessPublisher(RabbitMQProperties rProperties) throws AiravataException {
rProperties.setExchangeName(ServerSettings.getRabbitmqProcessExchangeName());
return new RabbitMQPublisher(rProperties, messageContext -> rProperties.getExchangeName());
}
private static RabbitMQProperties getProperties() {
return new RabbitMQProperties()
.setBrokerUrl(ServerSettings.getRabbitmqBrokerUrl())
.setDurable(ServerSettings.getRabbitmqDurableQueue())
.setPrefetchCount(ServerSettings.getRabbitmqPrefetchCount())
.setAutoRecoveryEnable(true)
.setConsumerTag("default")
.setExchangeType(RabbitMQProperties.EXCHANGE_TYPE.TOPIC);
}
private static RabbitMQSubscriber getStatusSubscriber(RabbitMQProperties sp) throws AiravataException {
sp.setExchangeName(ServerSettings.getRabbitmqStatusExchangeName())
.setAutoAck(true);
return new RabbitMQSubscriber(sp);
}
private static RabbitMQSubscriber getProcessSubscriber(RabbitMQProperties sp) throws AiravataException {
sp.setExchangeName(ServerSettings.getRabbitmqProcessExchangeName())
.setQueueName("process_launch")
.setAutoAck(false);
return new RabbitMQSubscriber(sp);
}
private static Subscriber getExperimentSubscriber(RabbitMQProperties sp) throws AiravataException {
sp.setExchangeName(ServerSettings.getRabbitmqExperimentExchangeName())
.setQueueName("experiment_launch")
.setAutoAck(false);
return new RabbitMQSubscriber(sp);
}
private static String statusRoutingkey(MessageContext msgCtx) {
String gatewayId = msgCtx.getGatewayId();
String routingKey = null;
if (msgCtx.getType() == MessageType.EXPERIMENT) {
ExperimentStatusChangeEvent event = (ExperimentStatusChangeEvent) msgCtx.getEvent();
routingKey = gatewayId + "." + event.getExperimentId();
} else if (msgCtx.getType() == MessageType.TASK) {
TaskStatusChangeEvent event = (TaskStatusChangeEvent) msgCtx.getEvent();
routingKey = gatewayId + "." + event.getTaskIdentity().getExperimentId() + "." +
event.getTaskIdentity().getProcessId() + "." + event.getTaskIdentity().getTaskId();
} else if (msgCtx.getType() == MessageType.PROCESSOUTPUT) {
TaskOutputChangeEvent event = (TaskOutputChangeEvent) msgCtx.getEvent();
routingKey = gatewayId + "." + event.getTaskIdentity().getExperimentId() + "." +
event.getTaskIdentity().getProcessId() + "." + event.getTaskIdentity().getTaskId();
} else if (msgCtx.getType() == MessageType.PROCESS) {
ProcessStatusChangeEvent event = (ProcessStatusChangeEvent) msgCtx.getEvent();
ProcessIdentifier processIdentifier = event.getProcessIdentity();
routingKey = gatewayId + "." + processIdentifier.getExperimentId() + "." + processIdentifier.getProcessId();
} else if (msgCtx.getType() == MessageType.JOB) {
JobStatusChangeEvent event = (JobStatusChangeEvent) msgCtx.getEvent();
JobIdentifier identity = event.getJobIdentity();
routingKey = gatewayId + "." + identity.getExperimentId() + "." +
identity.getProcessId() + "." +
identity.getTaskId() + "." +
identity.getJobId();
}
return routingKey;
}
}
| 1,154 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/MessagingConstants.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.messaging.core;
@Deprecated
public abstract class MessagingConstants {
public static final String RABBITMQ_BROKER_URL = "rabbitmq.broker.url";
public static final String RABBITMQ_STATUS_EXCHANGE_NAME = "rabbitmq.status.exchange.name";
public static final String RABBITMQ_TASK_EXCHANGE_NAME = "rabbitmq.task.exchange.name";
public static final String RABBIT_ROUTING_KEY = "routingKey";
public static final String RABBIT_QUEUE= "queue";
public static final String RABBIT_CONSUMER_TAG = "consumerTag";
public static final String DURABLE_QUEUE="durable.queue";
public static final String PREFETCH_COUNT="prefetch.count";
}
| 1,155 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/Publisher.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.messaging.core;
import org.apache.airavata.common.exception.AiravataException;
/**
* This is the basic publisher interface.
*/
//@FunctionalInterface
public interface Publisher {
/**
*
* @param messageContext object of message context which will include actual event and other information
* @throws AiravataException
*/
public void publish(MessageContext messageContext) throws AiravataException;
/**
* For publishing DB Events
* @param messageContext object of message context which will include actual db event and other information
* @param routingKey
* @throws AiravataException
*/
public void publish(MessageContext messageContext, String routingKey) throws AiravataException;
}
| 1,156 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/MessageConsumer.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.messaging.core.impl;
import com.rabbitmq.client.*;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.model.dbevent.DBEventMessage;
import org.apache.airavata.model.dbevent.DBEventMessageContext;
import org.apache.airavata.model.messaging.event.ExperimentSubmitEvent;
import org.apache.airavata.model.messaging.event.Message;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import java.io.IOException;
public class MessageConsumer extends QueueingConsumer {
private static final Logger logger = LogManager.getLogger(MessageConsumer.class);
private MessageHandler handler;
private Channel channel;
private Connection connection;
public MessageConsumer(MessageHandler messageHandler, Connection connection, Channel channel) {
super(channel);
this.handler = messageHandler;
this.connection = connection;
this.channel = channel;
}
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body) throws IOException {
Message message = new Message();
try {
logger.info("handleDelivery() -> Handling message delivery. Consumer Tag : " + consumerTag);
ThriftUtils.createThriftFromBytes(body, message);
DBEventMessage dBEventMessage = new DBEventMessage();
ThriftUtils.createThriftFromBytes(message.getEvent(), dBEventMessage);
MessageContext messageContext = new MessageContext((TBase) dBEventMessage, message.getMessageType(), message.getMessageId(), "gatewayId", envelope.getDeliveryTag());
handler.onMessage(messageContext);
//sendAck(deliveryTag);
} catch (TException e) {
logger.error("handleDelivery() -> Error handling delivery. Consumer Tag : " + consumerTag, e);
}
}
private void sendAck(long deliveryTag){
logger.info("sendAck() -> Sending ack. Delivery Tag : " + deliveryTag);
try {
if (channel.isOpen()){
channel.basicAck(deliveryTag,false);
}else {
channel = connection.createChannel();
channel.basicQos(20);
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
logger.error("sendAck() -> Error sending ack. Delivery Tag : " + deliveryTag, e);
}
}
}
| 1,157 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/ExperimentConsumer.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.messaging.core.impl;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.QueueingConsumer;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.model.messaging.event.*;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class ExperimentConsumer extends QueueingConsumer {
private static final Logger log = LoggerFactory.getLogger(ExperimentConsumer.class);
private MessageHandler handler;
private Channel channel;
private Connection connection;
public ExperimentConsumer(MessageHandler messageHandler, Connection connection, Channel channel) {
super(channel);
this.handler = messageHandler;
this.connection = connection;
this.channel = channel;
}
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body) throws IOException {
Message message = new Message();
try {
ThriftUtils.createThriftFromBytes(body, message);
long deliveryTag = envelope.getDeliveryTag();
TBase event = null;
String gatewayId = null;
if (message.getMessageType() == MessageType.EXPERIMENT ||
message.getMessageType() == MessageType.EXPERIMENT_CANCEL) {
ExperimentSubmitEvent experimentEvent = new ExperimentSubmitEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), experimentEvent);
log.info(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' for experimentId:" +
" " +
experimentEvent.getExperimentId());
event = experimentEvent;
gatewayId = experimentEvent.getGatewayId();
MessageContext messageContext = new MessageContext(event, message.getMessageType(),
message.getMessageId(), gatewayId, deliveryTag);
messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
messageContext.setIsRedeliver(envelope.isRedeliver());
handler.onMessage(messageContext);
} else if (message.getMessageType() == MessageType.INTERMEDIATE_OUTPUTS) {
ExperimentIntermediateOutputsEvent intermediateOutEvt = new ExperimentIntermediateOutputsEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), intermediateOutEvt);
log.info(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' for experimentId:" +
" " +
intermediateOutEvt.getExperimentId());
event = intermediateOutEvt;
gatewayId = intermediateOutEvt.getGatewayId();
MessageContext messageContext = new MessageContext(event, message.getMessageType(),
message.getMessageId(), gatewayId, deliveryTag);
messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
messageContext.setIsRedeliver(envelope.isRedeliver());
handler.onMessage(messageContext);
}else {
log.error("{} message type is not handle in ProcessLaunch Subscriber. Sending ack for " +
"delivery tag {} ", message.getMessageType().name(), deliveryTag);
sendAck(deliveryTag);
}
} catch (TException e) {
String msg = "Failed to de-serialize the thrift message, from routing keys:" + envelope.getRoutingKey();
log.warn(msg, e);
}
}
private void sendAck(long deliveryTag){
try {
if (channel.isOpen()){
channel.basicAck(deliveryTag,false);
}else {
channel = connection.createChannel();
channel.basicQos(ServerSettings.getRabbitmqPrefetchCount());
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
| 1,158 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/ProcessConsumer.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.messaging.core.impl;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.QueueingConsumer;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.model.messaging.event.Message;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessSubmitEvent;
import org.apache.airavata.model.messaging.event.ProcessTerminateEvent;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class ProcessConsumer extends QueueingConsumer{
private static final Logger log = LoggerFactory.getLogger(ProcessConsumer.class);
private MessageHandler handler;
private Channel channel;
private Connection connection;
public ProcessConsumer(MessageHandler messageHandler, Connection connection, Channel channel){
super(channel);
this.handler = messageHandler;
this.connection = connection;
this.channel = channel;
}
@Override public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties basicProperties,
byte[] body) throws IOException {
Message message = new Message();
try {
ThriftUtils.createThriftFromBytes(body, message);
TBase event = null;
String gatewayId = null;
long deliveryTag = envelope.getDeliveryTag();
if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
ProcessSubmitEvent processSubmitEvent = new ProcessSubmitEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), processSubmitEvent);
log.info(" Message Received with message id '" + message.getMessageId()
+ " and with message type:" + message.getMessageType() + ", for processId:" +
processSubmitEvent.getProcessId() + ", expId:" + processSubmitEvent.getExperimentId());
event = processSubmitEvent;
gatewayId = processSubmitEvent.getGatewayId();
MessageContext messageContext = new MessageContext(event, message.getMessageType(),
message.getMessageId(), gatewayId, deliveryTag);
messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
messageContext.setIsRedeliver(envelope.isRedeliver());
handler.onMessage(messageContext);
} else if (message.getMessageType().equals(MessageType.TERMINATEPROCESS)) {
ProcessTerminateEvent processTerminateEvent = new ProcessTerminateEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), processTerminateEvent);
log.info(" Message Received with message id '" + message.getMessageId()
+ " and with message type:" + message.getMessageType() + ", for processId:" +
processTerminateEvent.getProcessId());
event = processTerminateEvent;
gatewayId = processTerminateEvent.getGatewayId();
MessageContext messageContext = new MessageContext(event, message.getMessageType(),
message.getMessageId(), gatewayId, deliveryTag);
messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
messageContext.setIsRedeliver(envelope.isRedeliver());
handler.onMessage(messageContext);
} else {
log.error("{} message type is not handle in ProcessLaunch Subscriber. Sending ack for " +
"delivery tag {} ", message.getMessageType().name(), deliveryTag);
sendAck(deliveryTag);
}
} catch (TException e) {
String msg = "Failed to de-serialize the thrift message, from routing keys:" + envelope.getRoutingKey();
log.warn(msg, e);
}
}
private void sendAck(long deliveryTag){
try {
if (channel.isOpen()){
channel.basicAck(deliveryTag,false);
}else {
channel = connection.createChannel();
channel.basicQos(ServerSettings.getRabbitmqPrefetchCount());
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
| 1,159 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQProcessLaunchPublisher.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.
*/
///*
// *
// * 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.messaging.core.impl;
//
//import org.apache.airavata.common.exception.AiravataException;
//import org.apache.airavata.common.exception.ApplicationSettingsException;
//import org.apache.airavata.common.utils.ServerSettings;
//import org.apache.airavata.common.utils.ThriftUtils;
//import org.apache.airavata.messaging.core.MessageContext;
//import org.apache.airavata.messaging.core.MessagingConstants;
//import org.apache.airavata.messaging.core.Publisher;
//import org.apache.airavata.model.messaging.event.*;
//import org.apache.thrift.TException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class RabbitMQProcessLaunchPublisher implements Publisher{
// private final static Logger log = LoggerFactory.getLogger(RabbitMQProcessLaunchPublisher.class);
// private String launchTask;
//
// private RabbitMQProducer rabbitMQProducer;
//
// public RabbitMQProcessLaunchPublisher() throws Exception {
// String brokerUrl;
// try {
// brokerUrl = ServerSettings.getSetting(MessagingConstants.RABBITMQ_BROKER_URL);
// launchTask = ServerSettings.getRabbitmqProcessLaunchQueueName();
// } catch (ApplicationSettingsException e) {
// String message = "Failed to get read the required properties from airavata to initialize rabbitmq";
// log.error(message, e);
// throw new AiravataException(message, e);
// }
// rabbitMQProducer = new RabbitMQProducer(brokerUrl, null,null);
// rabbitMQProducer.open();
// }
//
// public void publish(MessageContext msgCtx) throws AiravataException {
// try {
// log.info("Publishing to launch queue ...");
// byte[] body = ThriftUtils.serializeThriftObject(msgCtx.getEvent());
// Message message = new Message();
// message.setEvent(body);
// message.setMessageId(msgCtx.getMessageId());
// message.setMessageType(msgCtx.getType());
// message.setUpdatedTime(msgCtx.getUpdatedTime().getTime());
// String routingKey = launchTask;
// byte[] messageBody = ThriftUtils.serializeThriftObject(message);
// rabbitMQProducer.sendToWorkerQueue(messageBody, routingKey);
// log.info("Successfully published to launch queue ...");
// } catch (TException e) {
// String msg = "Error while deserializing the object";
// log.error(msg, e);
// throw new AiravataException(msg, e);
// } catch (Exception e) {
// String msg = "Error while sending to rabbitmq";
// log.error(msg, e);
// throw new AiravataException(msg, e);
// }
// }
//}
| 1,160 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQPublisher.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.messaging.core.impl;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.RabbitMQProperties;
import org.apache.airavata.model.messaging.event.Message;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.function.Function;
public class RabbitMQPublisher implements Publisher {
private static final Logger log = LoggerFactory.getLogger(RabbitMQPublisher.class);
private final RabbitMQProperties properties;
private final Function<MessageContext, String> routingKeySupplier;
private Connection connection;
private ThreadLocal<Channel> channelThreadLocal = new ThreadLocal<>();
public RabbitMQPublisher(RabbitMQProperties properties, Function<MessageContext, String> routingKeySupplier) throws AiravataException {
this.properties = properties;
this.routingKeySupplier = routingKeySupplier;
connect();
}
public RabbitMQPublisher(RabbitMQProperties properties) throws AiravataException {
this.properties = properties;
routingKeySupplier = null;
connect();
}
private void connect() throws AiravataException {
try {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setUri(properties.getBrokerUrl());
connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
connection = connectionFactory.newConnection();
connection.addShutdownListener(new ShutdownListener() {
public void shutdownCompleted(ShutdownSignalException cause) {
}
});
log.info("connected to rabbitmq: " + connection + " for " + properties.getExchangeName());
} catch (Exception e) {
String msg = "RabbitMQ connection issue for exchange : " + properties.getExchangeName() + " with broker url " + properties.getBrokerUrl();
log.error(msg);
throw new AiravataException(msg, e);
}
}
@Override
public void publish(MessageContext messageContext) throws AiravataException {
try {
byte[] body = ThriftUtils.serializeThriftObject(messageContext.getEvent());
Message message = new Message();
message.setEvent(body);
message.setMessageId(messageContext.getMessageId());
message.setMessageType(messageContext.getType());
message.setUpdatedTime(messageContext.getUpdatedTime().getTime());
String routingKey = routingKeySupplier.apply(messageContext);
// log.info("publish messageId:" + messageContext.getMessageId() + ", messageType:" + messageContext.getType() + ", to routingKey:" + routingKey);
byte[] messageBody = ThriftUtils.serializeThriftObject(message);
send(messageBody, routingKey);
} catch (TException e) {
String msg = "Error while deserializing the object";
log.error(msg, e);
throw new AiravataException(msg, e);
} catch (Exception e) {
String msg = "Error while sending to rabbitmq";
log.error(msg, e);
throw new AiravataException(msg, e);
}
}
/**
* This method is used only for publishing DB Events
* @param messageContext object of message context which will include actual db event and other information
* @param routingKey
* @throws AiravataException
*/
@Override
public void publish(MessageContext messageContext, String routingKey) throws AiravataException {
try {
byte[] body = ThriftUtils.serializeThriftObject(messageContext.getEvent());
Message message = new Message();
message.setEvent(body);
message.setMessageId(messageContext.getMessageId());
message.setMessageType(messageContext.getType());
if (messageContext.getUpdatedTime() != null) {
message.setUpdatedTime(messageContext.getUpdatedTime().getTime());
}
// log.info("publish messageId:" + messageContext.getMessageId() + ", messageType:" + messageContext.getType() + ", to routingKey:" + routingKey);
byte[] messageBody = ThriftUtils.serializeThriftObject(message);
send(messageBody, routingKey);
} catch (TException e) {
String msg = "Error while deserializing the object";
log.error(msg, e);
throw new AiravataException(msg, e);
} catch (Exception e) {
String msg = "Error while sending to rabbitmq";
log.error(msg, e);
throw new AiravataException(msg, e);
}
}
public void send(byte []message, String routingKey) throws Exception {
try {
if (channelThreadLocal.get() == null) {
log.info("Creating the channel for thread " + Thread.currentThread().getName() + " " + toString());
Channel channel = connection.createChannel();
if (properties.getPrefetchCount() > 0) {
channel.basicQos(properties.getPrefetchCount());
}
if (properties.getExchangeName() != null) {
channel.exchangeDeclare(properties.getExchangeName(),
properties.getExchangeType(),
true); //durable
}
channelThreadLocal.set(channel);
}
channelThreadLocal.get().basicPublish(properties.getExchangeName(), routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, message);
} catch (IOException e) {
String msg = "Failed to publish message to exchange: " + properties.getExchangeName();
log.error(msg, e);
throw new Exception(msg, e);
}
}
}
| 1,161 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/StatusConsumer.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.messaging.core.impl;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.JobStatusChangeEvent;
import org.apache.airavata.model.messaging.event.Message;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessStatusChangeEvent;
import org.apache.airavata.model.messaging.event.TaskOutputChangeEvent;
import org.apache.airavata.model.messaging.event.TaskStatusChangeEvent;
import org.apache.airavata.model.messaging.event.TaskSubmitEvent;
import org.apache.airavata.model.messaging.event.TaskTerminateEvent;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class StatusConsumer extends DefaultConsumer {
private static final Logger log = LoggerFactory.getLogger(StatusConsumer.class);
private MessageHandler handler;
private Connection connection;
private Channel channel;
public StatusConsumer(MessageHandler handler, Connection connection, Channel channel) {
super(channel);
this.handler = handler;
this.connection = connection;
this.channel = channel;
}
private StatusConsumer(Channel channel) {
super(channel);
}
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body) throws IOException {
Message message = new Message();
try {
ThriftUtils.createThriftFromBytes(body, message);
TBase event = null;
String gatewayId = null;
if (message.getMessageType().equals(MessageType.EXPERIMENT)) {
ExperimentStatusChangeEvent experimentStatusChangeEvent = new ExperimentStatusChangeEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), experimentStatusChangeEvent);
log.debug(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' with status " +
experimentStatusChangeEvent.getState());
event = experimentStatusChangeEvent;
gatewayId = experimentStatusChangeEvent.getGatewayId();
} else if (message.getMessageType().equals(MessageType.PROCESS)) {
ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), processStatusChangeEvent);
log.debug("Message Recieved with message id :" + message.getMessageId() + " and with " +
"message type " + message.getMessageType() + " with status " +
processStatusChangeEvent.getState());
event = processStatusChangeEvent;
gatewayId = processStatusChangeEvent.getProcessIdentity().getGatewayId();
} else if (message.getMessageType().equals(MessageType.TASK)) {
TaskStatusChangeEvent taskStatusChangeEvent = new TaskStatusChangeEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), taskStatusChangeEvent);
log.debug(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' with status " +
taskStatusChangeEvent.getState());
event = taskStatusChangeEvent;
gatewayId = taskStatusChangeEvent.getTaskIdentity().getGatewayId();
} else if (message.getMessageType() == MessageType.PROCESSOUTPUT) {
TaskOutputChangeEvent taskOutputChangeEvent = new TaskOutputChangeEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), taskOutputChangeEvent);
log.debug(" Message Received with message id '" + message.getMessageId() + "' and with message type '" + message.getMessageType());
event = taskOutputChangeEvent;
gatewayId = taskOutputChangeEvent.getTaskIdentity().getGatewayId();
} else if (message.getMessageType().equals(MessageType.JOB)) {
JobStatusChangeEvent jobStatusChangeEvent = new JobStatusChangeEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), jobStatusChangeEvent);
log.debug(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' with status " +
jobStatusChangeEvent.getState());
event = jobStatusChangeEvent;
gatewayId = jobStatusChangeEvent.getJobIdentity().getGatewayId();
} else if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
TaskSubmitEvent taskSubmitEvent = new TaskSubmitEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), taskSubmitEvent);
log.debug(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' for experimentId: " +
taskSubmitEvent.getExperimentId() + "and taskId: " + taskSubmitEvent.getTaskId());
event = taskSubmitEvent;
gatewayId = taskSubmitEvent.getGatewayId();
} else if (message.getMessageType().equals(MessageType.TERMINATEPROCESS)) {
TaskTerminateEvent taskTerminateEvent = new TaskTerminateEvent();
ThriftUtils.createThriftFromBytes(message.getEvent(), taskTerminateEvent);
log.debug(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getMessageType() + "' for experimentId: " +
taskTerminateEvent.getExperimentId() + "and taskId: " + taskTerminateEvent.getTaskId());
event = taskTerminateEvent;
gatewayId = null;
}
MessageContext messageContext = new MessageContext(event, message.getMessageType(), message.getMessageId(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
messageContext.setIsRedeliver(envelope.isRedeliver());
handler.onMessage(messageContext);
} catch (TException e) {
String msg = "Failed to de-serialize the thrift message, from routing keys: " + envelope.getRoutingKey();
log.warn(msg, e);
}
}
}
| 1,162 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQSubscriber.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.messaging.core.impl;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.messaging.core.Subscriber;
import org.apache.airavata.messaging.core.RabbitMQProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
public class RabbitMQSubscriber implements Subscriber {
private static final Logger log = LoggerFactory.getLogger(RabbitMQSubscriber.class);
private Connection connection;
private Channel channel;
private Map<String, QueueDetail> queueDetailMap = new HashMap<>();
private RabbitMQProperties properties;
public RabbitMQSubscriber(RabbitMQProperties properties) throws AiravataException {
this.properties = properties;
createConnection();
}
private void createConnection() throws AiravataException {
try {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setUri(properties.getBrokerUrl());
connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
connection = connectionFactory.newConnection();
addShutdownListener();
log.info("connected to rabbitmq: " + connection + " for " + properties.getExchangeName());
channel = connection.createChannel();
channel.basicQos(properties.getPrefetchCount());
channel.exchangeDeclare(properties.getExchangeName(),
properties.getExchangeType(),
true); // durable
} catch (Exception e) {
String msg = "could not open channel for exchange " + properties.getExchangeName();
log.error(msg);
throw new AiravataException(msg, e);
}
}
@Override
public String listen(BiFunction<Connection, Channel, Consumer> supplier,
String queueName,
List<String> routingKeys) throws AiravataException {
try {
if (!channel.isOpen()) {
channel = connection.createChannel();
channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), false);
}
if (queueName == null) {
queueName = channel.queueDeclare().getQueue();
} else {
channel.queueDeclare(queueName,
true, // durable
false, // exclusive
false, // autoDelete
null);// arguments
}
final String id = getId(routingKeys, queueName);
if (queueDetailMap.containsKey(id)) {
throw new IllegalStateException("This subscriber is already defined for this Subscriber, " +
"cannot define the same subscriber twice");
}
// bind all the routing keys
for (String key : routingKeys) {
// log.info("Binding key:" + key + " to queue:" + queueName);
channel.queueBind(queueName, properties.getExchangeName(), key);
}
channel.basicConsume(queueName,
properties.isAutoAck(),
properties.getConsumerTag(),
supplier.apply(connection, channel));
queueDetailMap.put(id, new QueueDetail(queueName, routingKeys));
return id;
} catch (IOException e) {
String msg = "could not open channel for exchange " + properties.getExchangeName();
log.error(msg);
throw new AiravataException(msg, e);
}
}
@Override
public void stopListen(String id) throws AiravataException {
QueueDetail details = queueDetailMap.get(id);
if (details != null) {
try {
for (String key : details.getRoutingKeys()) {
channel.queueUnbind(details.getQueueName(), properties.getExchangeName(), key);
}
channel.queueDelete(details.getQueueName(), true, true);
} catch (IOException e) {
String msg = "could not un-bind queue: " + details.getQueueName() + " for exchange " + properties.getExchangeName();
log.debug(msg);
}
}
}
@Override
public void sendAck(long deliveryTag) {
try {
if (channel.isOpen()){
channel.basicAck(deliveryTag,false);
}else {
channel = connection.createChannel();
channel.basicQos(properties.getPrefetchCount());
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
private void addShutdownListener() {
connection.addShutdownListener(new ShutdownListener() {
public void shutdownCompleted(ShutdownSignalException cause) {
log.error("RabbitMQ connection " + connection + " for " + properties.getExchangeName() + " has been shut down", cause);
}
});
}
private String getId(List<String> routingKeys, String queueName) {
String id = "";
for (String key : routingKeys) {
id = id + "_" + key;
}
return id + "_" + queueName;
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (IOException ignore) {
}
}
}
private class QueueDetail {
String queueName;
List<String> routingKeys;
private QueueDetail(String queueName, List<String> routingKeys) {
this.queueName = queueName;
this.routingKeys = routingKeys;
}
public String getQueueName() {
return queueName;
}
List<String> getRoutingKeys() {
return routingKeys;
}
}
}
| 1,163 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQProducer.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.
*/
///*
// *
// * 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.messaging.core.impl;
//
//import com.rabbitmq.client.*;
//import org.apache.airavata.common.exception.AiravataException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//
//public class RabbitMQProducer {
// public static final int DEFAULT_PRE_FETCH = 64;
//
// private static Logger log = LoggerFactory.getLogger(RabbitMQProducer.class);
//
// private Connection connection;
//
// private Channel channel;
//
// private QueueingConsumer consumer;
//
// private String consumerTag;
//
// private String exchangeName;
//
// private int prefetchCount = DEFAULT_PRE_FETCH;
//
// private boolean isReQueueOnFail = false;
//
// private String url;
//
// private String getExchangeType = "topic";
//
//
// public RabbitMQProducer(String url, String exchangeName,String getExchangeType) {
// this.exchangeName = exchangeName;
// this.url = url;
// this.getExchangeType = getExchangeType;
// }
//
// public RabbitMQProducer(String url, String exchangeName) {
// this.exchangeName = exchangeName;
// this.url = url;
// }
//
// public void setPrefetchCount(int prefetchCount) {
// this.prefetchCount = prefetchCount;
// }
//
// public void setReQueueOnFail(boolean isReQueueOnFail) {
// this.isReQueueOnFail = isReQueueOnFail;
// }
//
// private void reset() {
// consumerTag = null;
// }
//
// private void reInitIfNecessary() throws Exception {
// if (consumerTag == null || consumer == null) {
// close();
// open();
// }
// }
//
// public void close() {
// log.info("Closing channel to exchange {}", exchangeName);
// try {
// if (channel != null && channel.isOpen()) {
// if (consumerTag != null) {
// channel.basicCancel(consumerTag);
// }
// channel.close();
// }
// } catch (Exception e) {
// log.debug("error closing channel and/or cancelling consumer", e);
// }
// try {
// log.info("closing connection to rabbitmq: " + connection);
// connection.close();
// } catch (Exception e) {
// log.debug("error closing connection", e);
// }
// consumer = null;
// consumerTag = null;
// channel = null;
// connection = null;
// }
//
// public void open() throws AiravataException {
// try {
// connection = createConnection();
// channel = connection.createChannel();
// if (prefetchCount > 0) {
// log.info("setting basic.qos / prefetch count to " + prefetchCount + " for " + exchangeName);
// channel.basicQos(prefetchCount);
// }
// if(exchangeName!=null) {
// channel.exchangeDeclare(exchangeName, getExchangeType, false);
// }
// } catch (Exception e) {
// reset();
// String msg = "could not open channel for exchange " + exchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
// }
// }
//
// public void send(byte []message, String routingKey) throws Exception {
// try {
// channel.basicPublish(exchangeName, routingKey, null, message);
// } catch (IOException e) {
// String msg = "Failed to publish message to exchange: " + exchangeName;
// log.error(msg, e);
// throw new Exception(msg, e);
// }
// }
//
// public void sendToWorkerQueue(byte []message, String routingKey) throws Exception {
// try {
// channel.basicPublish( "", routingKey,
// MessageProperties.PERSISTENT_TEXT_PLAIN,
// message);
// } catch (IOException e) {
// String msg = "Failed to publish message to exchange: " + exchangeName;
// log.error(msg, e);
// throw new Exception(msg, e);
// }
// }
//
// private Connection createConnection() throws IOException {
// try {
// ConnectionFactory connectionFactory = new ConnectionFactory();
// connectionFactory.setUri(url);
// connectionFactory.setAutomaticRecoveryEnabled(true);
// Connection connection = connectionFactory.newConnection();
// connection.addShutdownListener(new ShutdownListener() {
// public void shutdownCompleted(ShutdownSignalException cause) {
// }
// });
// log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
// return connection;
// } catch (Exception e) {
// log.info("connection failed to rabbitmq: " + connection + " for " + exchangeName);
// return null;
// }
// }
//
// public void ackMessage(Long msgId) throws Exception {
// try {
// channel.basicAck(msgId, false);
// } catch (ShutdownSignalException sse) {
// reset();
// String msg = "shutdown signal received while attempting to ack message";
// log.error(msg, sse);
// throw new Exception(msg, sse);
// } catch (Exception e) {
// String s = "could not ack for msgId: " + msgId;
// log.error(s, e);
// throw new Exception(s, e);
// }
// }
//
// public void failMessage(Long msgId) throws Exception {
// if (isReQueueOnFail) {
// failWithRedelivery(msgId);
// } else {
// deadLetter(msgId);
// }
// }
//
// public void failWithRedelivery(Long msgId) throws Exception {
// try {
// channel.basicReject(msgId, true);
// } catch (ShutdownSignalException sse) {
// reset();
// String msg = "shutdown signal received while attempting to fail with redelivery";
// log.error(msg, sse);
// throw new Exception(msg, sse);
// } catch (Exception e) {
// String msg = "could not fail with redelivery for msgId: " + msgId;
// log.error(msg, e);
// throw new Exception(msg, e);
// }
// }
//
// public void deadLetter(Long msgId) throws Exception {
// try {
// channel.basicReject(msgId, false);
// } catch (ShutdownSignalException sse) {
// reset();
// String msg = "shutdown signal received while attempting to fail with no redelivery";
// log.error(msg, sse);
// throw new Exception(msg, sse);
// } catch (Exception e) {
// String msg = "could not fail with dead-lettering (when configured) for msgId: " + msgId;
// log.error(msg, e);
// throw new Exception(msg, e);
// }
// }
//}
| 1,164 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQStatusSubscriber.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.
*/
///*
// *
// * 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.messaging.core.impl;
//
//
//import com.rabbitmq.client.*;
//import org.apache.airavata.common.exception.AiravataException;
//import org.apache.airavata.common.exception.ApplicationSettingsException;
//import org.apache.airavata.common.utils.AiravataUtils;
//import org.apache.airavata.common.utils.ServerSettings;
//import org.apache.airavata.common.utils.ThriftUtils;
//import org.apache.airavata.messaging.core.Subscriber;
//import org.apache.airavata.messaging.core.MessageContext;
//import org.apache.airavata.messaging.core.MessageHandler;
//import org.apache.airavata.messaging.core.MessagingConstants;
//import org.apache.airavata.model.messaging.event.*;
//import org.apache.thrift.TBase;
//import org.apache.thrift.TException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import javax.annotation.Nonnull;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//public class RabbitMQStatusSubscriber implements Subscriber {
// public static final String EXCHANGE_TYPE = "topic";
// private static Logger log = LoggerFactory.getLogger(RabbitMQStatusSubscriber.class);
//
// private String exchangeName;
// private String url;
// private Connection connection;
// private Channel channel;
// private int prefetchCount;
// private Map<String, QueueDetails> queueDetailsMap = new HashMap<String, QueueDetails>();
//
// public RabbitMQStatusSubscriber() throws AiravataException {
// try {
// url = ServerSettings.getSetting(MessagingConstants.RABBITMQ_BROKER_URL);
// exchangeName = ServerSettings.getSetting(MessagingConstants.RABBITMQ_STATUS_EXCHANGE_NAME);
// prefetchCount = Integer.valueOf(ServerSettings.getSetting(MessagingConstants.PREFETCH_COUNT, String.valueOf(64)));
// createConnection();
// } catch (ApplicationSettingsException e) {
// String message = "Failed to get read the required properties from airavata to initialize rabbitmq";
// log.error(message, e);
// throw new AiravataException(message, e);
// }
// }
//
// public RabbitMQStatusSubscriber(String brokerUrl, String exchangeName) throws AiravataException {
// this.exchangeName = exchangeName;
// this.url = brokerUrl;
//
// createConnection();
// }
//
// private void createConnection() throws AiravataException {
// try {
// ConnectionFactory connectionFactory = new ConnectionFactory();
// connectionFactory.setUri(url);
// connectionFactory.setAutomaticRecoveryEnabled(true);
// connection = connectionFactory.newConnection();
// connection.addShutdownListener(new ShutdownListener() {
// public void shutdownCompleted(ShutdownSignalException cause) {
// }
// });
// log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
//
// channel = connection.createChannel();
// channel.basicQos(prefetchCount);
// channel.exchangeDeclare(exchangeName, EXCHANGE_TYPE, false);
//
// } catch (Exception e) {
// String msg = "could not open channel for exchange " + exchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
// }
// }
//
// public String listen(final MessageHandler handler) throws AiravataException {
// try {
// Map<String, Object> props = handler.getProperties();
// final Object routing = props.get(MessagingConstants.RABBIT_ROUTING_KEY);
// if (routing == null) {
// throw new IllegalArgumentException("The routing key must be present");
// }
//
// List<String> keys = new ArrayList<String>();
// if (routing instanceof List) {
// for (Object o : (List)routing) {
// keys.add(o.toString());
// }
// } else if (routing instanceof String) {
// keys.add((String) routing);
// }
//
// String queueName = (String) props.get(MessagingConstants.RABBIT_QUEUE);
// String consumerTag = (String) props.get(MessagingConstants.RABBIT_CONSUMER_TAG);
// if (queueName == null) {
// if (!channel.isOpen()) {
// channel = connection.createChannel();
// channel.exchangeDeclare(exchangeName, "topic", false);
// }
// queueName = channel.queueDeclare().getQueue();
// } else {
// channel.queueDeclare(queueName, true, false, false, null);
// }
//
// final String id = getId(keys, queueName);
// if (queueDetailsMap.containsKey(id)) {
// throw new IllegalStateException("This subscriber is already defined for this Subscriber, " +
// "cannot define the same subscriber twice");
// }
//
// if (consumerTag == null) {
// consumerTag = "default";
// }
//
// // bind all the routing keys
// for (String routingKey : keys) {
// channel.queueBind(queueName, exchangeName, routingKey);
// }
//
// channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
// @Override
// public void handleDelivery(String consumerTag,
// Envelope envelope,
// AMQP.BasicProperties properties,
// byte[] body) {
// Message message = new Message();
//
// try {
// ThriftUtils.createThriftFromBytes(body, message);
// TBase event = null;
// String gatewayId = null;
//
// if (message.getMessageType().equals(MessageType.EXPERIMENT)) {
// ExperimentStatusChangeEvent experimentStatusChangeEvent = new ExperimentStatusChangeEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), experimentStatusChangeEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' with status " +
// experimentStatusChangeEvent.getState());
// event = experimentStatusChangeEvent;
// gatewayId = experimentStatusChangeEvent.getGatewayId();
// } else if (message.getMessageType().equals(MessageType.PROCESS)) {
// ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), processStatusChangeEvent);
// log.debug("Message Recieved with message id :" + message.getMessageId() + " and with " +
// "message type " + message.getMessageType() + " with status " +
// processStatusChangeEvent.getState());
// event = processStatusChangeEvent;
// gatewayId = processStatusChangeEvent.getProcessIdentity().getGatewayId();
// } else if (message.getMessageType().equals(MessageType.TASK)) {
// TaskStatusChangeEvent taskStatusChangeEvent = new TaskStatusChangeEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), taskStatusChangeEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' with status " +
// taskStatusChangeEvent.getState());
// event = taskStatusChangeEvent;
// gatewayId = taskStatusChangeEvent.getTaskIdentity().getGatewayId();
// }else if (message.getMessageType() == MessageType.PROCESSOUTPUT) {
// TaskOutputChangeEvent taskOutputChangeEvent = new TaskOutputChangeEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), taskOutputChangeEvent);
// log.debug(" Message Received with message id '" + message.getMessageId() + "' and with message type '" + message.getMessageType());
// event = taskOutputChangeEvent;
// gatewayId = taskOutputChangeEvent.getTaskIdentity().getGatewayId();
// } else if (message.getMessageType().equals(MessageType.JOB)) {
// JobStatusChangeEvent jobStatusChangeEvent = new JobStatusChangeEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), jobStatusChangeEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' with status " +
// jobStatusChangeEvent.getState());
// event = jobStatusChangeEvent;
// gatewayId = jobStatusChangeEvent.getJobIdentity().getGatewayId();
// } else if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
// TaskSubmitEvent taskSubmitEvent = new TaskSubmitEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), taskSubmitEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' for experimentId: " +
// taskSubmitEvent.getExperimentId() + "and taskId: " + taskSubmitEvent.getTaskId());
// event = taskSubmitEvent;
// gatewayId = taskSubmitEvent.getGatewayId();
// } else if (message.getMessageType().equals(MessageType.TERMINATEPROCESS)) {
// TaskTerminateEvent taskTerminateEvent = new TaskTerminateEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), taskTerminateEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' for experimentId: " +
// taskTerminateEvent.getExperimentId() + "and taskId: " + taskTerminateEvent.getTaskId());
// event = taskTerminateEvent;
// gatewayId = null;
// }
// MessageContext messageContext = new MessageContext(event, message.getMessageType(), message.getMessageId(), gatewayId);
// messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
// messageContext.setIsRedeliver(envelope.isRedeliver());
// handler.onMessage(messageContext);
// } catch (TException e) {
// String msg = "Failed to de-serialize the thrift message, from routing keys and queueName " + id;
// log.warn(msg, e);
// }
// }
// });
// // save the name for deleting the queue
// queueDetailsMap.put(id, new QueueDetails(queueName, keys));
// return id;
// } catch (Exception e) {
// String msg = "could not open channel for exchange " + exchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
// }
// }
//
// public void stopListen(final String id) throws AiravataException {
// QueueDetails details = queueDetailsMap.get(id);
// if (details != null) {
// try {
// for (String key : details.getRoutingKeys()) {
// channel.queueUnbind(details.getQueueName(), exchangeName, key);
// }
// channel.queueDelete(details.getQueueName(), true, true);
// } catch (IOException e) {
// String msg = "could not un-bind queue: " + details.getQueueName() + " for exchange " + exchangeName;
// log.debug(msg);
// }
// }
// }
//
// /**
// * Private class for holding some information about the consumers registered
// */
// private class QueueDetails {
// String queueName;
//
// List<String> routingKeys;
//
// private QueueDetails(String queueName, List<String> routingKeys) {
// this.queueName = queueName;
// this.routingKeys = routingKeys;
// }
//
// public String getQueueName() {
// return queueName;
// }
//
// public List<String> getRoutingKeys() {
// return routingKeys;
// }
// }
//
// private String getId(List<String> routingKeys, String queueName) {
// String id = "";
// for (String key : routingKeys) {
// id = id + "_" + key;
// }
// return id + "_" + queueName;
// }
//
// public void close() {
// if (connection != null) {
// try {
// connection.close();
// } catch (IOException ignore) {
// }
// }
// }
//}
| 1,165 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQStatusPublisher.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.
*/
///*
// *
// * 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.messaging.core.impl;
//
//import org.apache.airavata.common.exception.AiravataException;
//import org.apache.airavata.common.exception.ApplicationSettingsException;
//import org.apache.airavata.common.utils.ServerSettings;
//import org.apache.airavata.common.utils.ThriftUtils;
//import org.apache.airavata.messaging.core.MessageContext;
//import org.apache.airavata.messaging.core.MessagingConstants;
//import org.apache.airavata.messaging.core.Publisher;
//import org.apache.airavata.model.messaging.event.*;
//import org.apache.thrift.TException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class RabbitMQStatusPublisher implements Publisher {
//
// private static Logger log = LoggerFactory.getLogger(RabbitMQStatusPublisher.class);
//
// private RabbitMQProducer rabbitMQProducer;
//
//// StatCounter statCounter = StatCounter.getInstance();
//
// public RabbitMQStatusPublisher() throws AiravataException {
// String brokerUrl;
// String exchangeName;
// try {
// brokerUrl = ServerSettings.getSetting(MessagingConstants.RABBITMQ_BROKER_URL);
// exchangeName = ServerSettings.getSetting(MessagingConstants.RABBITMQ_STATUS_EXCHANGE_NAME);
// } catch (ApplicationSettingsException e) {
// String message = "Failed to get read the required properties from airavata to initialize rabbitmq";
// log.error(message, e);
// throw new AiravataException(message, e);
// }
// rabbitMQProducer = new RabbitMQProducer(brokerUrl, exchangeName);
// rabbitMQProducer.open();
// }
//
// public void publish(MessageContext msgCtx) throws AiravataException {
// try {
// log.info("Publishing status to rabbitmq...");
// byte[] body = ThriftUtils.serializeThriftObject(msgCtx.getEvent());
// Message message = new Message();
// message.setEvent(body);
// message.setMessageId(msgCtx.getMessageId());
// message.setMessageType(msgCtx.getType());
// message.setUpdatedTime(msgCtx.getUpdatedTime().getTime());
// String gatewayId = msgCtx.getGatewayId();
// String routingKey = null;
// if (msgCtx.getType() == MessageType.EXPERIMENT) {
// ExperimentStatusChangeEvent event = (ExperimentStatusChangeEvent) msgCtx.getEvent();
// routingKey = gatewayId + "." + event.getExperimentId();
// } else if (msgCtx.getType() == MessageType.TASK) {
// TaskStatusChangeEvent event = (TaskStatusChangeEvent) msgCtx.getEvent();
// routingKey = gatewayId + "." + event.getTaskIdentity().getExperimentId() + "." +
// event.getTaskIdentity().getProcessId() + "." + event.getTaskIdentity().getTaskId();
// } else if (msgCtx.getType() == MessageType.PROCESSOUTPUT) {
// TaskOutputChangeEvent event = (TaskOutputChangeEvent) msgCtx.getEvent();
// routingKey = gatewayId + "." + event.getTaskIdentity().getExperimentId() + "." +
// event.getTaskIdentity().getProcessId() + "." + event.getTaskIdentity().getTaskId();
// } else if (msgCtx.getType() == MessageType.PROCESS) {
// ProcessStatusChangeEvent event = (ProcessStatusChangeEvent) msgCtx.getEvent();
// ProcessIdentifier processIdentifier = event.getProcessIdentity();
// routingKey = gatewayId + "." + processIdentifier.getExperimentId() + "." + processIdentifier.getProcessId();
// } else if (msgCtx.getType() == MessageType.JOB) {
// JobStatusChangeEvent event = (JobStatusChangeEvent) msgCtx.getEvent();
// JobIdentifier identity = event.getJobIdentity();
// routingKey = gatewayId + "." + identity.getExperimentId() + "." +
// identity.getProcessId() + "." +
// identity.getTaskId() + "." +
// identity.getJobId();
// }
// byte[] messageBody = ThriftUtils.serializeThriftObject(message);
// rabbitMQProducer.send(messageBody, routingKey);
//// statCounter.add(message);
// } catch (TException e) {
// String msg = "Error while deserializing the object";
// log.error(msg, e);
// throw new AiravataException(msg, e);
// } catch (Exception e) {
// String msg = "Error while sending to rabbitmq";
// log.error(msg, e);
// throw new AiravataException(msg, e);
// }
// }
//}
| 1,166 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/impl/RabbitMQProcessLaunchConsumer.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.
*/
///*
// *
// * 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.messaging.core.impl;
//
//import com.rabbitmq.client.*;
//import org.apache.airavata.common.exception.AiravataException;
//import org.apache.airavata.common.exception.ApplicationSettingsException;
//import org.apache.airavata.common.utils.AiravataUtils;
//import org.apache.airavata.common.utils.ServerSettings;
//import org.apache.airavata.common.utils.ThriftUtils;
//import org.apache.airavata.messaging.core.MessageContext;
//import org.apache.airavata.messaging.core.MessageHandler;
//import org.apache.airavata.messaging.core.MessagingConstants;
//import org.apache.airavata.model.messaging.event.*;
//import org.apache.thrift.TBase;
//import org.apache.thrift.TException;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//public class RabbitMQProcessLaunchConsumer {
// private final static Logger logger = LoggerFactory.getLogger(RabbitMQProcessLaunchConsumer.class);
// private static Logger log = LoggerFactory.getLogger(RabbitMQStatusSubscriber.class);
//
// private String taskLaunchExchangeName;
// private String url;
// private Connection connection;
// private Channel channel;
// private Map<String, QueueDetails> queueDetailsMap = new HashMap<String, QueueDetails>();
// private boolean durableQueue;
// private MessageHandler messageHandler;
// private int prefetchCount;
//
//
// public RabbitMQProcessLaunchConsumer() throws AiravataException {
// try {
// url = ServerSettings.getSetting(MessagingConstants.RABBITMQ_BROKER_URL);
// durableQueue = Boolean.parseBoolean(ServerSettings.getSetting(MessagingConstants.DURABLE_QUEUE));
// taskLaunchExchangeName = ServerSettings.getSetting(MessagingConstants.RABBITMQ_TASK_LAUNCH_EXCHANGE_NAME);
// prefetchCount = Integer.valueOf(ServerSettings.getSetting(MessagingConstants.PREFETCH_COUNT, String.valueOf(64)));
// createConnection();
// } catch (ApplicationSettingsException e) {
// String message = "Failed to get read the required properties from airavata to initialize rabbitmq";
// log.error(message, e);
// throw new AiravataException(message, e);
// }
// }
//
// public RabbitMQProcessLaunchConsumer(String brokerUrl, String exchangeName) throws AiravataException {
// this.taskLaunchExchangeName = exchangeName;
// this.url = brokerUrl;
//
// createConnection();
// }
//
// private void createConnection() throws AiravataException {
// try {
// ConnectionFactory connectionFactory = new ConnectionFactory();
// connectionFactory.setUri(url);
// connectionFactory.setAutomaticRecoveryEnabled(true);
// connection = connectionFactory.newConnection();
// connection.addShutdownListener(new ShutdownListener() {
// public void shutdownCompleted(ShutdownSignalException cause) {
// }
// });
// log.info("connected to rabbitmq: " + connection + " for " + taskLaunchExchangeName);
//
// channel = connection.createChannel();
// channel.basicQos(prefetchCount);
//
//// channel.exchangeDeclare(taskLaunchExchangeName, "fanout");
//
// } catch (Exception e) {
// String msg = "could not open channel for exchange " + taskLaunchExchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
// }
// }
//
// public void reconnect() throws AiravataException{
// if(messageHandler!=null) {
// try {
// listen(messageHandler);
// } catch (AiravataException e) {
// String msg = "could not open channel for exchange " + taskLaunchExchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
//
// }
// }
// }
// public String listen(final MessageHandler handler) throws AiravataException {
// try {
// messageHandler = handler;
// Map<String, Object> props = handler.getProperties();
// final Object routing = props.get(MessagingConstants.RABBIT_ROUTING_KEY);
// if (routing == null) {
// throw new IllegalArgumentException("The routing key must be present");
// }
// List<String> keys = new ArrayList<String>();
// if (routing instanceof List) {
// for (Object o : (List)routing) {
// keys.add(o.toString());
// }
// } else if (routing instanceof String) {
// keys.add((String) routing);
// }
//
// String queueName = (String) props.get(MessagingConstants.RABBIT_QUEUE);
// String consumerTag = (String) props.get(MessagingConstants.RABBIT_CONSUMER_TAG);
// if (queueName == null) {
// if (!channel.isOpen()) {
// channel = connection.createChannel();
// channel.basicQos(prefetchCount);
//// channel.exchangeDeclare(taskLaunchExchangeName, "fanout");
// }
// queueName = channel.queueDeclare().getQueue();
// } else {
//
// channel.queueDeclare(queueName, durableQueue, false, false, null);
// }
//
// final String id = getId(keys, queueName);
// if (queueDetailsMap.containsKey(id)) {
// throw new IllegalStateException("This subscriber is already defined for this Subscriber, " +
// "cannot define the same subscriber twice");
// }
//
// if (consumerTag == null) {
// consumerTag = "default";
// }
//
// // bind all the routing keys
//// for (String routingKey : keys) {
//// channel.queueBind(queueName, taskLaunchExchangeName, routingKey);
//// }
// // autoAck=false, we will ack after task is done
// channel.basicConsume(queueName, false, consumerTag, new QueueingConsumer(channel) {
// @Override
// public void handleDelivery(String consumerTag,
// Envelope envelope,
// AMQP.BasicProperties properties,
// byte[] body) {
// Message message = new Message();
//
// try {
// ThriftUtils.createThriftFromBytes(body, message);
// TBase event = null;
// String gatewayId = null;
// long deliveryTag = envelope.getDeliveryTag();
// if (message.getMessageType().equals(MessageType.LAUNCHPROCESS)) {
// ProcessSubmitEvent processSubmitEvent = new ProcessSubmitEvent();
// ThriftUtils.createThriftFromBytes(message.getEvent(), processSubmitEvent);
// log.debug(" Message Received with message id '" + message.getMessageId()
// + "' and with message type '" + message.getMessageType() + "' for experimentId:" +
// " " +
// processSubmitEvent.getProcessId());
// event = processSubmitEvent;
// gatewayId = processSubmitEvent.getGatewayId();
// MessageContext messageContext = new MessageContext(event, message.getMessageType(),
// message.getMessageId(), gatewayId, deliveryTag);
// messageContext.setUpdatedTime(AiravataUtils.getTime(message.getUpdatedTime()));
// messageContext.setIsRedeliver(envelope.isRedeliver());
// handler.onMessage(messageContext);
// } else {
// log.error("{} message type is not handle in ProcessLaunch Subscriber. Sending ack for " +
// "delivery tag {} ", message.getMessageType().name(), deliveryTag);
// sendAck(deliveryTag);
// }
// } catch (TException e) {
// String msg = "Failed to de-serialize the thrift message, from routing keys and queueName " + id;
// log.warn(msg, e);
// }
// }
//
// @Override
// public void handleCancel(String consumerTag) throws IOException {
// super.handleCancel(consumerTag);
// log.info("Subscriber cancelled : " + consumerTag);
// }
// });
//
// // save the name for deleting the queue
// queueDetailsMap.put(id, new QueueDetails(queueName, keys));
// return id;
// } catch (Exception e) {
// String msg = "could not open channel for exchange " + taskLaunchExchangeName;
// log.error(msg);
// throw new AiravataException(msg, e);
// }
// }
//
// public void stopListen(final String id) throws AiravataException {
// QueueDetails details = queueDetailsMap.get(id);
// if (details != null) {
// try {
// for (String key : details.getRoutingKeys()) {
// channel.queueUnbind(details.getQueueName(), taskLaunchExchangeName, key);
// }
// } catch (IOException e) {
// String msg = "could not un-bind queue: " + details.getQueueName() + " for exchange " + taskLaunchExchangeName;
// log.debug(msg);
// }
// }
// }
//
// /**
// * Private class for holding some information about the consumers registered
// */
// private class QueueDetails {
// String queueName;
//
// List<String> routingKeys;
//
// private QueueDetails(String queueName, List<String> routingKeys) {
// this.queueName = queueName;
// this.routingKeys = routingKeys;
// }
//
// public String getQueueName() {
// return queueName;
// }
//
// public List<String> getRoutingKeys() {
// return routingKeys;
// }
// }
//
// private String getId(List<String> routingKeys, String queueName) {
// String id = "";
// for (String key : routingKeys) {
// id = id + "_" + key;
// }
// return id + "_" + queueName;
// }
//
// public void close() {
// if (connection != null) {
// try {
// connection.close();
// } catch (IOException ignore) {
// }
// }
// }
// public boolean isOpen(){
// if(connection!=null){
// return connection.isOpen();
// }
// return false;
// }
//
// public void sendAck(long deliveryTag){
// try {
// if (channel.isOpen()){
// channel.basicAck(deliveryTag,false);
// }else {
// channel = connection.createChannel();
// channel.basicQos(prefetchCount);
// channel.basicAck(deliveryTag, false);
// }
// } catch (IOException e) {
// logger.error(e.getMessage(), e);
// }
// }
//}
| 1,167 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/util/DBEventPublisherUtils.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.messaging.core.util;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.DBEventManagerConstants;
import org.apache.airavata.common.utils.DBEventService;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.model.dbevent.CrudType;
import org.apache.airavata.model.dbevent.DBEventMessage;
import org.apache.airavata.model.dbevent.DBEventMessageContext;
import org.apache.airavata.model.dbevent.DBEventPublisher;
import org.apache.airavata.model.dbevent.DBEventPublisherContext;
import org.apache.airavata.model.dbevent.DBEventType;
import org.apache.airavata.model.dbevent.EntityType;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.thrift.TBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DBEventPublisherUtils
*/
public class DBEventPublisherUtils {
private final static Logger logger = LoggerFactory.getLogger(DBEventPublisherUtils.class);
private Publisher dbEventPublisher = null;
private DBEventService publisherService;
public DBEventPublisherUtils(DBEventService dbEventService) {
this.publisherService = dbEventService;
}
/**
* Publish DB Event for given entity.
* @param entityType
* @param crudType
* @param entityModel
*/
public void publish(EntityType entityType, CrudType crudType, TBase entityModel) throws AiravataException {
getDbEventPublisher().publish(getDBEventMessageContext(entityType, crudType, entityModel),
DBEventManagerConstants.getRoutingKey(DBEventService.DB_EVENT.toString()));
}
/**
* Returns singleton instance of dbEventPublisher
* @return
* @throws AiravataException
*/
private Publisher getDbEventPublisher() throws AiravataException {
if(null == dbEventPublisher){
synchronized (this){
if(null == dbEventPublisher){
logger.info("Creating DB Event publisher.....");
dbEventPublisher = MessagingFactory.getDBEventPublisher();
logger.info("DB Event publisher created");
}
}
}
return dbEventPublisher;
}
/**
* Constructs the dbEventMessageContext
* @param entityType
* @param crudType
* @param entityModel
* @return
* @throws AiravataException
*/
private MessageContext getDBEventMessageContext(EntityType entityType, CrudType crudType, TBase entityModel) throws AiravataException {
try {
// set the publisherContext
DBEventMessage dbEventMessage = new DBEventMessage();
DBEventPublisherContext publisherContext = new DBEventPublisherContext();
publisherContext.setCrudType(crudType);
publisherContext.setEntityDataModel(ThriftUtils.serializeThriftObject(entityModel));
publisherContext.setEntityType(entityType);
// create dbEventPublisher with publisherContext
DBEventPublisher dbEventPublisher = new DBEventPublisher();
dbEventPublisher.setPublisherContext(publisherContext);
// set messageContext to dbEventPublisher
DBEventMessageContext dbMessageContext = DBEventMessageContext.publisher(dbEventPublisher);
// set dbEventMessage with messageContext
dbEventMessage.setDbEventType(DBEventType.PUBLISHER);
dbEventMessage.setPublisherService(this.publisherService.toString());
dbEventMessage.setMessageContext(dbMessageContext);
// construct and return messageContext
return new MessageContext(dbEventMessage, MessageType.DB_EVENT, "", "");
} catch (Exception ex) {
throw new AiravataException(ex.getMessage(), ex);
}
}
}
| 1,168 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/stats/LatencyWriterTask.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.messaging.core.stats;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
public class LatencyWriterTask extends TimerTask {
private File file;
private FileOutputStream fos;
private BufferedWriter bw;
public void setFile(File file) {
this.file = file;
}
@Override
public void run() {
try {
System.out.println("########### Latency Write Task ############");
StatCounter statCounter = StatCounter.getInstance();
Map<String, Long> messageTimeStamp = statCounter.getMessageTimeStamp();
fos = new FileOutputStream(file, false);
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (String msgId : messageTimeStamp.keySet()){
bw.write(msgId + " :" + String.valueOf(messageTimeStamp.get(msgId)));
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,169 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/stats/CountWriterTask.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.messaging.core.stats;
import java.io.*;
import java.util.List;
import java.util.TimerTask;
public class CountWriterTask extends TimerTask {
private File file;
private FileOutputStream fos;
private BufferedWriter bw;
public void setFile(File file) {
this.file = file;
}
@Override
public void run() {
try {
StatCounter statCounter = StatCounter.getInstance();
List<Long> contPer10S = statCounter.getMessageContPer10S();
fos = new FileOutputStream(file, false);
bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i = 0; i < contPer10S.size(); i++) {
bw.write(String.valueOf(i+1) + " :" + String.valueOf(contPer10S.get(i)));
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,170 |
0 | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core | Create_ds/airavata/modules/messaging/core/src/main/java/org/apache/airavata/messaging/core/stats/StatCounter.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.messaging.core.stats;
import org.apache.airavata.model.messaging.event.Message;
import java.io.*;
import java.util.*;
public class StatCounter {
private static StatCounter ourInstance = new StatCounter();
private long msgCount;
private long period = 10*1000;
private long msgCountForPeriod;
private long bucketStartTime = 0;
private File file1;
private File file2;
private List<Long> messageContPer10S = new ArrayList<Long>();
private Map<String, Long> messageTimeStamp = new HashMap<String, Long>();
public static StatCounter getInstance() {
return ourInstance;
}
public long getMsgCount() {
return msgCount;
}
public void setMsgCount(long msgCount) {
this.msgCount = msgCount;
}
public List<Long> getMessageContPer10S() {
return messageContPer10S;
}
public void setMessageContPer10S(List<Long> messageContPer10S) {
this.messageContPer10S = messageContPer10S;
}
private StatCounter() {
file1 = new File("/tmp/results");
file2 = new File("/tmp/latency");
Timer counterTimer = new Timer();
Timer latencyTimer = new Timer();
CountWriterTask writerTask = new CountWriterTask();
writerTask.setFile(file1);
LatencyWriterTask latencyWriterTask = new LatencyWriterTask();
latencyWriterTask.setFile(file2);
counterTimer.scheduleAtFixedRate(writerTask, 0, 60 * 1000);
latencyTimer.scheduleAtFixedRate(latencyWriterTask, 0, 60 * 1000);
}
public void add (Message message) {
messageTimeStamp.put(message.getMessageId(), System.currentTimeMillis());
if (System.currentTimeMillis() - bucketStartTime < period) {
msgCountForPeriod++;
} else {
messageContPer10S.add(msgCountForPeriod);
bucketStartTime = System.currentTimeMillis();
msgCountForPeriod = 1;
}
msgCount++;
}
public long getMsgCountForPeriod() {
return msgCountForPeriod;
}
public void setMsgCountForPeriod(long msgCountForPeriod) {
this.msgCountForPeriod = msgCountForPeriod;
}
public Map<String, Long> getMessageTimeStamp() {
return messageTimeStamp;
}
public void setMessageTimeStamp(Map<String, Long> messageTimeStamp) {
this.messageTimeStamp = messageTimeStamp;
}
}
| 1,171 |
0 | Create_ds/airavata/modules/messaging/client/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/client/src/main/java/org/apache/airavata/messaging/client/TestReader.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.messaging.client;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
//import java.util.stream.Stream;
public class TestReader {
// public static void main(String[] args) throws IOException {
// String fileName = "/Users/chathuri/dev/airavata/docs/messaging_framework/gw111/results_350";
// File file = new File("/Users/chathuri/dev/airavata/docs/messaging_framework/gw111/processed/results_350");
// BufferedReader br = null;
// List<Long> count = new ArrayList<Long>();
// FileOutputStream fos;
// BufferedWriter bw;
// try {
// br = new BufferedReader(new FileReader(fileName));
//// String line = br.readLine();
// Stream<String> lines = br.lines();
// Object[] objects = lines.toArray();
// for (int i = 0; i < objects.length; i++){
// String line = (String)objects[i];
// if (line.contains(":")){
// String[] split = line.split(":");
// count.add(Long.valueOf(split[1]));
// }
// }
// fos = new FileOutputStream(file, false);
// bw = new BufferedWriter(new OutputStreamWriter(fos));
// long allCount = 0;
// for (int i = 0; i < count.size(); i++) {
// if (i % 10 != 9){
// allCount += count.get(i);
// }else {
// bw.write(String.valueOf(i + 1) + " :" + String.valueOf(allCount));
// bw.newLine();
// allCount = 0;
// }
// }
// bw.flush();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// br.close();
// }
// }
}
| 1,172 |
0 | Create_ds/airavata/modules/messaging/client/src/main/java/org/apache/airavata/messaging | Create_ds/airavata/modules/messaging/client/src/main/java/org/apache/airavata/messaging/client/RabbitMQListener.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.messaging.client;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageHandler;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Subscriber;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.JobStatusChangeEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.TaskStatusChangeEvent;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class RabbitMQListener {
public static final String RABBITMQ_BROKER_URL = "rabbitmq.broker.url";
public static final String RABBITMQ_EXCHANGE_NAME = "rabbitmq.exchange.name";
private final static Logger logger = LoggerFactory.getLogger(RabbitMQListener.class);
private static String gatewayId = "*";
private static String experimentId = "*";
private static String jobId = "*";
private static LEVEL level = LEVEL.ALL;
public static void main(String[] args) {
File file = new File("/tmp/latency_client");
parseArguments(args);
try {
FileOutputStream fos = new FileOutputStream(file, false);
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String brokerUrl = ServerSettings.getSetting(RABBITMQ_BROKER_URL);
System.out.println("broker url " + brokerUrl);
final String exchangeName = ServerSettings.getSetting(RABBITMQ_EXCHANGE_NAME);
List<String> routingKeys = getRoutingKeys(level);
Subscriber subscriber = MessagingFactory.getSubscriber(message -> {}, routingKeys, Type.STATUS);
} catch (ApplicationSettingsException e) {
logger.error("Error reading airavata server properties", e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private static MessageHandler getMessageHandler(final BufferedWriter bw) {
return message -> {
try {
long latency = System.currentTimeMillis() - message.getUpdatedTime().getTime();
bw.write(message.getMessageId() + " :" + latency);
bw.newLine();
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
if (message.getType().equals(MessageType.EXPERIMENT)) {
try {
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent();
TBase messageEvent = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(messageEvent);
ThriftUtils.createThriftFromBytes(bytes, event);
System.out.println(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getType() + "' and with state : '" + event.getState().toString() +
" for Gateway " + event.getGatewayId());
} catch (TException e) {
logger.error(e.getMessage(), e);
}
} else if (message.getType().equals(MessageType.PROCESS)) {
/*try {
WorkflowNodeStatusChangeEvent event = new WorkflowNodeStatusChangeEvent();
TBase messageEvent = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(messageEvent);
ThriftUtils.createThriftFromBytes(bytes, event);
System.out.println(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getType() + "' and with state : '" + event.getState().toString() +
" for Gateway " + event.getWorkflowNodeIdentity().getGatewayId());
} catch (TException e) {
logger.error(e.getMessage(), e);
}*/
} else if (message.getType().equals(MessageType.TASK)) {
try {
TaskStatusChangeEvent event = new TaskStatusChangeEvent();
TBase messageEvent = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(messageEvent);
ThriftUtils.createThriftFromBytes(bytes, event);
System.out.println(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getType() + "' and with state : '" + event.getState().toString() +
" for Gateway " + event.getTaskIdentity().getGatewayId());
} catch (TException e) {
logger.error(e.getMessage(), e);
}
} else if (message.getType().equals(MessageType.JOB)) {
try {
JobStatusChangeEvent event = new JobStatusChangeEvent();
TBase messageEvent = message.getEvent();
byte[] bytes = ThriftUtils.serializeThriftObject(messageEvent);
ThriftUtils.createThriftFromBytes(bytes, event);
System.out.println(" Message Received with message id '" + message.getMessageId()
+ "' and with message type '" + message.getType() + "' and with state : '" + event.getState().toString() +
" for Gateway " + event.getJobIdentity().getGatewayId());
} catch (TException e) {
logger.error(e.getMessage(), e);
}
}
};
}
private static List<String> getRoutingKeys(LEVEL level) {
List<String> routingKeys = new ArrayList<String>();
switch (level) {
case ALL:
routingKeys.add("*");
routingKeys.add("*.*");
routingKeys.add("*.*.*");
routingKeys.add("*.*.*.*");
routingKeys.add("*.*.*.*.*");
break;
case GATEWAY:
routingKeys.add(gatewayId);
routingKeys.add(gatewayId + ".*");
routingKeys.add(gatewayId + ".*.*");
routingKeys.add(gatewayId + ".*.*.*");
routingKeys.add(gatewayId + ".*.*.*.*");
break;
case EXPERIMENT:
routingKeys.add(gatewayId);
routingKeys.add(gatewayId + "." + experimentId);
routingKeys.add(gatewayId + "." + experimentId + ".*");
routingKeys.add(gatewayId + "." + experimentId + ".*.*");
routingKeys.add(gatewayId + "." + experimentId + ".*.*.*");
break;
case JOB:
routingKeys.add(gatewayId);
routingKeys.add(gatewayId + "." + experimentId);
routingKeys.add(gatewayId + "." + experimentId + ".*");
routingKeys.add(gatewayId + "." + experimentId + ".*.*");
routingKeys.add(gatewayId + "." + experimentId + ".*." + jobId);
break;
default:
break;
}
return routingKeys;
}
public static void parseArguments(String[] args) {
try {
Options options = new Options();
options.addOption("gId", true, "Gateway ID");
options.addOption("eId", true, "Experiment ID");
options.addOption("jId", true, "Job ID");
options.addOption("a", false, "All Notifications");
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.getOptions() == null || cmd.getOptions().length == 0) {
logger.info("You have not specified any options. We assume you need to listen to all the messages...");
level = LEVEL.ALL;
gatewayId = "*";
}
if (cmd.hasOption("a")) {
logger.info("Listening to all the messages...");
level = LEVEL.ALL;
gatewayId = "*";
} else {
gatewayId = cmd.getOptionValue("gId");
if (gatewayId == null) {
gatewayId = "*";
logger.info("You have not specified a gateway id. We assume you need to listen to all the messages...");
} else {
level = LEVEL.GATEWAY;
}
experimentId = cmd.getOptionValue("eId");
if (experimentId == null && !gatewayId.equals("*")) {
experimentId = "*";
logger.info("You have not specified a experiment id. We assume you need to listen to all the messages for the gateway with id " + gatewayId);
} else if (experimentId == null && gatewayId.equals("*")) {
experimentId = "*";
logger.info("You have not specified a experiment id and a gateway id. We assume you need to listen to all the messages...");
} else {
level = LEVEL.EXPERIMENT;
}
jobId = cmd.getOptionValue("jId");
if (jobId == null && !gatewayId.equals("*") && !experimentId.equals("*")) {
jobId = "*";
logger.info("You have not specified a job id. We assume you need to listen to all the messages for the gateway with id " + gatewayId
+ " with experiment id : " + experimentId);
} else if (jobId == null && gatewayId.equals("*") && experimentId.equals("*")) {
jobId = "*";
logger.info("You have not specified a job Id or experiment Id or a gateway Id. We assume you need to listen to all the messages...");
} else {
level = LEVEL.JOB;
}
}
} catch (ParseException e) {
logger.error("Error while reading command line parameters", e);
}
}
private enum LEVEL {
ALL,
GATEWAY,
EXPERIMENT,
JOB;
}
}
| 1,173 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/NewOrchestratorTest.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.orchestrator.core;
public class NewOrchestratorTest extends BaseOrchestratorTest {
// private static final Logger log = LoggerFactory.getLogger(NewOrchestratorTest.class);
//
// private Orchestrator orchestrator;
// private List<TaskDetails> tasks;
//
// @BeforeTest
// public void setUp() throws Exception {
// AiravataUtils.setExecutionAsServer();
// super.setUp();
// orchestrator = new SimpleOrchestratorImpl();
// // System.setProperty("myproxy.user", "ogce");
//// System.setProperty("myproxy.pass", "");
//// System.setProperty("trusted.cert.location", "/Users/lahirugunathilake/Downloads/certificates");
// //this is the same propertySystem.getProperty("myproxy.user");
//// System.setProperty("myproxy.pass",System.getProperty("myproxy.password"));
//// System.setProperty("trusted.cert.location",System.getProperty("gsi.working.directory"));
// }
//
//
//
// @Test
// public void localHostTest() throws Exception {
// // creating host description
// List<DataObjectType> exInputs = new ArrayList<DataObjectType>();
// DataObjectType input = new DataObjectType();
// input.setKey("echo_input");
// input.setType(DataType.STRING);
// input.setValue("echo_output=Hello World");
// exInputs.add(input);
//
// List<DataObjectType> exOut = new ArrayList<DataObjectType>();
// DataObjectType output = new DataObjectType();
// output.setKey("echo_output");
// output.setType(DataType.STRING);
// output.setValue("");
// exOut.add(output);
//
// Experiment simpleExperiment =
// ExperimentModelUtil.createSimpleExperiment("default", "admin", "echoExperiment", "SimpleEcho0", "SimpleEcho0", exInputs);
// simpleExperiment.setExperimentOutputs(exOut);
//
// WorkflowNodeDetails test = ExperimentModelUtil.createWorkflowNode("test", null);
// ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("localhost", 1, 1, 1, "normal", 0, 0, 1, "sds128");
// scheduling.setResourceHostId("localhost");
// UserConfigurationData userConfigurationData = new UserConfigurationData();
// userConfigurationData.setAiravataAutoSchedule(false);
// userConfigurationData.setOverrideManualScheduledParams(false);
// userConfigurationData.setComputationalResourceScheduling(scheduling);
// simpleExperiment.setUserConfigurationData(userConfigurationData);
//
// Registry defaultRegistry = RegistryFactory.getDefaultExpCatalog();
// String experimentId = (String)defaultRegistry.add(ParentDataType.EXPERIMENT, simpleExperiment);
//
// simpleExperiment.setExperimentID(experimentId);
// tasks = orchestrator.createTasks(experimentId);
// for(TaskDetails details:tasks) {
// orchestrator.launchProcess(simpleExperiment,test, details,null);
// }
// }
//
// private AiravataAPI getAiravataAPI() {
// AiravataAPI airavataAPI = null;
// try {
// String systemUserName = ServerSettings.getSystemUser();
// String gateway = ServerSettings.getSystemUserGateway();
// airavataAPI = AiravataAPIFactory.getAPI(gateway, systemUserName);
// } catch (ApplicationSettingsException e) {
// e.printStackTrace();
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace();
// }
// return airavataAPI;
// }
}
| 1,174 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/OrchestratorTestWithGRAM.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.orchestrator.core;
public class OrchestratorTestWithGRAM extends BaseOrchestratorTest {
// private static final Logger log = LoggerFactory.getLogger(OrchestratorTestWithGRAM.class);
//
// private Orchestrator orchestrator;
//
// private String experimentID;
//
// @BeforeTest
// public void setUp() throws Exception {
// AiravataUtils.setExecutionAsServer();
// super.setUp();
// orchestrator = new SimpleOrchestratorImpl();
// createJobRequestWithDocuments();
// }
//
// private void createJobRequestWithDocuments() throws Exception{
// //Using new airavata-api methods to store experiment metadata
//// BasicMetadata basicMetadata = new BasicMetadata();
//// basicMetadata.setExperimentName("test-trestles");
//// basicMetadata.setUserName("admin");
//// basicMetadata.setUserNameIsSet(true);
//// basicMetadata.setProjectID("default");
////
//// AdvancedInputDataHandling advancedInputDataHandling = new AdvancedInputDataHandling();
//// AdvancedOutputDataHandling advancedOutputDataHandling = new AdvancedOutputDataHandling();
//// ComputationalResourceScheduling computationalResourceScheduling = new ComputationalResourceScheduling();
//// QualityOfServiceParams qualityOfServiceParams = new QualityOfServiceParams();
//// ConfigurationData configurationData = new ConfigurationData();
////
//// HashMap<String, String> exInputs = new HashMap<String, String>();
//// exInputs.put("echo_input", "echo_output=hello");
////
//// configurationData.setExperimentInputs(exInputs);
//// configurationData.setAdvanceInputDataHandling(advancedInputDataHandling);
//// configurationData.setAdvanceOutputDataHandling(advancedOutputDataHandling);
//// configurationData.setComputationalResourceScheduling(computationalResourceScheduling);
//// configurationData.setQosParams(qualityOfServiceParams);
//// configurationData.setApplicationId("SimpleEcho1");
////
//// Registry registry = new RegistryImpl();
//// experimentID = (String) registry.add(ParentDataType.EXPERIMENT, basicMetadata);
//// registry.add(ChildDataType.EXPERIMENT_CONFIGURATION_DATA, configurationData, experimentID);
// }
//
// @Test
// public void noDescriptorTest() throws Exception {
//
//// boolean b = orchestrator.launchProcess(experimentID);
////
//// if (b) {
//// Assert.assertTrue(true);
//// } else {
//// Assert.assertFalse(true);
//// }
// }
}
| 1,175 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/ValidatorTest.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.
*/
///*
// *
// * 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.orchestrator.core;
//
//import org.apache.airavata.common.utils.AiravataUtils;
//import org.apache.airavata.model.error.LaunchValidationException;
//import org.apache.airavata.model.util.ExperimentModelUtil;
//import org.apache.airavata.model.experiment.*;
//import org.apache.airavata.orchestrator.core.utils.OrchestratorConstants;
//import org.apache.airavata.orchestrator.cpi.Orchestrator;
//import org.apache.airavata.orchestrator.cpi.impl.SimpleOrchestratorImpl;
//import org.apache.airavata.registry.core.experiment.registry.jpa.impl.RegistryFactory;
//import org.apache.airavata.registry.cpi.ParentDataType;
//import org.apache.airavata.registry.cpi.Registry;
//import org.junit.Assert;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.testng.annotations.BeforeTest;
//import org.testng.annotations.Test;
//
//import java.util.ArrayList;
//import java.util.List;
//
//public class ValidatorTest extends BaseOrchestratorTest {
// private static final Logger log = LoggerFactory.getLogger(NewOrchestratorTest.class);
//
// private Orchestrator orchestrator;
// private List<TaskDetails> tasks;
//
// @BeforeTest
// public void setUp() throws Exception {
// AiravataUtils.setExecutionAsServer();
// super.setUp();
// System.setProperty(OrchestratorConstants.JOB_VALIDATOR,"org.apache.airavata.orchestrator.core.util.TestValidator,org.apache.airavata.orchestrator.core.util.SecondValidator");
// System.setProperty("enable.validation", "true");
// orchestrator = new SimpleOrchestratorImpl();
// }
//
//
//
// @Test
// public void testValidator() throws Exception {
// // creating host description
// List<DataObjectType> exInputs = new ArrayList<DataObjectType>();
// DataObjectType input = new DataObjectType();
// input.setKey("echo_input");
// input.setType(DataType.STRING);
// input.setValue("echo_output=Hello World");
// exInputs.add(input);
//
// List<DataObjectType> exOut = new ArrayList<DataObjectType>();
// DataObjectType output = new DataObjectType();
// output.setKey("echo_output");
// output.setType(DataType.STRING);
// output.setValue("");
// exOut.add(output);
//
// Experiment simpleExperiment =
// ExperimentModelUtil.createSimpleExperiment("default", "admin", "echoExperiment", "SimpleEcho0", "SimpleEcho0", exInputs);
// simpleExperiment.setExperimentOutputs(exOut);
//
// WorkflowNodeDetails test = ExperimentModelUtil.createWorkflowNode("test", null);
// ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("localhost", 1, 1, 1, "normal", 0, 0, 1, "sds128");
// scheduling.setResourceHostId("localhost");
// UserConfigurationData userConfigurationData = new UserConfigurationData();
// userConfigurationData.setAiravataAutoSchedule(false);
// userConfigurationData.setOverrideManualScheduledParams(false);
// userConfigurationData.setComputationalResourceScheduling(scheduling);
// simpleExperiment.setUserConfigurationData(userConfigurationData);
//
// Registry defaultRegistry = RegistryFactory.getDefaultExpCatalog();
// String experimentId = (String)defaultRegistry.add(ParentDataType.EXPERIMENT, simpleExperiment);
//
// simpleExperiment.setExperimentID(experimentId);
// tasks = orchestrator.createTasks(experimentId);
//
// Assert.assertTrue(orchestrator.validateExperiment(simpleExperiment, test, tasks.get(0)).isValidationState());
//
// simpleExperiment.setExperimentID(null);
//
// try {
// orchestrator.validateExperiment(simpleExperiment, test, tasks.get(0)).isValidationState();
// }catch(LaunchValidationException e){
// Assert.assertTrue(true);
// }
// tasks.get(0).setTaskID(null);
// try {
// orchestrator.validateExperiment(simpleExperiment, test, tasks.get(0));
// }catch (LaunchValidationException e){
// Assert.assertTrue(true);
// }
// }
//
//}
| 1,176 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/BaseOrchestratorTest.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.orchestrator.core;
//import org.apache.airavata.client.tools.DocumentCreatorNew;
public class BaseOrchestratorTest {
/* private GatewayResource gatewayResource;
private WorkerResource workerResource;
private UserResource userResource;
private Initialize initialize;
private DocumentCreatorNew documentCreator;
public void setUp() throws Exception {
initialize = new Initialize("registry-derby.sql");
initialize.initializeDB();
gatewayResource = (GatewayResource) ResourceUtils.getGateway(ServerSettings.getSystemUserGateway());
workerResource = (WorkerResource) ResourceUtils.getWorker(gatewayResource.getGatewayName(), ServerSettings.getDefaultUser());
userResource = new UserResource();
userResource.setUserName(ServerSettings.getDefaultUser());
userResource.setPassword(ServerSettings.getDefaultUser());
documentCreator = new DocumentCreatorNew(getAiravataClient());
documentCreator.createLocalHostDocs();
documentCreator.createPBSDocsForOGCE_Echo();
}
public void tearDown() throws Exception {
initialize.stopDerbyServer();
}
public GatewayResource getGatewayResource() {
return gatewayResource;
}
public WorkerResource getWorkerResource() {
return workerResource;
}
public UserResource getUserResource() {
return userResource;
}
private Airavata.Client getAiravataClient() {
Airavata.Client client = null;
try {
client = AiravataClientFactory.createAiravataClient("localhost", 8930);
} catch (AiravataClientConnectException e) {
e.printStackTrace();
}
return client;
}
public DocumentCreatorNew getDocumentCreator() {
return documentCreator;
}
public void setDocumentCreator(DocumentCreatorNew documentCreator) {
this.documentCreator = documentCreator;
}
private void settingServerProperties(){
}*/
}
| 1,177 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/OrchestratorTestWithMyProxyAuth.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.orchestrator.core;
public class OrchestratorTestWithMyProxyAuth extends BaseOrchestratorTest {
// private static final Logger log = LoggerFactory.getLogger(NewOrchestratorTest.class);
//
// private Orchestrator orchestrator;
//
// private String experimentID;
//
// private List<TaskDetails> tasks;
//
// @BeforeTest
// public void setUp() throws Exception {
// AiravataUtils.setExecutionAsServer();
// super.setUp();
// orchestrator = new SimpleOrchestratorImpl();
//// System.setProperty("myproxy.username", "ogce");
//// System.setProperty("myproxy.password", "");
// System.setProperty("trusted.cert.location", "/Users/lahirugunathilake/Downloads/certificates");
//// System.setProperty("trusted.cert.location",System.getProperty("gsi.working.directory"));
// }
//
// @Test
// public void noDescriptorTest() throws Exception {
// List<DataObjectType> exInputs = new ArrayList<DataObjectType>();
// DataObjectType input = new DataObjectType();
// input.setKey("echo_input");
// input.setType(DataType.STRING);
// input.setValue("echo_output=Hello World");
// exInputs.add(input);
//
// List<DataObjectType> exOut = new ArrayList<DataObjectType>();
// DataObjectType output = new DataObjectType();
// output.setKey("echo_output");
// output.setType(DataType.STRING);
// output.setValue("");
// exOut.add(output);
//
// Experiment simpleExperiment =
// ExperimentModelUtil.createSimpleExperiment("default", "admin", "echoExperiment", "SimpleEcho2", "SimpleEcho2", exInputs);
// simpleExperiment.setExperimentOutputs(exOut);
//
// ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("trestles.sdsc.edu", 1, 1, 1, "normal", 0, 0, 1, "sds128");
// scheduling.setResourceHostId("gsissh-trestles");
// UserConfigurationData userConfigurationData = new UserConfigurationData();
// userConfigurationData.setAiravataAutoSchedule(false);
// userConfigurationData.setOverrideManualScheduledParams(false);
// userConfigurationData.setComputationalResourceScheduling(scheduling);
// simpleExperiment.setUserConfigurationData(userConfigurationData);
//
// WorkflowNodeDetails test = ExperimentModelUtil.createWorkflowNode("test", null);
// Registry registry = RegistryFactory.getDefaultExpCatalog();
// experimentID = (String) registry.add(ParentDataType.EXPERIMENT, simpleExperiment);
// tasks = orchestrator.createTasks(experimentID);
//
// for (TaskDetails taskDetail: tasks)
// {
// orchestrator.launchProcess(simpleExperiment,test, taskDetail,null);
// }
// }
}
| 1,178 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/util/SecondValidator.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.
*/
///*
// *
// * 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.orchestrator.core.util;
//
//import org.apache.airavata.model.error.ValidationResults;
//import org.apache.airavata.model.error.ValidatorResult;
//import org.apache.airavata.model.experiment.ExperimentModel;
//import org.apache.airavata.model.experiment.TaskDetails;
//import org.apache.airavata.model.experiment.WorkflowNodeDetails;
//import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
//
//public class SecondValidator implements JobMetadataValidator {
// public ValidationResults validate(Experiment experiment, WorkflowNodeDetails workflowNodeDetail, TaskDetails taskID) {
// ValidationResults validationResults = new ValidationResults();
// validationResults.setValidationState(true);
// if(taskID.getTaskID() == null) {
// ValidatorResult validatorResult = new ValidatorResult(false);
// validatorResult.setErrorDetails("No taskID is set, so Validation failed");
// validationResults.addToValidationResultList(validatorResult);
// validationResults.setValidationState(false);
// }
// return validationResults;
// }
//}
| 1,179 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/test/java/org/apache/airavata/orchestrator/core/util/TestValidator.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.
*/
///*
// *
// * 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.orchestrator.core.util;
//
//import org.apache.airavata.model.error.ValidationResults;
//import org.apache.airavata.model.error.ValidatorResult;
//import org.apache.airavata.model.experiment.ExperimentModel;
//import org.apache.airavata.model.experiment.TaskDetails;
//import org.apache.airavata.model.experiment.WorkflowNodeDetails;
//import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
//import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//public class TestValidator implements JobMetadataValidator {
// private final static Logger logger = LoggerFactory.getLogger(TestValidator.class);
//
// public ValidationResults validate(Experiment experiment, WorkflowNodeDetails workflowNodeDetail, TaskDetails taskID) {
// ValidationResults validationResults = new ValidationResults();
// validationResults.setValidationState(true);
// if (experiment.getProjectID() == null) {
// logger.error("Project ID is not set");
// ValidatorResult validatorResult = new ValidatorResult(false);
// validatorResult.setErrorDetails("Project ID is not set");
// validationResults.addToValidationResultList(validatorResult);
// validationResults.setValidationState(false);
// } else if (experiment.getExperimentID() == null) {
// logger.error("This experiment is wrong, no experimentID set");
// ValidatorResult validatorResult = new ValidatorResult(false);
// validatorResult.setErrorDetails("This experiment is wrong, no experimentID set");
// validationResults.addToValidationResultList(validatorResult);
// validationResults.setValidationState(false);
// }
// return validationResults;
// }
//}
| 1,180 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/OrchestratorConfiguration.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.orchestrator.core;
import java.net.URL;
import java.util.List;
/**
* This keeps configuration of orchestrator, mostly this keep static
* configuration, this can be accessed through orchestratorContext object
*/
public class OrchestratorConfiguration {
private String newJobSubmitterClass;
private String hangedJobSubmitterClass;
private int submitterInterval = 1000;
private int threadPoolSize = 10;
private boolean startSubmitter = false;
private URL brokerURL;
private boolean embeddedMode;
private List<String> validatorClasses;
private boolean enableValidation;
public List<String> getValidatorClasses() {
return validatorClasses;
}
public void setValidatorClasses(List<String> validatorClasses) {
this.validatorClasses = validatorClasses;
}
public boolean isEmbeddedMode() {
return embeddedMode;
}
public void setEmbeddedMode(boolean embeddedMode) {
this.embeddedMode = embeddedMode;
}
public URL getBrokerURL() {
return brokerURL;
}
public void setBrokerURL(URL brokerURL) {
this.brokerURL = brokerURL;
}
public String getNewJobSubmitterClass() {
return newJobSubmitterClass;
}
public int getSubmitterInterval() {
return submitterInterval;
}
public int getThreadPoolSize() {
return threadPoolSize;
}
public void setNewJobSubmitterClass(String newJobSubmitterClass) {
this.newJobSubmitterClass = newJobSubmitterClass;
}
public void setSubmitterInterval(int submitterInterval) {
this.submitterInterval = submitterInterval;
}
public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
public boolean isStartSubmitter() {
return startSubmitter;
}
public void setStartSubmitter(boolean startSubmitter) {
this.startSubmitter = startSubmitter;
}
public String getHangedJobSubmitterClass() {
return hangedJobSubmitterClass;
}
public void setHangedJobSubmitterClass(String hangedJobSubmitterClass) {
this.hangedJobSubmitterClass = hangedJobSubmitterClass;
}
public boolean isEnableValidation() {
return enableValidation;
}
public void setEnableValidation(boolean enableValidation) {
this.enableValidation = enableValidation;
}
}
| 1,181 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/impl/GFACPassiveJobSubmitter.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.orchestrator.core.impl;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.credential.store.store.CredentialReader;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.messaging.event.ProcessSubmitEvent;
import org.apache.airavata.model.messaging.event.ProcessTerminateEvent;
import org.apache.airavata.orchestrator.core.context.OrchestratorContext;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.orchestrator.core.job.JobSubmitter;
import org.apache.airavata.orchestrator.core.utils.OrchestratorUtils;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
/**
* This class can be used to do the communication between orchestrator and gfac to handle using a queue
*/
public class GFACPassiveJobSubmitter implements JobSubmitter,Watcher {
private final static Logger logger = LoggerFactory.getLogger(GFACPassiveJobSubmitter.class);
private static Integer mutex = -1;
private Publisher publisher;
public void initialize(OrchestratorContext orchestratorContext) throws OrchestratorException {
if(orchestratorContext.getPublisher()!=null){
this.publisher = orchestratorContext.getPublisher();
}else {
try {
this.publisher = MessagingFactory.getPublisher(Type.PROCESS_LAUNCH);
} catch (AiravataException e) {
logger.error(e.getMessage(), e);
throw new OrchestratorException("Cannot initialize " + GFACPassiveJobSubmitter.class + " need to start Rabbitmq server to use " + GFACPassiveJobSubmitter.class);
}
}
}
/**
* Submit the job to a shared launch.queue accross multiple gfac instances
*
* @param experimentId
* @param processId
* @param tokenId
* @return
* @throws OrchestratorException
*/
public boolean submit(String experimentId, String processId, String tokenId) throws OrchestratorException {
try {
String gatewayId = null;
CredentialReader credentialReader = OrchestratorUtils.getCredentialReader();
if (credentialReader != null) {
try {
gatewayId = credentialReader.getGatewayID(tokenId);
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
}
}
if (gatewayId == null || gatewayId.isEmpty()) {
gatewayId = ServerSettings.getDefaultUserGateway();
}
ProcessSubmitEvent processSubmitEvent = new ProcessSubmitEvent(processId, gatewayId, experimentId,
tokenId);
MessageContext messageContext = new MessageContext(processSubmitEvent, MessageType.LAUNCHPROCESS, "LAUNCH" +
".PROCESS-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
publisher.publish(messageContext);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new OrchestratorException(e);
}
return true;
}
/**
* Submit the experiment the terminate.queue job queue and remove the experiment from shared launch.queue
* @param experimentId
* @param processId
* @return
* @throws OrchestratorException
*/
public boolean terminate(String experimentId, String processId, String tokenId) throws OrchestratorException {
String gatewayId = null;
try {
CredentialReader credentialReader = OrchestratorUtils.getCredentialReader();
if (credentialReader != null) {
try {
gatewayId = credentialReader.getGatewayID(tokenId);
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
}
}
if (gatewayId == null || gatewayId.isEmpty()) {
gatewayId = ServerSettings.getDefaultUserGateway();
}
ProcessTerminateEvent processTerminateEvent = new ProcessTerminateEvent(processId, gatewayId, tokenId);
MessageContext messageContext = new MessageContext(processTerminateEvent, MessageType.TERMINATEPROCESS, "LAUNCH.TERMINATE-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
publisher.publish(messageContext);
return true;
} catch (Exception e) {
throw new OrchestratorException(e);
}
}
synchronized public void process(WatchedEvent event) {
logger.info(getClass().getName() + event.getPath());
logger.info(getClass().getName()+event.getType());
synchronized (mutex) {
switch (event.getState()) {
case SyncConnected:
mutex.notify();
}
switch (event.getType()) {
case NodeCreated:
mutex.notify();
break;
}
}
}
}
| 1,182 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/schedule/DefaultHostScheduler.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.orchestrator.core.schedule;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import java.util.List;
public class DefaultHostScheduler implements HostScheduler {
@Override
public ComputeResourceDescription schedule(List<ComputeResourceDescription> registeredHosts) {
if (registeredHosts == null || registeredHosts.isEmpty()) {
return null;
} else {
return registeredHosts.get(0); // return first schedulear in the list.
}
}
}
| 1,183 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/schedule/HostScheduler.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.orchestrator.core.schedule;
import java.util.List;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
public interface HostScheduler {
/**
* This method will pick a host among set of hosts based on the algorithm users wants to implement, For a single instance
* of Airavata users can pick one Scheduler.
* @param registeredHosts
* @return
*/
public ComputeResourceDescription schedule(List<ComputeResourceDescription> registeredHosts);
}
| 1,184 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/context/OrchestratorContext.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.orchestrator.core.context;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.orchestrator.core.OrchestratorConfiguration;
/**
* This is the context object used in orchestrator which
*/
public class OrchestratorContext {
private OrchestratorConfiguration orchestratorConfiguration;
private Publisher publisher;
private String gatewayId;
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public OrchestratorConfiguration getOrchestratorConfiguration() {
return orchestratorConfiguration;
}
public void setOrchestratorConfiguration(OrchestratorConfiguration orchestratorConfiguration) {
this.orchestratorConfiguration = orchestratorConfiguration;
}
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
}
| 1,185 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator/JobMetadataValidator.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.orchestrator.core.validator;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.task.TaskModel;
/**
* This is the interface to implement a validation logic, users can implement their validation
* logic in validate mthod and if its failed, they can wrap-up an error and return the validation-Results object
* as the return value
*/
public interface JobMetadataValidator {
/**
* Validation logic can be implemented, more importantsly no exceptions should be thrown,
* if there are internal exceptions, errors can be encapsulate to the ValidationResults object
* and set the results as failed (false) and return in, orchestrator will wrap them to an Exception and
* thrown to the client side
* @param experiment
* @param processModel
* @return
*/
ValidationResults validate(ExperimentModel experiment, ProcessModel processModel);
}
| 1,186 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator/impl/GroupResourceProfileValidator.java | package org.apache.airavata.orchestrator.core.validator.impl;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.model.appcatalog.groupresourceprofile.BatchQueueResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.error.ValidatorResult;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.experiment.UserConfigurationDataModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class GroupResourceProfileValidator implements JobMetadataValidator {
private final static Logger logger = LoggerFactory.getLogger(GroupResourceProfileValidator.class);
private RegistryService.Client registryClient;
public GroupResourceProfileValidator() throws TException, ApplicationSettingsException {
this.registryClient = getRegistryServiceClient();
}
@Override
public ValidationResults validate(ExperimentModel experiment, ProcessModel processModel) {
ValidationResults validationResults = new ValidationResults();
validationResults.setValidationState(true);
try {
List<ValidatorResult> validatorResultList = validateGroupResourceProfile(experiment, processModel);
for (ValidatorResult result : validatorResultList){
if (!result.isResult()){
validationResults.setValidationState(false);
break;
}
}
validationResults.setValidationResultList(validatorResultList);
} catch (TException e) {
throw new RuntimeException("Error while validating Group Resource Profile", e);
}
return validationResults;
}
private List<ValidatorResult> validateGroupResourceProfile(ExperimentModel experiment, ProcessModel processModel) throws TException{
List<ValidatorResult> validatorResultList = new ArrayList<ValidatorResult>();
UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData();
ComputationalResourceSchedulingModel computationalResourceScheduling = userConfigurationData.getComputationalResourceScheduling();
String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId();
String computeResourceId;
if (processModel == null) {
computeResourceId = computationalResourceScheduling.getResourceHostId();
} else {
computeResourceId = processModel.getProcessResourceSchedule().getResourceHostId();
}
List<BatchQueueResourcePolicy> batchQueueResourcePolicies = registryClient.getGroupBatchQueueResourcePolicyList(groupResourceProfileId);
List<ComputeResourcePolicy> computeResourcePolicies = registryClient.getGroupComputeResourcePolicyList(groupResourceProfileId);
ComputeResourcePolicy groupComputeResourcePolicy = computeResourcePolicies.stream()
.filter(computeResourcePolicy -> computeResourceId.equals(computeResourcePolicy.getComputeResourceId()))
.findFirst().get();
if (groupComputeResourcePolicy != null) {
ValidatorResult queueNameResult = new ValidatorResult();
List<String> ComputeResourcePolicyBatchQueues = groupComputeResourcePolicy.getAllowedBatchQueues();
String queueName = computationalResourceScheduling.getQueueName().trim();
if (ComputeResourcePolicyBatchQueues.contains(queueName)) {
BatchQueueResourcePolicy batchQueueResourcePolicy = batchQueueResourcePolicies.stream()
.filter(bqResourcePolicy -> computeResourceId.equals(bqResourcePolicy.getComputeResourceId())
&& queueName.equals(bqResourcePolicy.getQueuename()))
.findFirst().get();
if (batchQueueResourcePolicy != null) {
validatorResultList.addAll(batchQueuePolicyValidate(computationalResourceScheduling, batchQueueResourcePolicy));
} else {
ValidatorResult batchQueuePolicyResult = new ValidatorResult();
logger.info("There is no batch queue resource policy specified for the group resource profile and queue name");
batchQueuePolicyResult.setResult(true);
validatorResultList.add(batchQueuePolicyResult);
}
} else {
queueNameResult.setResult(false);
queueNameResult.setErrorDetails("The specified queue " + queueName +
" does not exist in the list of allowed queues for the group resource profile.");
validatorResultList.add(queueNameResult);
}
} else {
ValidatorResult result = new ValidatorResult();
logger.info("There is no compute resource policy specified for the group resource profile");
result.setResult(true);
validatorResultList.add(result);
// verify if batchQueueResourcePolicy exists without computeResourcePolicy
if (batchQueueResourcePolicies != null && !batchQueueResourcePolicies.isEmpty()) {
String queueName = computationalResourceScheduling.getQueueName().trim();
BatchQueueResourcePolicy batchQueueResourcePolicy = batchQueueResourcePolicies.stream()
.filter(bqResourcePolicy -> computeResourceId.equals(bqResourcePolicy.getComputeResourceId())
&& queueName.equals(bqResourcePolicy.getQueuename()))
.findFirst().get();
if (batchQueueResourcePolicy != null) {
validatorResultList.addAll(batchQueuePolicyValidate(computationalResourceScheduling, batchQueueResourcePolicy));
} else {
ValidatorResult batchQueuePolicyResult = new ValidatorResult();
logger.info("There is no batch queue resource policy specified for the group resource profile and queue name");
batchQueuePolicyResult.setResult(true);
validatorResultList.add(batchQueuePolicyResult);
}
} else {
logger.info("There is no batch resource policy specified for the group resource profile");
}
}
return validatorResultList;
}
private List<ValidatorResult> batchQueuePolicyValidate(ComputationalResourceSchedulingModel computationalResourceScheduling, BatchQueueResourcePolicy batchQueueResourcePolicy) {
List<ValidatorResult> batchQueuevalidatorResultList = new ArrayList<ValidatorResult>();
int experimentWallTimeLimit = computationalResourceScheduling.getWallTimeLimit();
int experimentNodeCount = computationalResourceScheduling.getNodeCount();
int experimentCPUCount = computationalResourceScheduling.getTotalCPUCount();
ValidatorResult wallTimeResult = new ValidatorResult();
if (experimentWallTimeLimit > batchQueueResourcePolicy.getMaxAllowedWalltime()) {
wallTimeResult.setResult(false);
wallTimeResult.setErrorDetails("Job Execution walltime " + experimentWallTimeLimit +
" exceeds the allowable walltime for the group resource profile " + batchQueueResourcePolicy.getMaxAllowedWalltime() +
" for queue " + batchQueueResourcePolicy.getQueuename());
} else {
wallTimeResult.setResult(true);
wallTimeResult.setErrorDetails("");
}
ValidatorResult nodeCountResult = new ValidatorResult();
if (experimentNodeCount > batchQueueResourcePolicy.getMaxAllowedNodes()) {
nodeCountResult.setResult(false);
nodeCountResult.setErrorDetails("Job Execution node count " + experimentNodeCount +
" exceeds the allowable node count for the group resource profile " + batchQueueResourcePolicy.getMaxAllowedNodes() +
" for queue " + batchQueueResourcePolicy.getQueuename());
} else {
nodeCountResult.setResult(true);
nodeCountResult.setErrorDetails("");
}
ValidatorResult cpuCountResult = new ValidatorResult();
if (experimentCPUCount > batchQueueResourcePolicy.getMaxAllowedCores()) {
cpuCountResult.setResult(false);
cpuCountResult.setErrorDetails("Job Execution cpu count " + experimentCPUCount +
" exceeds the allowable cpu count for the group resource profile " + batchQueueResourcePolicy.getMaxAllowedCores() +
" for queue " + batchQueueResourcePolicy.getQueuename());
} else {
cpuCountResult.setResult(true);
cpuCountResult.setErrorDetails("");
}
batchQueuevalidatorResultList.add(wallTimeResult);
batchQueuevalidatorResultList.add(nodeCountResult);
batchQueuevalidatorResultList.add(cpuCountResult);
return batchQueuevalidatorResultList;
}
private RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
try {
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
}
| 1,187 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator/impl/BatchQueueValidator.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.orchestrator.core.validator.impl;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.model.appcatalog.computeresource.BatchQueue;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.error.ValidatorResult;
import org.apache.airavata.model.experiment.*;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class BatchQueueValidator implements JobMetadataValidator {
private final static Logger logger = LoggerFactory.getLogger(BatchQueueValidator.class);
private RegistryService.Client registryClient;
public BatchQueueValidator() throws TException, ApplicationSettingsException {
this.registryClient = getRegistryServiceClient();
}
public ValidationResults validate(ExperimentModel experiment, ProcessModel processModel) {
ValidationResults validationResults = new ValidationResults();
validationResults.setValidationState(true);
try {
List<ValidatorResult> validatorResultList = validateUserConfiguration(experiment, processModel);
for (ValidatorResult result : validatorResultList){
if (!result.isResult()){
validationResults.setValidationState(false);
break;
}
}
validationResults.setValidationResultList(validatorResultList);
} catch (TException e) {
throw new RuntimeException("Error while validating", e);
}
return validationResults;
}
private List<ValidatorResult> validateUserConfiguration (ExperimentModel experiment, ProcessModel processModel) throws TException {
List<ValidatorResult> validatorResultList = new ArrayList<ValidatorResult>();
UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData();
ComputationalResourceSchedulingModel computationalResourceScheduling = userConfigurationData.getComputationalResourceScheduling();
if (userConfigurationData.isAiravataAutoSchedule()) {
logger.info("User enabled Auto-Schedule. Hence we don't do validation..");
ValidatorResult validatorResult = new ValidatorResult();
validatorResult.setResult(true);
validatorResultList.add(validatorResult);
} else {
ComputeResourceDescription computeResource;
if (processModel == null) {
computeResource = registryClient.getComputeResource(experiment.getUserConfigurationData().getComputationalResourceScheduling().getResourceHostId());
} else {
computeResource = registryClient.getComputeResource(processModel.getProcessResourceSchedule().getResourceHostId());
}
List<BatchQueue> batchQueues = computeResource.getBatchQueues();
if (computationalResourceScheduling == null) {
ValidatorResult queueNameResult = new ValidatorResult();
queueNameResult.setResult(false);
queueNameResult.setErrorDetails("No compute resource scheduling for experiment " + experiment.getExperimentId());
validatorResultList.add(queueNameResult);
return validatorResultList;
}
if (computationalResourceScheduling.getQueueName() == null) {
ValidatorResult queueNameResult = new ValidatorResult();
queueNameResult.setResult(false);
queueNameResult.setErrorDetails("No queue name for experiment " + experiment.getExperimentId());
validatorResultList.add(queueNameResult);
return validatorResultList;
}
if (batchQueues != null && !batchQueues.isEmpty()) {
String experimentQueueName = computationalResourceScheduling.getQueueName().trim();
int experimentWallTimeLimit = computationalResourceScheduling.getWallTimeLimit();
int experimentNodeCount = computationalResourceScheduling.getNodeCount();
int experimentCPUCount = computationalResourceScheduling.getTotalCPUCount();
ValidatorResult queueNameResult = new ValidatorResult();
//Set the validation to false. Once all the queue's are looped, if nothing matches, then this gets passed.
queueNameResult.setResult(false);
queueNameResult.setErrorDetails("The specified queue " + experimentQueueName +
" does not exist. If you believe this is an error, contact the administrator to verify App-Catalog Configurations");
for (BatchQueue queue : batchQueues) {
String resourceQueueName = queue.getQueueName();
int maxQueueRunTime = queue.getMaxRunTime();
int maxNodeCount = queue.getMaxNodes();
int maxcpuCount = queue.getMaxProcessors();
if (resourceQueueName != null && resourceQueueName.equals(experimentQueueName)) {
queueNameResult.setResult(true);
queueNameResult.setErrorDetails("");
//Validate if the specified wall time is within allowable limit
ValidatorResult wallTimeResult = new ValidatorResult();
if (experimentWallTimeLimit == 0) {
wallTimeResult.setResult(false);
wallTimeResult.setErrorDetails("Walltime cannot be zero for queue " + resourceQueueName);
} else {
if (maxQueueRunTime == 0) {
wallTimeResult.setResult(true);
wallTimeResult.setErrorDetails("Maximum wall time is not configured for the queue," +
"Validation is being skipped");
logger.info("Maximum wall time is not configured for the queue" +
"Validation is being skipped");
} else {
if (maxQueueRunTime < experimentWallTimeLimit) {
wallTimeResult.setResult(false);
wallTimeResult.setErrorDetails("Job Execution walltime " + experimentWallTimeLimit +
"exceeds the allowable walltime" + maxQueueRunTime +
"for queue " + resourceQueueName);
} else {
wallTimeResult.setResult(true);
wallTimeResult.setErrorDetails("");
}
}
}
//validate max node count
ValidatorResult nodeCountResult = new ValidatorResult();
if (maxNodeCount == 0) {
nodeCountResult.setResult(true);
nodeCountResult.setErrorDetails("Max node count is not configured for the queue," +
"Validation is being skipped");
logger.info("Max node count is not configured for the queue" +
"Validation is being skipped");
} else {
if (experimentNodeCount == 0) {
nodeCountResult.setResult(false);
nodeCountResult.setErrorDetails("Job Execution node count cannot be zero for queue " + resourceQueueName);
} else {
if (maxNodeCount < experimentNodeCount) {
nodeCountResult.setResult(false);
nodeCountResult.setErrorDetails("Job Execution node count " + experimentNodeCount +
"exceeds the allowable node count" + maxNodeCount +
"for queue " + resourceQueueName);
} else {
nodeCountResult.setResult(true);
nodeCountResult.setErrorDetails("");
}
}
}
// validate cpu count
ValidatorResult cpuCountResult = new ValidatorResult();
if (maxcpuCount == 0) {
cpuCountResult.setResult(true);
cpuCountResult.setErrorDetails("Max cpu count is not configured for the queue," +
"Validation is being skipped");
logger.info("Max cpu count is not configured for the queue" +
"Validation is being skipped");
} else {
if (experimentCPUCount == 0) {
cpuCountResult.setResult(false);
cpuCountResult.setErrorDetails("Job Execution cpu count cannot be zero for queue " + resourceQueueName);
} else {
if (maxcpuCount < experimentCPUCount) {
cpuCountResult.setResult(false);
cpuCountResult.setErrorDetails("Job Execution cpu count " + experimentCPUCount +
"exceeds the allowable cpu count" + maxcpuCount +
"for queue " + resourceQueueName);
} else {
cpuCountResult.setResult(true);
cpuCountResult.setErrorDetails("");
}
}
}
validatorResultList.add(wallTimeResult);
validatorResultList.add(nodeCountResult);
validatorResultList.add(cpuCountResult);
}
}
validatorResultList.add(queueNameResult);
} else {
// for some compute resources, you dnt need to specify queue names
ValidatorResult result = new ValidatorResult();
logger.info("There are not queues defined under the compute resource. Airavata assumes this experiment " +
"does not need a queue name...");
result.setResult(true);
validatorResultList.add(result);
}
}
return validatorResultList;
}
private RegistryService.Client getRegistryServiceClient() throws ApplicationSettingsException {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
try {
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
}
| 1,188 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/validator/impl/ExperimentStatusValidator.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.orchestrator.core.validator.impl;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.error.ValidatorResult;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.status.ExperimentState;
import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class ExperimentStatusValidator implements JobMetadataValidator {
private static Logger log = LoggerFactory.getLogger(ExperimentStatusValidator.class);
public ValidationResults validate(ExperimentModel experiment, ProcessModel processModel) {
String error = "During the validation step experiment status should be CREATED, But this experiment status is : ";
ValidationResults validationResults = new ValidationResults();
validationResults.setValidationState(true);
ValidatorResult validatorResult = new ValidatorResult();
List<ValidatorResult> validatorResultList = new ArrayList<ValidatorResult>();
if (!experiment.getExperimentStatus().get(0).getState().equals(ExperimentState.CREATED)) {
error += experiment.getExperimentStatus().get(0).getState().toString();
log.error(error);
validatorResult.setErrorDetails(error);
validatorResult.setResult(false);
validationResults.setValidationState(false);
}
validatorResult.setResult(true);
validatorResultList.add(validatorResult);
validationResults.setValidationResultList(validatorResultList);
return validationResults;
}
}
| 1,189 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/utils/OrchestratorUtils.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.orchestrator.core.utils;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.DBUtil;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.credential.store.store.CredentialReader;
import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference;
import org.apache.airavata.model.data.movement.DataMovementInterface;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.apache.airavata.model.data.movement.SCPDataMovement;
import org.apache.airavata.model.data.movement.SecurityProtocol;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.orchestrator.core.OrchestratorConfiguration;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* This contains orchestrator specific utilities
*/
public class OrchestratorUtils {
private final static Logger logger = LoggerFactory.getLogger(OrchestratorUtils.class);
public static OrchestratorConfiguration loadOrchestratorConfiguration()
throws OrchestratorException, IOException, NumberFormatException, ApplicationSettingsException {
OrchestratorConfiguration orchestratorConfiguration = new OrchestratorConfiguration();
orchestratorConfiguration.setSubmitterInterval(
Integer.parseInt(ServerSettings.getSetting(OrchestratorConstants.SUBMIT_INTERVAL)));
orchestratorConfiguration.setThreadPoolSize(
Integer.parseInt(ServerSettings.getSetting(OrchestratorConstants.THREAD_POOL_SIZE)));
orchestratorConfiguration.setStartSubmitter(
Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.START_SUBMITTER)));
orchestratorConfiguration.setEmbeddedMode(
Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.EMBEDDED_MODE)));
orchestratorConfiguration.setEnableValidation(
Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.ENABLE_VALIDATION)));
if (orchestratorConfiguration.isEnableValidation()) {
orchestratorConfiguration.setValidatorClasses(
Arrays.asList(ServerSettings.getSetting(OrchestratorConstants.JOB_VALIDATOR).split(",")));
}
return orchestratorConfiguration;
}
public static JobSubmissionProtocol getPreferredJobSubmissionProtocol(ProcessModel model,
String gatewayId) throws TException, OrchestratorException {
return getPreferredJobSubmissionInterface(model, gatewayId).getJobSubmissionProtocol();
}
public static GroupComputeResourcePreference getGroupComputeResourcePreference(ProcessModel model) throws TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getGroupComputeResourcePreference(model.getComputeResourceId(), model.getGroupResourceProfileId());
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static String getApplicationInterfaceName(ProcessModel model)
throws TException, OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ApplicationInterfaceDescription appInterface = registryClient.getApplicationInterface(model.getApplicationInterfaceId());
return appInterface.getApplicationName();
} catch (Exception e) {
throw new OrchestratorException("Error while retrieving application interface", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static DataMovementProtocol getPreferredDataMovementProtocol(ProcessModel model,
String gatewayId) throws TException, OrchestratorException {
return getPreferredDataMovementInterface(model, gatewayId).getDataMovementProtocol();
}
public static StoragePreference getStoragePreference(ProcessModel processModel,
String gatewayId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
String resourceHostId = processModel.getComputeResourceId();
return registryClient.getGatewayStoragePreference(gatewayId, resourceHostId);
} catch (Exception e) {
logger.error("Error occurred while retrieving StoragePreference", e);
throw new OrchestratorException("Error occurred while retrieving StoragePreference", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static String getLoginUserName(ProcessModel processModel,
String gatewayId) throws AiravataException, TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
GroupComputeResourcePreference computeResourcePreference = getGroupComputeResourcePreference(processModel);
ComputationalResourceSchedulingModel processResourceSchedule = processModel.getProcessResourceSchedule();
if (processModel.isUseUserCRPref()) {
UserComputeResourcePreference userComputeResourcePreference = registryClient
.getUserComputeResourcePreference(processModel.getUserName(), gatewayId,
processModel.getComputeResourceId());
if (isValid(userComputeResourcePreference.getLoginUserName())) {
return userComputeResourcePreference.getLoginUserName();
} else if (isValid(processResourceSchedule.getOverrideLoginUserName())) {
logger.warn("User computer resource preference doesn't have valid user login name, using computer " +
"resource scheduling login name " + processResourceSchedule.getOverrideLoginUserName());
return processResourceSchedule.getOverrideLoginUserName();
} else if (isValid(computeResourcePreference.getLoginUserName())) {
logger.warn("Either User computer resource preference or computer resource scheduling " +
"doesn't have valid user login name, using group resource profile computer resource preference login name "
+ computeResourcePreference.getLoginUserName());
return computeResourcePreference.getLoginUserName();
}else {
throw new AiravataException("Login name is not found");
}
}else {
if (isValid(processResourceSchedule.getOverrideLoginUserName())) {
return processResourceSchedule.getOverrideLoginUserName();
} else if (isValid(computeResourcePreference.getLoginUserName())) {
logger.warn("Process compute resource scheduling doesn't have valid user login name, " +
"using gateway computer resource preference login name "
+ computeResourcePreference.getLoginUserName());
return computeResourcePreference.getLoginUserName();
}else {
throw new AiravataException("Login name is not found");
}
}
} catch (ApplicationSettingsException e) {
logger.error("Error occurred while initializing app catalog to fetch login username", e);
throw new ApplicationSettingsException("Error occurred while initializing app catalog to fetch login username", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static String getScratchLocation(ProcessModel processModel,
String gatewayId) throws AiravataException, TException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
GroupComputeResourcePreference computeResourcePreference = getGroupComputeResourcePreference(processModel);
ComputationalResourceSchedulingModel processResourceSchedule = processModel.getProcessResourceSchedule();
if (processModel.isUseUserCRPref()) {
UserComputeResourcePreference userComputeResourcePreference = registryClient
.getUserComputeResourcePreference(processModel.getUserName(), gatewayId,
processModel.getComputeResourceId());
if (isValid(userComputeResourcePreference.getScratchLocation())) {
return userComputeResourcePreference.getScratchLocation();
} else if (isValid(processResourceSchedule.getOverrideScratchLocation())) {
logger.warn("User computer resource preference doesn't have valid scratch location, using computer " +
"resource scheduling scratch location " + processResourceSchedule.getOverrideScratchLocation());
return processResourceSchedule.getOverrideScratchLocation();
} else if (isValid(computeResourcePreference.getScratchLocation())) {
logger.warn("Either User computer resource preference or computer resource scheduling doesn't have " +
"valid scratch location, using gateway computer resource preference scratch location"
+ computeResourcePreference.getScratchLocation());
return computeResourcePreference.getScratchLocation();
}else {
throw new AiravataException("Scratch location is not found");
}
}else {
if (isValid(processResourceSchedule.getOverrideScratchLocation())) {
return processResourceSchedule.getOverrideScratchLocation();
} else if (isValid(computeResourcePreference.getScratchLocation())) {
logger.warn("Process compute resource scheduling doesn't have valid scratch location, " +
"using gateway computer resource preference scratch location"
+ computeResourcePreference.getScratchLocation());
return computeResourcePreference.getScratchLocation();
}else {
throw new AiravataException("Scratch location is not found");
}
}
} catch (AiravataException e) {
logger.error("Error occurred while initializing app catalog to fetch scratch location", e);
throw new AiravataException("Error occurred while initializing app catalog to fetch scratch location", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static JobSubmissionInterface getPreferredJobSubmissionInterface(ProcessModel processModel,
String gatewayId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
String resourceHostId = processModel.getComputeResourceId();
ComputeResourceDescription resourceDescription = registryClient.getComputeResource(resourceHostId);
List<JobSubmissionInterface> jobSubmissionInterfaces = resourceDescription.getJobSubmissionInterfaces();
if (jobSubmissionInterfaces != null && !jobSubmissionInterfaces.isEmpty()) {
Collections.sort(jobSubmissionInterfaces, Comparator.comparingInt(JobSubmissionInterface::getPriorityOrder));
} else {
throw new OrchestratorException("Compute resource should have at least one job submission interface defined...");
}
return jobSubmissionInterfaces.get(0);
} catch (Exception e) {
throw new OrchestratorException("Error occurred while retrieving data from app catalog", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static DataMovementInterface getPreferredDataMovementInterface(ProcessModel processModel,
String gatewayId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
String resourceHostId = processModel.getComputeResourceId();
ComputeResourceDescription resourceDescription = registryClient.getComputeResource(resourceHostId);
List<DataMovementInterface> dataMovementInterfaces = resourceDescription.getDataMovementInterfaces();
if (dataMovementInterfaces != null && !dataMovementInterfaces.isEmpty()) {
Collections.sort(dataMovementInterfaces, Comparator.comparingInt(DataMovementInterface::getPriorityOrder));
} else {
throw new OrchestratorException("Compute resource should have at least one data movement interface defined...");
}
return dataMovementInterfaces.get(0);
} catch (Exception e) {
throw new OrchestratorException("Error occurred while retrieving data from app catalog", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static int getDataMovementPort(ProcessModel processModel,
String gatewayId) throws TException, ApplicationSettingsException, OrchestratorException {
try {
DataMovementProtocol protocol = getPreferredDataMovementProtocol(processModel, gatewayId);
DataMovementInterface dataMovementInterface = getPreferredDataMovementInterface(processModel, gatewayId);
if (protocol == DataMovementProtocol.SCP ) {
SCPDataMovement scpDataMovement = getSCPDataMovement(dataMovementInterface.getDataMovementInterfaceId());
if (scpDataMovement != null) {
return scpDataMovement.getSshPort();
}
}
} catch (Exception e) {
logger.error("Error occurred while retrieving security protocol", e);
}
return 0;
}
public static SecurityProtocol getSecurityProtocol(ProcessModel processModel,
String gatewayId) throws TException, ApplicationSettingsException, OrchestratorException {
try {
JobSubmissionProtocol submissionProtocol = getPreferredJobSubmissionProtocol(processModel, gatewayId);
JobSubmissionInterface jobSubmissionInterface = getPreferredJobSubmissionInterface(processModel, gatewayId);
if (submissionProtocol == JobSubmissionProtocol.SSH ) {
SSHJobSubmission sshJobSubmission = getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
if (sshJobSubmission != null) {
return sshJobSubmission.getSecurityProtocol();
}
} else if (submissionProtocol == JobSubmissionProtocol.LOCAL) {
LOCALSubmission localJobSubmission = getLocalJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
if (localJobSubmission != null) {
return localJobSubmission.getSecurityProtocol();
}
} else if (submissionProtocol == JobSubmissionProtocol.SSH_FORK){
SSHJobSubmission sshJobSubmission = getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
if (sshJobSubmission != null) {
return sshJobSubmission.getSecurityProtocol();
}
} else if (submissionProtocol == JobSubmissionProtocol.CLOUD) {
CloudJobSubmission cloudJobSubmission = getCloudJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
if (cloudJobSubmission != null) {
return cloudJobSubmission.getSecurityProtocol();
}
}
} catch (OrchestratorException e) {
logger.error("Error occurred while retrieving security protocol", e);
}
return null;
}
public static LOCALSubmission getLocalJobSubmission(String submissionId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getLocalJobSubmission(submissionId);
} catch (Exception e) {
String errorMsg = "Error while retrieving local job submission with submission id : " + submissionId;
logger.error(errorMsg, e);
throw new OrchestratorException(errorMsg, e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static UnicoreJobSubmission getUnicoreJobSubmission(String submissionId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getUnicoreJobSubmission(submissionId);
} catch (Exception e) {
String errorMsg = "Error while retrieving UNICORE job submission with submission id : " + submissionId;
logger.error(errorMsg, e);
throw new OrchestratorException(errorMsg, e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static SSHJobSubmission getSSHJobSubmission(String submissionId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getSSHJobSubmission(submissionId);
} catch (Exception e) {
String errorMsg = "Error while retrieving SSH job submission with submission id : " + submissionId;
logger.error(errorMsg, e);
throw new OrchestratorException(errorMsg, e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static CloudJobSubmission getCloudJobSubmission(String submissionId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getCloudJobSubmission(submissionId);
} catch (Exception e) {
String errorMsg = "Error while retrieving SSH job submission with submission id : " + submissionId;
logger.error(errorMsg, e);
throw new OrchestratorException(errorMsg, e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static SCPDataMovement getSCPDataMovement(String dataMoveId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
return registryClient.getSCPDataMovement(dataMoveId);
} catch (Exception e) {
String errorMsg = "Error while retrieving SCP Data movement with submission id : " + dataMoveId;
logger.error(errorMsg, e);
throw new OrchestratorException(errorMsg, e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private static boolean isValid(String str) {
return (str != null && !str.trim().isEmpty());
}
private static RegistryService.Client getRegistryServiceClient() {
try {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException|ApplicationSettingsException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
public static CredentialReader getCredentialReader()
throws ApplicationSettingsException, IllegalAccessException,
InstantiationException {
try {
String jdbcUrl = ServerSettings.getCredentialStoreDBURL();
String jdbcUsr = ServerSettings.getCredentialStoreDBUser();
String jdbcPass = ServerSettings.getCredentialStoreDBPassword();
String driver = ServerSettings.getCredentialStoreDBDriver();
return new CredentialReaderImpl(new DBUtil(jdbcUrl, jdbcUsr, jdbcPass,
driver));
} catch (ClassNotFoundException e) {
logger.error("Not able to find driver: " + e.getLocalizedMessage());
return null;
}
}
}
| 1,190 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/utils/OrchestratorConstants.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.orchestrator.core.utils;
/**
* This class contains all the constants in orchestrator-core
*
*/
public class OrchestratorConstants {
public static final String AIRAVATA_PROPERTIES = "airavata-server.properties";
public static final int hotUpdateInterval=1000;
public static final String SUBMIT_INTERVAL = "submitter.interval";
public static final String THREAD_POOL_SIZE = "threadpool.size";
public static final String START_SUBMITTER = "start.submitter";
public static final String EMBEDDED_MODE = "embedded.mode";
public static final String ENABLE_VALIDATION = "enable.validation";
public static final String JOB_VALIDATOR = "job.validators";
public static final String EXPERIMENT_ERROR = "EXPERIMENT_ERROR";
public static final String PROCESS_ERROR = "PROCESS_ERROR";
public static final String TASK_ERROR = "TASK_ERROR";
}
| 1,191 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/job/JobSubmitter.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.orchestrator.core.job;
import org.apache.airavata.orchestrator.core.context.OrchestratorContext;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
/**
* This is the submitter interface, orchestrator can
* submit jobs to gfac in different modes, gfac running embedded
* or gfac running in server mode. This can be configured in
* airavata-server.properties
* todo provide a way to configure this in a dynamic way
*/
public interface JobSubmitter {
void initialize(OrchestratorContext orchestratorContext) throws OrchestratorException;
/**
* This is similar to submit with expId and taskId but this has extra param called token
* @param experimentId
* @param processId
* @param tokenId
* @return
* @throws OrchestratorException
*/
boolean submit(String experimentId,String processId,String tokenId) throws OrchestratorException;
/**
* This can be used to terminate the experiment
* @param experimentId
* @param processId
* @return
* @throws OrchestratorException
*/
boolean terminate(String experimentId,String processId, String tokenId)throws OrchestratorException;
}
| 1,192 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/core/exception/OrchestratorException.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.orchestrator.core.exception;
/**
* This is the main exception class for orchestrator, All the other
* exception classes has to extend this class
*/
public class OrchestratorException extends Exception{
private static final long serialVersionUID = -2849422320139467602L;
public OrchestratorException(Throwable e) {
super(e);
}
public OrchestratorException(String message) {
super(message, null);
}
public OrchestratorException(String message, Throwable e) {
super(message, e);
}
}
| 1,193 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/cpi/Orchestrator.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.orchestrator.cpi;
import org.apache.airavata.model.error.LaunchValidationException;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
/*
This is the interface for orchestrator functionality exposed to the out side of the
module
*/
public interface Orchestrator {
/**
* This method can be used to run all custom validators plugged in to the orchestrator and make
* sure the experiment is ready to launch and if its not this will return false
*
* @param experiment
* @return boolean if the experiment is valid after executing all the validators return true otherwise it will return false
* @throws OrchestratorException
*/
ValidationResults validateExperiment(ExperimentModel experiment) throws OrchestratorException, LaunchValidationException;
/**
* This method can be used to run all custom validators plugged in to the orchestrator and make
* sure the experiment is ready to launch and if its not this will return false
*
* @param experiment
* @param processModel
* @return boolean if the process is valid after executing all the validators return true otherwise it will return false
* @throws OrchestratorException
*/
ValidationResults validateProcess(ExperimentModel experiment, ProcessModel processModel) throws OrchestratorException, LaunchValidationException;
/**
* After creating the experiment Data user have the
* experimentID as the handler to the experiment, during the launchProcess
* We just have to give the experimentID
*
* @param processModel - Process model created for this process.
* @param tokenId - token id for this request.
* @return launchProcess status
* @throws OrchestratorException
*/
boolean launchProcess(ProcessModel processModel, String tokenId) throws OrchestratorException;
/**
* After creating the experiment Data user have the
* experimentID as the handler to the experiment, during the launchProcess
* We just have to give the experimentID
*
* @param experiment
* @param tokenId
* @throws OrchestratorException
*/
void cancelExperiment(ExperimentModel experiment, String tokenId) throws OrchestratorException;
//todo have to add another method to handle failed or jobs to be recovered by orchestrator
//todo if you don't add these this is not an orchestrator, its just an intemediate component which invoke gfac
void initialize() throws OrchestratorException;
}
| 1,194 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/cpi | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/cpi/impl/AbstractOrchestrator.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.orchestrator.cpi.impl;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.orchestrator.core.OrchestratorConfiguration;
import org.apache.airavata.orchestrator.core.context.OrchestratorContext;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.orchestrator.core.utils.OrchestratorUtils;
import org.apache.airavata.orchestrator.cpi.Orchestrator;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public abstract class AbstractOrchestrator implements Orchestrator {
private final static Logger logger = LoggerFactory.getLogger(AbstractOrchestrator.class);
protected OrchestratorContext orchestratorContext;
protected OrchestratorConfiguration orchestratorConfiguration;
private String registryURL;
private String gatewayName;
private String airavataUserName;
public String getRegistryURL() {
return registryURL;
}
public void setRegistryURL(String registryURL) {
this.registryURL = registryURL;
}
public String getGatewayName() {
return gatewayName;
}
public void setGatewayName(String gatewayName) {
this.gatewayName = gatewayName;
}
public String getAiravataUserName() {
return airavataUserName;
}
public void setAiravataUserName(String airavataUserName) {
this.airavataUserName = airavataUserName;
}
public AbstractOrchestrator() throws OrchestratorException, TException {
try {
/* Initializing the OrchestratorConfiguration object */
orchestratorConfiguration = OrchestratorUtils.loadOrchestratorConfiguration();
setGatewayProperties();
orchestratorContext = new OrchestratorContext();
orchestratorContext.setOrchestratorConfiguration(orchestratorConfiguration);
} catch (IOException e) {
logger.error("Failed to initializing Orchestrator - Error parsing configuration files");
OrchestratorException orchestratorException = new OrchestratorException(e);
throw orchestratorException;
} catch (ApplicationSettingsException e) {
throw new OrchestratorException(e);
}
}
protected void setGatewayProperties() {
try {
setAiravataUserName(ServerSettings.getDefaultUser());
setGatewayName(ServerSettings.getDefaultUserGateway());
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException("Error while setting gateway properties.", e);
}
}
public OrchestratorContext getOrchestratorContext() {
return orchestratorContext;
}
public OrchestratorConfiguration getOrchestratorConfiguration() {
return orchestratorConfiguration;
}
}
| 1,195 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/cpi | Create_ds/airavata/modules/orchestrator/orchestrator-core/src/main/java/org/apache/airavata/orchestrator/cpi/impl/SimpleOrchestratorImpl.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.orchestrator.cpi.impl;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.application.io.DataType;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.commons.ErrorModel;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.apache.airavata.model.error.LaunchValidationException;
import org.apache.airavata.model.error.ValidationResults;
import org.apache.airavata.model.error.ValidatorResult;
import org.apache.airavata.model.experiment.ExperimentModel;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.status.TaskState;
import org.apache.airavata.model.status.TaskStatus;
import org.apache.airavata.model.task.*;
import org.apache.airavata.model.util.ExperimentModelUtil;
import org.apache.airavata.orchestrator.core.context.OrchestratorContext;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.orchestrator.core.impl.GFACPassiveJobSubmitter;
import org.apache.airavata.orchestrator.core.job.JobSubmitter;
import org.apache.airavata.orchestrator.core.utils.OrchestratorConstants;
import org.apache.airavata.orchestrator.core.utils.OrchestratorUtils;
import org.apache.airavata.orchestrator.core.validator.JobMetadataValidator;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ExecutorService;
public class SimpleOrchestratorImpl extends AbstractOrchestrator{
private final static Logger logger = LoggerFactory.getLogger(SimpleOrchestratorImpl.class);
private ExecutorService executor;
// this is going to be null unless the thread count is 0
private JobSubmitter jobSubmitter = null;
public SimpleOrchestratorImpl() throws OrchestratorException, TException {
try {
try {
// We are only going to use GFacPassiveJobSubmitter
jobSubmitter = new GFACPassiveJobSubmitter();
jobSubmitter.initialize(this.orchestratorContext);
} catch (Exception e) {
String error = "Error creating JobSubmitter in non threaded mode ";
logger.error(error);
throw new OrchestratorException(error, e);
}
} catch (OrchestratorException e) {
logger.error("Error Constructing the Orchestrator");
throw e;
}
}
public boolean launchProcess(ProcessModel processModel, String tokenId) throws OrchestratorException {
try {
return jobSubmitter.submit(processModel.getExperimentId(), processModel.getProcessId(), tokenId);
} catch (Exception e) {
throw new OrchestratorException("Error launching the job", e);
}
}
public ValidationResults validateExperiment(ExperimentModel experiment)
throws OrchestratorException,LaunchValidationException {
org.apache.airavata.model.error.ValidationResults validationResults =
new org.apache.airavata.model.error.ValidationResults();
validationResults.setValidationState(true); // initially making it to success, if atleast one failed them simply mark it failed.
String errorMsg = "Validation Errors : ";
if (this.orchestratorConfiguration.isEnableValidation()) {
List<String> validatorClasses = this.orchestratorContext.getOrchestratorConfiguration().getValidatorClasses();
for (String validator : validatorClasses) {
try {
Class<? extends JobMetadataValidator> vClass =
Class.forName(validator.trim()).asSubclass(JobMetadataValidator.class);
JobMetadataValidator jobMetadataValidator = vClass.newInstance();
validationResults = jobMetadataValidator.validate(experiment, null);
if (validationResults.isValidationState()) {
logger.info("Validation of " + validator + " is SUCCESSFUL");
} else {
List<ValidatorResult> validationResultList = validationResults.getValidationResultList();
for (ValidatorResult result : validationResultList){
if (!result.isResult()){
String validationError = result.getErrorDetails();
if (validationError != null){
errorMsg += validationError + " ";
}
}
}
logger.error("Validation of " + validator + " for experiment Id " +
experiment.getExperimentId() + " is FAILED:[error]. " + errorMsg);
validationResults.setValidationState(false);
try {
ErrorModel details = new ErrorModel();
details.setActualErrorMessage(errorMsg);
details.setCreationTime(Calendar.getInstance().getTimeInMillis());
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
registryClient
.addErrors(OrchestratorConstants.EXPERIMENT_ERROR, details, experiment.getExperimentId());
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
} catch (RegistryServiceException e) {
logger.error("Error while saving error details to registry", e);
throw new RuntimeException("Error while saving error details to registry", e);
} catch (TException e) {
throw new RuntimeException("Error while saving error details to registry", e);
}
break;
}
} catch (ClassNotFoundException e) {
logger.error("Error loading the validation class: ", validator, e);
validationResults.setValidationState(false);
} catch (InstantiationException e) {
logger.error("Error loading the validation class: ", validator, e);
validationResults.setValidationState(false);
} catch (IllegalAccessException e) {
logger.error("Error loading the validation class: ", validator, e);
validationResults.setValidationState(false);
}
}
}
if(validationResults.isValidationState()){
return validationResults;
}else {
//atleast one validation has failed, so we throw an exception
LaunchValidationException launchValidationException = new LaunchValidationException();
launchValidationException.setValidationResult(validationResults);
launchValidationException.setErrorMessage("Validation failed refer the validationResults list for " +
"detail error. Validation errors : " + errorMsg);
throw launchValidationException;
}
}
public ValidationResults validateProcess(ExperimentModel experiment, ProcessModel processModel)
throws OrchestratorException, LaunchValidationException {
org.apache.airavata.model.error.ValidationResults validationResults = new org.apache.airavata.model.error.ValidationResults();
validationResults.setValidationState(true); // initially making it to success, if atleast one failed them simply mark it failed.
String errorMsg = "Validation Errors : ";
if (this.orchestratorConfiguration.isEnableValidation()) {
List<String> validatorClzzez = this.orchestratorContext.getOrchestratorConfiguration().getValidatorClasses();
for (String validator : validatorClzzez) {
try {
Class<? extends JobMetadataValidator> vClass = Class.forName(validator.trim()).asSubclass(JobMetadataValidator.class);
JobMetadataValidator jobMetadataValidator = vClass.newInstance();
validationResults = jobMetadataValidator.validate(experiment, processModel);
if (validationResults.isValidationState()) {
logger.info("Validation of " + validator + " is SUCCESSFUL");
} else {
List<ValidatorResult> validationResultList = validationResults.getValidationResultList();
for (ValidatorResult result : validationResultList) {
if (!result.isResult()) {
String validationError = result.getErrorDetails();
if (validationError != null) {
errorMsg += validationError + " ";
}
}
}
logger.error("Validation of " + validator + " for experiment Id " +
experiment.getExperimentId() + " is FAILED:[error]. " + errorMsg);
validationResults.setValidationState(false);
try {
ErrorModel details = new ErrorModel();
details.setActualErrorMessage(errorMsg);
details.setCreationTime(Calendar.getInstance().getTimeInMillis());
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
registryClient
.addErrors(OrchestratorConstants.PROCESS_ERROR, details, processModel.getProcessId());
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
} catch (RegistryServiceException e) {
logger.error("Error while saving error details to registry", e);
throw new RuntimeException("Error while saving error details to registry", e);
} catch (TException e) {
throw new RuntimeException("Error while saving error details to registry", e);
}
break;
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
logger.error("Error loading the validation class: ", validator, e);
validationResults.setValidationState(false);
}
}
}
if (validationResults.isValidationState()) {
return validationResults;
} else {
//atleast one validation has failed, so we throw an exception
LaunchValidationException launchValidationException = new LaunchValidationException();
launchValidationException.setValidationResult(validationResults);
launchValidationException.setErrorMessage("Validation failed refer the validationResults " +
"list for detail error. Validation errors : " + errorMsg);
throw launchValidationException;
}
}
public void cancelExperiment(ExperimentModel experiment, String tokenId) throws OrchestratorException {
logger.info("Terminating experiment " + experiment.getExperimentId());
RegistryService.Client registryServiceClient = getRegistryServiceClient();
try {
List<String> processIds = registryServiceClient.getProcessIds(experiment.getExperimentId());
if (processIds != null && processIds.size() > 0) {
for (String processId : processIds) {
logger.info("Terminating process " + processId + " of experiment " + experiment.getExperimentId());
jobSubmitter.terminate(experiment.getExperimentId(), processId, tokenId);
}
} else {
logger.warn("No processes found for experiment " + experiment.getExperimentId() + " to cancel");
}
} catch (TException e) {
logger.error("Failed to fetch process ids for experiment " + experiment.getExperimentId(), e);
throw new OrchestratorException("Failed to fetch process ids for experiment " + experiment.getExperimentId(), e);
}
}
public ExecutorService getExecutor() {
return executor;
}
public void setExecutor(ExecutorService executor) {
this.executor = executor;
}
public JobSubmitter getJobSubmitter() {
return jobSubmitter;
}
public void setJobSubmitter(JobSubmitter jobSubmitter) {
this.jobSubmitter = jobSubmitter;
}
public void initialize() throws OrchestratorException {
}
public List<ProcessModel> createProcesses (String experimentId, String gatewayId) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ExperimentModel experimentModel = registryClient.getExperiment(experimentId);
List<ProcessModel> processModels = registryClient.getProcessList(experimentId);
if (processModels == null || processModels.isEmpty()){
ProcessModel processModel = ExperimentModelUtil.cloneProcessFromExperiment(experimentModel);
String processId = registryClient.addProcess(processModel, experimentId);
processModel.setProcessId(processId);
processModels = new ArrayList<>();
processModels.add(processModel);
}
return processModels;
} catch (Exception e) {
throw new OrchestratorException("Error during creating process", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public String createAndSaveTasks(String gatewayId, ProcessModel processModel) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
ComputationalResourceSchedulingModel resourceSchedule = processModel.getProcessResourceSchedule();
String userGivenQueueName = resourceSchedule.getQueueName();
int userGivenWallTime = resourceSchedule.getWallTimeLimit();
String resourceHostId = resourceSchedule.getResourceHostId();
if (resourceHostId == null){
throw new OrchestratorException("Compute Resource Id cannot be null at this point");
}
ComputeResourceDescription computeResource = registryClient.getComputeResource(resourceHostId);
JobSubmissionInterface preferredJobSubmissionInterface =
OrchestratorUtils.getPreferredJobSubmissionInterface(processModel, gatewayId);
JobSubmissionProtocol preferredJobSubmissionProtocol = OrchestratorUtils.getPreferredJobSubmissionProtocol(processModel, gatewayId);
List<String> taskIdList = new ArrayList<>();
if (preferredJobSubmissionProtocol == JobSubmissionProtocol.UNICORE) {
// TODO - breakdown unicore all in one task to multiple tasks, then we don't need to handle UNICORE here.
taskIdList.addAll(createAndSaveSubmissionTasks(registryClient, gatewayId, preferredJobSubmissionInterface, processModel, userGivenWallTime));
} else {
taskIdList.addAll(createAndSaveEnvSetupTask(registryClient, gatewayId, processModel));
taskIdList.addAll(createAndSaveInputDataStagingTasks(processModel, gatewayId));
// if (autoSchedule) {
// List<BatchQueue> definedBatchQueues = computeResource.getBatchQueues();
// for (BatchQueue batchQueue : definedBatchQueues) {
// if (batchQueue.getQueueName().equals(userGivenQueueName)) {
// int maxRunTime = batchQueue.getMaxRunTime();
// if (maxRunTime < userGivenWallTime) {
// resourceSchedule.setWallTimeLimit(maxRunTime);
// // need to create more job submissions
// int numOfMaxWallTimeJobs = ((int) Math.floor(userGivenWallTime / maxRunTime));
// for (int i = 1; i <= numOfMaxWallTimeJobs; i++) {
// taskIdList.addAll(
// createAndSaveSubmissionTasks(registryClient, gatewayId, preferredJobSubmissionInterface, processModel, maxRunTime));
// }
// int leftWallTime = userGivenWallTime % maxRunTime;
// if (leftWallTime != 0) {
// taskIdList.addAll(
// createAndSaveSubmissionTasks(registryClient, gatewayId, preferredJobSubmissionInterface, processModel, leftWallTime));
// }
// } else {
// taskIdList.addAll(
// createAndSaveSubmissionTasks(registryClient, gatewayId, preferredJobSubmissionInterface, processModel, userGivenWallTime));
// }
// }
// }
// } else {
taskIdList.addAll(createAndSaveSubmissionTasks(registryClient, gatewayId, preferredJobSubmissionInterface, processModel, userGivenWallTime));
// }
taskIdList.addAll(createAndSaveOutputDataStagingTasks(processModel, gatewayId));
}
// update process scheduling
registryClient.updateProcess(processModel, processModel.getProcessId());
return getTaskDag(taskIdList);
} catch (Exception e) {
throw new OrchestratorException("Error during creating process", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public String createAndSaveIntermediateOutputFetchingTasks(String gatewayId, ProcessModel processModel,
ProcessModel parentProcess) throws OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
List<String> taskIdList = new ArrayList<>();
taskIdList.addAll(createAndSaveIntermediateOutputDataStagingTasks(processModel, gatewayId, parentProcess));
// update process scheduling
registryClient.updateProcess(processModel, processModel.getProcessId());
return getTaskDag(taskIdList);
} catch (Exception e) {
throw new OrchestratorException("Error during creating process", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private String getTaskDag(List<String> taskIdList) {
if (taskIdList.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String s : taskIdList) {
sb.append(s).append(","); // comma separated values
}
String dag = sb.toString();
return dag.substring(0, dag.length() - 1); // remove last comma
}
private List<String> createAndSaveEnvSetupTask(RegistryService.Client registryClient, String gatewayId,
ProcessModel processModel)
throws TException, AiravataException, OrchestratorException {
List<String> envTaskIds = new ArrayList<>();
TaskModel envSetupTask = new TaskModel();
envSetupTask.setTaskType(TaskTypes.ENV_SETUP);
envSetupTask.setTaskStatuses(Arrays.asList(new TaskStatus(TaskState.CREATED)));
envSetupTask.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
envSetupTask.setLastUpdateTime(AiravataUtils.getCurrentTimestamp().getTime());
envSetupTask.setParentProcessId(processModel.getProcessId());
EnvironmentSetupTaskModel envSetupSubModel = new EnvironmentSetupTaskModel();
envSetupSubModel.setProtocol(OrchestratorUtils.getSecurityProtocol(processModel, gatewayId));
String scratchLocation = OrchestratorUtils.getScratchLocation(processModel, gatewayId);
String workingDir = scratchLocation + File.separator + processModel.getProcessId();
envSetupSubModel.setLocation(workingDir);
byte[] envSetupSub = ThriftUtils.serializeThriftObject(envSetupSubModel);
envSetupTask.setSubTaskModel(envSetupSub);
envSetupTask.setMaxRetry(3);
envSetupTask.setCurrentRetry(0);
String envSetupTaskId = (String) registryClient.addTask(envSetupTask, processModel.getProcessId());
envSetupTask.setTaskId(envSetupTaskId);
envTaskIds.add(envSetupTaskId);
return envTaskIds;
}
public List<String> createAndSaveInputDataStagingTasks(ProcessModel processModel, String gatewayId)
throws AiravataException, OrchestratorException {
List<String> dataStagingTaskIds = new ArrayList<>();
List<InputDataObjectType> processInputs = processModel.getProcessInputs();
sortByInputOrder(processInputs);
if (processInputs != null) {
for (InputDataObjectType processInput : processInputs) {
DataType type = processInput.getType();
switch (type) {
case STDERR:
break;
case STDOUT:
break;
case URI:
case URI_COLLECTION:
if ((processInput.getValue() == null || processInput.getValue().equals("")) && !processInput.isIsRequired()) {
logger.debug("Skipping input data staging task for {} since value is empty and not required", processInput.getName());
break;
}
final RegistryService.Client registryClient = getRegistryServiceClient();
try {
TaskModel inputDataStagingTask = getInputDataStagingTask(registryClient, processModel, processInput, gatewayId);
String taskId = registryClient
.addTask( inputDataStagingTask, processModel.getProcessId());
inputDataStagingTask.setTaskId(taskId);
dataStagingTaskIds.add(inputDataStagingTask.getTaskId());
} catch (Exception e) {
throw new AiravataException("Error while serializing data staging sub task model", e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
break;
default:
// nothing to do
break;
}
}
}
return dataStagingTaskIds;
}
public List<String> createAndSaveOutputDataStagingTasks(ProcessModel processModel, String gatewayId)
throws AiravataException, TException, OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
List<String> dataStagingTaskIds = new ArrayList<>();
try {
List<OutputDataObjectType> processOutputs = processModel.getProcessOutputs();
String appName = OrchestratorUtils.getApplicationInterfaceName(processModel);
if (processOutputs != null) {
for (OutputDataObjectType processOutput : processOutputs) {
DataType type = processOutput.getType();
switch (type) {
case STDOUT:
if (null == processOutput.getValue() || processOutput.getValue().trim().isEmpty()) {
processOutput.setValue(appName + ".stdout");
}
createOutputDataSatagingTasks(registryClient, processModel, gatewayId, dataStagingTaskIds, processOutput);
break;
case STDERR:
if (null == processOutput.getValue() || processOutput.getValue().trim().isEmpty()) {
processOutput.setValue(appName + ".stderr");
}
createOutputDataSatagingTasks(registryClient, processModel, gatewayId, dataStagingTaskIds, processOutput);
break;
case URI:
case URI_COLLECTION:
createOutputDataSatagingTasks(registryClient, processModel, gatewayId, dataStagingTaskIds, processOutput);
break;
default:
// nothing to do
break;
}
}
}
try {
if (isArchive(registryClient, processModel, orchestratorContext)) {
createArchiveDataStatgingTask(registryClient, processModel, gatewayId, dataStagingTaskIds);
}
} catch (Exception e) {
throw new AiravataException("Error! Application interface retrieval failed", e);
}
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
return dataStagingTaskIds;
}
public List<String> createAndSaveIntermediateOutputDataStagingTasks(ProcessModel processModel, String gatewayId,
ProcessModel parentProcess)
throws AiravataException, TException, OrchestratorException {
final RegistryService.Client registryClient = getRegistryServiceClient();
List<String> dataStagingTaskIds = new ArrayList<>();
try {
List<OutputDataObjectType> processOutputs = processModel.getProcessOutputs();
String appName = OrchestratorUtils.getApplicationInterfaceName(processModel);
if (processOutputs != null) {
for (OutputDataObjectType processOutput : processOutputs) {
DataType type = processOutput.getType();
switch (type) {
case STDOUT:
if (null == processOutput.getValue() || processOutput.getValue().trim().isEmpty()) {
processOutput.setValue(appName + ".stdout");
}
createIntermediateOutputDataStagingTasks(registryClient, processModel, gatewayId,
parentProcess, dataStagingTaskIds, processOutput);
break;
case STDERR:
if (null == processOutput.getValue() || processOutput.getValue().trim().isEmpty()) {
processOutput.setValue(appName + ".stderr");
}
createIntermediateOutputDataStagingTasks(registryClient, processModel, gatewayId,
parentProcess, dataStagingTaskIds, processOutput);
break;
case URI:
case URI_COLLECTION:
createIntermediateOutputDataStagingTasks(registryClient, processModel, gatewayId,
parentProcess, dataStagingTaskIds, processOutput);
break;
default:
// nothing to do
break;
}
}
}
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
return dataStagingTaskIds;
}
private boolean isArchive(RegistryService.Client registryClient, ProcessModel processModel, OrchestratorContext orchestratorContext) throws TException {
ApplicationInterfaceDescription appInterface = registryClient
.getApplicationInterface(processModel.getApplicationInterfaceId());
return appInterface.isArchiveWorkingDirectory();
}
private void createArchiveDataStatgingTask(RegistryService.Client registryClient, ProcessModel processModel,
String gatewayId,
List<String> dataStagingTaskIds) throws AiravataException, TException, OrchestratorException {
TaskModel archiveTask = null;
try {
archiveTask = getOutputDataStagingTask(registryClient, processModel, null, gatewayId, null);
} catch (TException e) {
throw new AiravataException("Error! DataStaging sub task serialization failed", e);
}
String taskId = registryClient
.addTask(archiveTask, processModel.getProcessId());
archiveTask.setTaskId(taskId);
dataStagingTaskIds.add(archiveTask.getTaskId());
}
private void createOutputDataSatagingTasks(RegistryService.Client registryClient, ProcessModel processModel,
String gatewayId,
List<String> dataStagingTaskIds,
OutputDataObjectType processOutput) throws AiravataException, OrchestratorException {
try {
TaskModel outputDataStagingTask = getOutputDataStagingTask(registryClient, processModel, processOutput, gatewayId, null);
String taskId = registryClient
.addTask(outputDataStagingTask, processModel.getProcessId());
outputDataStagingTask.setTaskId(taskId);
dataStagingTaskIds.add(outputDataStagingTask.getTaskId());
} catch (TException e) {
throw new AiravataException("Error while serializing data staging sub task model", e);
}
}
private void createIntermediateOutputDataStagingTasks(RegistryService.Client registryClient,
ProcessModel processModel,
String gatewayId,
ProcessModel parentProcess,
List<String> dataStagingTaskIds,
OutputDataObjectType processOutput) throws AiravataException, OrchestratorException {
try {
TaskModel outputDataStagingTask = getOutputDataStagingTask(registryClient, processModel, processOutput,
gatewayId, parentProcess);
outputDataStagingTask.setTaskType(TaskTypes.OUTPUT_FETCHING);
String taskId = registryClient
.addTask(outputDataStagingTask, processModel.getProcessId());
outputDataStagingTask.setTaskId(taskId);
dataStagingTaskIds.add(outputDataStagingTask.getTaskId());
} catch (TException e) {
throw new AiravataException("Error while serializing data staging sub task model", e);
}
}
private List<String> createAndSaveSubmissionTasks(RegistryService.Client registryClient, String gatewayId,
JobSubmissionInterface jobSubmissionInterface,
ProcessModel processModel,
int wallTime)
throws TException, OrchestratorException {
JobSubmissionProtocol jobSubmissionProtocol = jobSubmissionInterface.getJobSubmissionProtocol();
MonitorMode monitorMode = null;
if (jobSubmissionProtocol == JobSubmissionProtocol.SSH || jobSubmissionProtocol == JobSubmissionProtocol.SSH_FORK) {
SSHJobSubmission sshJobSubmission = OrchestratorUtils.getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
monitorMode = sshJobSubmission.getMonitorMode();
} else if (jobSubmissionProtocol == JobSubmissionProtocol.UNICORE) {
monitorMode = MonitorMode.FORK;
} else if(jobSubmissionProtocol == JobSubmissionProtocol.LOCAL){
monitorMode = MonitorMode.LOCAL;
} else if (jobSubmissionProtocol == JobSubmissionProtocol.CLOUD) {
monitorMode = MonitorMode.CLOUD_JOB_MONITOR;
}else {
logger.error("expId : {}, processId : {} :- Unsupported Job submission protocol {}.",
processModel.getExperimentId(), processModel.getProcessId(), jobSubmissionProtocol.name());
throw new OrchestratorException("Unsupported Job Submission Protocol " + jobSubmissionProtocol.name());
}
List<String> submissionTaskIds = new ArrayList<>();
TaskModel taskModel = new TaskModel();
taskModel.setParentProcessId(processModel.getProcessId());
taskModel.setCreationTime(System.currentTimeMillis());
taskModel.setLastUpdateTime(taskModel.getCreationTime());
TaskStatus taskStatus = new TaskStatus(TaskState.CREATED);
taskStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
taskModel.setTaskStatuses(Arrays.asList(taskStatus));
taskModel.setTaskType(TaskTypes.JOB_SUBMISSION);
JobSubmissionTaskModel submissionSubTask = new JobSubmissionTaskModel();
submissionSubTask.setMonitorMode(monitorMode);
submissionSubTask.setJobSubmissionProtocol(jobSubmissionProtocol);
submissionSubTask.setWallTime(wallTime);
byte[] bytes = ThriftUtils.serializeThriftObject(submissionSubTask);
taskModel.setSubTaskModel(bytes);
taskModel.setMaxRetry(1);
taskModel.setCurrentRetry(0);
String taskId = registryClient.addTask(taskModel, processModel.getProcessId());
taskModel.setTaskId(taskId);
submissionTaskIds.add(taskModel.getTaskId());
// create monitor task for this Email based monitor mode job
if (monitorMode == MonitorMode.JOB_EMAIL_NOTIFICATION_MONITOR
|| monitorMode == MonitorMode.CLOUD_JOB_MONITOR) {
TaskModel monitorTaskModel = new TaskModel();
monitorTaskModel.setParentProcessId(processModel.getProcessId());
monitorTaskModel.setCreationTime(System.currentTimeMillis());
monitorTaskModel.setLastUpdateTime(monitorTaskModel.getCreationTime());
TaskStatus monitorTaskStatus = new TaskStatus(TaskState.CREATED);
monitorTaskStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
monitorTaskModel.setTaskStatuses(Arrays.asList(monitorTaskStatus));
monitorTaskModel.setTaskType(TaskTypes.MONITORING);
MonitorTaskModel monitorSubTaskModel = new MonitorTaskModel();
monitorSubTaskModel.setMonitorMode(monitorMode);
monitorTaskModel.setSubTaskModel(ThriftUtils.serializeThriftObject(monitorSubTaskModel));
String mTaskId = (String) registryClient.addTask(monitorTaskModel, processModel.getProcessId());
monitorTaskModel.setTaskId(mTaskId);
submissionTaskIds.add(monitorTaskModel.getTaskId());
}
return submissionTaskIds;
}
private void sortByInputOrder(List<InputDataObjectType> processInputs) {
Collections.sort(processInputs, new Comparator<InputDataObjectType>() {
@Override
public int compare(InputDataObjectType inputDT_1, InputDataObjectType inputDT_2) {
return inputDT_1.getInputOrder() - inputDT_2.getInputOrder();
}
});
}
private TaskModel getInputDataStagingTask(RegistryService.Client registryClient, ProcessModel processModel, InputDataObjectType processInput, String gatewayId) throws TException, AiravataException, OrchestratorException {
// create new task model for this task
TaskModel taskModel = new TaskModel();
taskModel.setParentProcessId(processModel.getProcessId());
taskModel.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
taskModel.setLastUpdateTime(taskModel.getCreationTime());
TaskStatus taskStatus = new TaskStatus(TaskState.CREATED);
taskStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
taskModel.setTaskStatuses(Arrays.asList(taskStatus));
taskModel.setTaskType(TaskTypes.DATA_STAGING);
// create data staging sub task model
DataStagingTaskModel submodel = new DataStagingTaskModel();
ComputeResourceDescription computeResource = registryClient.
getComputeResource(processModel.getComputeResourceId());
String scratchLocation = OrchestratorUtils.getScratchLocation(processModel, gatewayId);
String workingDir = (scratchLocation.endsWith(File.separator) ? scratchLocation : scratchLocation + File.separator) +
processModel.getProcessId() + File.separator;
URI destination = null;
try {
DataMovementProtocol dataMovementProtocol =
OrchestratorUtils.getPreferredDataMovementProtocol(processModel, gatewayId);
String loginUserName = OrchestratorUtils.getLoginUserName(processModel, gatewayId);
StringBuilder destinationPath = new StringBuilder(workingDir);
Optional.ofNullable(processInput.getOverrideFilename()).ifPresent(destinationPath::append); //If an override filename is provided
destination = new URI(dataMovementProtocol.name(),
loginUserName,
computeResource.getHostName(),
OrchestratorUtils.getDataMovementPort(processModel, gatewayId),
destinationPath.toString(), null, null);
} catch (URISyntaxException e) {
throw new OrchestratorException("Error while constructing destination file URI", e);
}
submodel.setType(DataStageType.INPUT);
submodel.setSource(processInput.getValue());
submodel.setProcessInput(processInput);
submodel.setDestination(destination.toString());
taskModel.setSubTaskModel(ThriftUtils.serializeThriftObject(submodel));
taskModel.setMaxRetry(3);
taskModel.setCurrentRetry(0);
return taskModel;
}
private TaskModel getOutputDataStagingTask(RegistryService.Client registryClient, ProcessModel processModel,
OutputDataObjectType processOutput, String gatewayId,
ProcessModel parentProcess) throws TException, AiravataException, OrchestratorException {
try {
// create new task model for this task
TaskModel taskModel = new TaskModel();
taskModel.setParentProcessId(processModel.getProcessId());
taskModel.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
taskModel.setLastUpdateTime(taskModel.getCreationTime());
TaskStatus taskStatus = new TaskStatus(TaskState.CREATED);
taskStatus.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime());
taskModel.setTaskStatuses(Arrays.asList(taskStatus));
taskModel.setTaskType(TaskTypes.DATA_STAGING);
ComputeResourceDescription computeResource = registryClient.
getComputeResource(processModel.getComputeResourceId());
String workingDir = OrchestratorUtils.getScratchLocation(processModel, gatewayId)
+ File.separator + (parentProcess == null ? processModel.getProcessId() : parentProcess.getProcessId()) + File.separator;
DataStagingTaskModel submodel = new DataStagingTaskModel();
DataMovementProtocol dataMovementProtocol = OrchestratorUtils.getPreferredDataMovementProtocol(processModel, gatewayId);
URI source = null;
try {
String loginUserName = OrchestratorUtils.getLoginUserName(processModel, gatewayId);
if (processOutput != null) {
submodel.setType(DataStageType.OUPUT);
submodel.setProcessOutput(processOutput);
source = new URI(dataMovementProtocol.name(),
loginUserName,
computeResource.getHostName(),
OrchestratorUtils.getDataMovementPort(processModel, gatewayId),
workingDir + processOutput.getValue(), null, null);
} else {
// archive
submodel.setType(DataStageType.ARCHIVE_OUTPUT);
source = new URI(dataMovementProtocol.name(),
loginUserName,
computeResource.getHostName(),
OrchestratorUtils.getDataMovementPort(processModel, gatewayId),
workingDir, null, null);
}
} catch (URISyntaxException e) {
throw new OrchestratorException("Error while constructing source file URI", e);
}
// We don't know destination location at this time, data staging task will set this.
// because destination is required field we set dummy destination
submodel.setSource(source.toString());
// We don't know destination location at this time, data staging task will set this.
// because destination is required field we set dummy destination
submodel.setDestination("dummy://temp/file/location");
taskModel.setSubTaskModel(ThriftUtils.serializeThriftObject(submodel));
taskModel.setMaxRetry(3);
taskModel.setCurrentRetry(0);
return taskModel;
} catch (OrchestratorException e) {
throw new OrchestratorException("Error occurred while retrieving data movement from app catalog", e);
}
}
private RegistryService.Client getRegistryServiceClient() {
try {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException|ApplicationSettingsException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
}
| 1,196 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/test/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/test/java/org/apache/airavata/orchestrator/client/OrchestratorClientFactoryTest.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.orchestrator.client;
//import org.apache.airavata.client.AiravataAPIFactory;
//import org.apache.airavata.client.api.exception.AiravataAPIInvocationException;
//import org.apache.airavata.client.tools.DocumentCreator;
//import org.apache.airavata.client.tools.DocumentCreatorNew;
public class OrchestratorClientFactoryTest {
/* private DocumentCreatorNew documentCreator;
private OrchestratorService.Client orchestratorClient;
private Registry registry;
private int NUM_CONCURRENT_REQUESTS = 1;
Initialize initialize;
OrchestratorServer service;
private static ServerCnxnFactory cnxnFactory;
@Test
public void setUp() {
AiravataUtils.setExecutionAsServer();
initialize = new Initialize("registry-derby.sql");
initialize.initializeDB();
System.setProperty(Constants.ZOOKEEPER_SERVER_PORT,"2185");
AiravataZKUtils.startEmbeddedZK(cnxnFactory);
try {
service = (new OrchestratorServer());
service.start();
registry = RegistryFactory.getDefaultExpCatalog();
documentCreator = new DocumentCreatorNew(getAiravataClient());
documentCreator.createLocalHostDocs();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
AiravataUtils.setExecutionAsServer();
try {
service.stop();
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
private Airavata.Client getAiravataClient() {
Airavata.Client client = null;
try {
client = AiravataClientFactory.createAiravataClient("localhost", 8930);
} catch (AiravataClientConnectException e) {
e.printStackTrace();
}
return client;
}
private void storeDescriptors() {
}*/
}
| 1,197 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator/util/OrchestratorUtils.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.orchestrator.util;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.status.ExperimentStatus;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrchestratorUtils {
private static final Logger log = LoggerFactory.getLogger(OrchestratorUtils.class);
public static void updateAndPublishExperimentStatus(String experimentId, ExperimentStatus status, Publisher publisher, String gatewayId) throws TException {
RegistryService.Client registryClient = null;
try {
registryClient = getRegistryServiceClient();
registryClient.updateExperimentStatus(status,
experimentId);
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent(status.getState(),
experimentId,
gatewayId);
String messageId = AiravataUtils.getId("EXPERIMENT");
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
publisher.publish(messageContext);
} catch (AiravataException e) {
log.error("expId : " + experimentId + " Error while publishing experiment status to " + status.toString(), e);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static ExperimentStatus getExperimentStatus(String experimentId) throws TException, ApplicationSettingsException {
RegistryService.Client registryClient = null;
try {
registryClient = getRegistryServiceClient();
return registryClient.getExperimentStatus(experimentId);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
public static ProcessModel getProcess(String processId) throws TException, ApplicationSettingsException {
RegistryService.Client registryClient = null;
try {
registryClient = getRegistryServiceClient();
return registryClient.getProcess(processId);
} finally {
if (registryClient != null) {
ThriftUtils.close(registryClient);
}
}
}
private static RegistryService.Client getRegistryServiceClient() throws ApplicationSettingsException {
final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
final String serverHost = ServerSettings.getRegistryServerHost();
try {
return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
} catch (RegistryServiceException e) {
throw new RuntimeException("Unable to create registry client...", e);
}
}
}
| 1,198 |
0 | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator | Create_ds/airavata/modules/orchestrator/orchestrator-service/src/main/java/org/apache/airavata/orchestrator/util/OrchestratorServerThreadPoolExecutor.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.orchestrator.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrchestratorServerThreadPoolExecutor {
private final static Logger logger = LoggerFactory.getLogger(OrchestratorServerThreadPoolExecutor.class);
public static final String AIRAVATA_SERVER_THREAD_POOL_SIZE = "airavata.server.thread.pool.size";
private static ExecutorService threadPool;
public static ExecutorService getCachedThreadPool() {
if(threadPool ==null){
threadPool = Executors.newCachedThreadPool();
}
return threadPool;
}
public static ExecutorService getFixedThreadPool() {
if(threadPool ==null){
try {
threadPool = Executors.newFixedThreadPool(Integer.parseInt(ServerSettings.getSetting(AIRAVATA_SERVER_THREAD_POOL_SIZE)));
} catch (ApplicationSettingsException e) {
logger.error("Error reading " + AIRAVATA_SERVER_THREAD_POOL_SIZE+ " property");
}
}
return threadPool;
}
}
| 1,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.