JobManagementLogic.cs 19.3 KB
Newer Older
Vaclav Svaton's avatar
Vaclav Svaton committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using HaaSMiddleware.BusinessLogicTier.Factory;
using HaaSMiddleware.BusinessLogicTier.Logic.JobManagement.Exceptions;
using HaaSMiddleware.BusinessLogicTier.Logic.UserAndLimitationManagement;
using HaaSMiddleware.BusinessLogicTier.Logic.UserAndLimitationManagement.Exceptions;
using HaaSMiddleware.DataAccessTier.UnitOfWork;
using HaaSMiddleware.DomainObjects.ClusterInformation;
using HaaSMiddleware.DomainObjects.JobManagement;
using HaaSMiddleware.DomainObjects.JobManagement.JobInformation;
using HaaSMiddleware.DomainObjects.UserAndLimitationManagement;
using HaaSMiddleware.FileTransferFramework;
using HaaSMiddleware.HpcConnectionFramework;
using log4net;
using System.Net;

namespace HaaSMiddleware.BusinessLogicTier.Logic.JobManagement {
	internal class JobManagementLogic : IJobManagementLogic {
		private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
		private readonly IUnitOfWork unitOfWork;

		internal JobManagementLogic(IUnitOfWork unitOfWork) {
			this.unitOfWork = unitOfWork;
		}

		public SubmittedJobInfo CreateJob(JobSpecification specification, AdaptorUser loggedUser) {
			log.Info("User " + loggedUser.GetLogIdentification() + " is creating a job specified as " + specification);
			IUserAndLimitationManagementLogic userLogic = LogicFactory.GetLogicFactory().CreateUserAndLimitationManagementLogic(unitOfWork);
			ResourceUsage currentUsage =
				(from usage in userLogic.GetCurrentUsageAndLimitationsForUser(loggedUser) where usage.NodeType == specification.NodeType select usage).FirstOrDefault();
			if (currentUsage != null) {
				if (CheckRequestedResourcesAgainstLimitations(ref specification, currentUsage)) {
					CombineSpecificationWithJobTemplate(specification, specification.NodeType.JobTemplate);
					CompleteJobSpecification(specification, loggedUser);
					unitOfWork.JobSpecificationRepository.Insert(specification);
					SubmittedJobInfo jobInfo = CreateSubmittedJobInfo(specification);
					unitOfWork.SubmittedJobInfoRepository.Insert(jobInfo);
					unitOfWork.Save();
					// Create job directory
					SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType).CreateScheduler(jobInfo.NodeType.Cluster).CreateJobDirectory(jobInfo);
					return jobInfo;
				}
				log.Error("Requested resources for job " + specification.Name + " exceeded user limitations.");
				throw new RequestedJobResourcesExceededUserLimitationsException("Requested resources for job " + specification.Name + " exceeded user limitations.");
			}
			log.Error("Current usage for user " + loggedUser.GetLogIdentification() + " and node type " + specification.NodeType +
			          " was not created by the GetCurrentUsageAndLimitationsForUser method.");
			throw new NotImplementedException("Current usage for user " + loggedUser.GetLogIdentification() + " and node type " + specification.NodeType +
			                                  " was not created by the GetCurrentUsageAndLimitationsForUser method.");
		}

		public SubmittedJobInfo SubmitJob(long createdJobInfoId, AdaptorUser loggedUser) {
			log.Info("User " + loggedUser.GetLogIdentification() + " is submitting the job with info Id " + createdJobInfoId);
			SubmittedJobInfo jobInfo = GetSubmittedJobInfoById(createdJobInfoId, loggedUser);
			SubmittedJobInfo clusterJobInfo =
				SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType)
					.CreateScheduler(jobInfo.NodeType.Cluster)
					.SubmitJob(jobInfo.Specification, jobInfo.Specification.ClusterUser);
			jobInfo = CombineSubmittedJobInfoFromCluster(jobInfo, clusterJobInfo);
			unitOfWork.SubmittedJobInfoRepository.Update(jobInfo);
			unitOfWork.Save();
			return jobInfo;
		}

		public SubmittedJobInfo CancelJob(long submittedJobInfoId, AdaptorUser loggedUser) {
			log.Info("User " + loggedUser.GetLogIdentification() + " is canceling the job with info Id " + submittedJobInfoId);
			SubmittedJobInfo jobInfo = GetSubmittedJobInfoById(submittedJobInfoId, loggedUser);
			if (jobInfo.State >= JobState.Finished) {
				return jobInfo;
			}
			IRexScheduler scheduler = SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType).CreateScheduler(jobInfo.NodeType.Cluster);
			if (jobInfo.State != JobState.Configuring) {
				scheduler.CancelJob(jobInfo.ScheduledJobId, jobInfo.Specification.ClusterUser);
			}
			//FileSystemFactory.GetInstance(jobInfo.NodeType.FileTransferMethod.Protocol)
			//	.CreateFileSystemManager(jobInfo.NodeType.FileTransferMethod)
			//	.DeleteSessionFromCluster(jobInfo);
			SubmittedJobInfo clusterJobInfo = scheduler.GetActualJobInfo(jobInfo.ScheduledJobId, jobInfo.Specification.ClusterUser);
			jobInfo = CombineSubmittedJobInfoFromCluster(jobInfo, clusterJobInfo);
			unitOfWork.SubmittedJobInfoRepository.Update(jobInfo);
			unitOfWork.Save();
			return jobInfo;
		}

        public void DeleteJob(long submittedJobInfoId, AdaptorUser loggedUser)
        {
            log.Info("User " + loggedUser.GetLogIdentification() + " is deleting the job with info Id " + submittedJobInfoId);
            SubmittedJobInfo jobInfo = GetSubmittedJobInfoById(submittedJobInfoId, loggedUser);
93
            if (jobInfo.State == JobState.Configuring || jobInfo.State >= JobState.Finished)
Vaclav Svaton's avatar
Vaclav Svaton committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            {
                #warning Renci SSH.NET bug - resolving paths when deleting symlink, use ssh delete instead
                //FileSystemFactory.GetInstance(jobInfo.NodeType.FileTransferMethod.Protocol)
                //    .CreateFileSystemManager(jobInfo.NodeType.FileTransferMethod)
                //    .DeleteSessionFromCluster(jobInfo);
                SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType).CreateScheduler(jobInfo.NodeType.Cluster).DeleteJobDirectory(jobInfo);
            }
        }

		public SubmittedJobInfo GetSubmittedJobInfoById(long submittedJobInfoId, AdaptorUser loggedUser) {
			SubmittedJobInfo jobInfo = unitOfWork.SubmittedJobInfoRepository.GetById(submittedJobInfoId);
			if (jobInfo == null) {
				log.Error("Requested job info with Id=" + submittedJobInfoId + " does not exist in the system.");
				throw new RequestedObjectDoesNotExistException("Requested job info with Id=" + submittedJobInfoId + " does not exist in the system.");
			}
			if (!LogicFactory.GetLogicFactory().CreateUserAndLimitationManagementLogic(unitOfWork).AuthorizeUserForJobInfo(loggedUser, jobInfo)) {
				log.Error("Logged user " + loggedUser.GetLogIdentification() + " is not authorized to work with job info with ID " + submittedJobInfoId +
				          ". This job was submitted by user " + jobInfo.Submitter.GetLogIdentification() + " for group " + jobInfo.Specification.SubmitterGroup.Name);
				throw new AdaptorUserNotAuthorizedForJobException("Logged user " + loggedUser.GetLogIdentification() + " is not authorized to work with job info with ID " +
				                                                  submittedJobInfoId);
			}
			return jobInfo;
		}

		public IList<SubmittedJobInfo> ListJobsForUser(AdaptorUser loggedUser) {
			return unitOfWork.SubmittedJobInfoRepository.ListAllForSubmitterId(loggedUser.Id);
		}

		public CommandTemplate GetCommandTemplateById(long commandTemplateId) {
			return unitOfWork.CommandTemplateRepository.GetById(commandTemplateId);
		}

		public CommandTemplateParameter GetCommandTemplateParameterForTemplateAndIdentifier(long commandTemplateId, string identifier) {
			return (from templateParameter in unitOfWork.CommandTemplateRepository.GetById(commandTemplateId).TemplateParameters
				where templateParameter.Identifier == identifier
				select templateParameter).FirstOrDefault();
		}

		public IList<SubmittedJobInfo> ListNotFinishedJobInfosForSubmitterId(long submitterId) {
			return unitOfWork.SubmittedJobInfoRepository.ListNotFinishedForSubmitterId(submitterId);
		}

		public IList<SubmittedJobInfo> ListNotFinishedJobInfos() {
			return unitOfWork.SubmittedJobInfoRepository.ListAllUnfinished();
		}

		/// <summary>
		/// Contacts cluster and retreives info about jobs with state higher than Configuring and lower than Finished.
		/// Method updates jobs in db with received info.
		/// </summary>
		/// <returns>Collection of updated job info (contains only jobs where status change occured since last update).</returns>
		public IList<SubmittedJobInfo> UpdateCurrentStateOfUnfinishedJobs() {
			List<SubmittedJobInfo> result = new List<SubmittedJobInfo>();
			// Load jobs
			List<SubmittedJobInfo> unfinishedJobInfoDb = (List<SubmittedJobInfo>) unitOfWork.SubmittedJobInfoRepository.ListAllUnfinished();
			var jobsGroup = (from job in unfinishedJobInfoDb
				group job by job.NodeType.Cluster
				into jobGroup
				orderby jobGroup.Key
				select jobGroup).ToList();

			foreach (var jobGroup in jobsGroup) {
			Cluster cluster = jobGroup.Key;
				// Get updated status from cluster
				int[] jobIds = (from job in jobGroup where job.State > JobState.Configuring select job.ScheduledJobId).ToArray();
				List<SubmittedJobInfo> unfinishedJobInfoCluster =
					(SchedulerFactory.GetInstance(cluster.SchedulerType).CreateScheduler(cluster).GetActualJobsInfo(jobIds, cluster)).ToList();
				// Combine the objects together
				foreach (var clusterJob in unfinishedJobInfoCluster) {
					if (clusterJob != null)
					{
						// Search for jobs in db by scheduler id
						SubmittedJobInfo jobDb = (from job in jobGroup where job.ScheduledJobId == clusterJob.ScheduledJobId select job).First();
						if (jobDb.State != clusterJob.State)
						{
							// Combine together with actual info from cluster
							jobDb = CombineSubmittedJobInfoFromCluster(jobDb, clusterJob);
							// Append to output collection
							result.Add(jobDb);
							// Update and save to DB
							unitOfWork.SubmittedJobInfoRepository.Update(jobDb);
						}
					}
				}
			}
			// Save unit of work
			unitOfWork.Save();
			return result;
		}

        public void CopyJobDataToTemp(long submittedJobInfoId, AdaptorUser loggedUser, string hash, string path)
        {
            log.Info(string.Format("User {0} with job Id {1} is copying job data to temp {2}", loggedUser.GetLogIdentification(), submittedJobInfoId, hash));
            SubmittedJobInfo jobInfo = GetSubmittedJobInfoById(submittedJobInfoId, loggedUser);
            SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType)
                    .CreateScheduler(jobInfo.NodeType.Cluster)
                    .CopyJobDataToTemp(jobInfo, hash, path);
        }

        public void CopyJobDataFromTemp(long createdJobInfoId, AdaptorUser loggedUser, string hash)
        {
            log.Info(string.Format("User {0} with job Id {1} is copying job data from temp {2}", loggedUser.GetLogIdentification(), createdJobInfoId, hash));
            SubmittedJobInfo jobInfo = GetSubmittedJobInfoById(createdJobInfoId, loggedUser);
            SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType)
                    .CreateScheduler(jobInfo.NodeType.Cluster)
                    .CopyJobDataFromTemp(jobInfo, hash);
        }

        public List<string> GetAllocatedNodesIPs(long submittedJobInfoId, AdaptorUser loggedUser)
        {
            SubmittedJobInfo jobInfo = LogicFactory.GetLogicFactory().CreateJobManagementLogic(unitOfWork).GetSubmittedJobInfoById(submittedJobInfoId, loggedUser);
            if (jobInfo.State >= JobState.Running)
            {
                List<string> stringIPs = SchedulerFactory.GetInstance(jobInfo.NodeType.Cluster.SchedulerType).CreateScheduler(jobInfo.NodeType.Cluster).GetAllocatedNodes(jobInfo);
                //List<byte[]> byteIPs = new List<byte[]>();
                //foreach (string sip in stringIPs)
                //{
                //    byte[] bip = IPAddress.Parse(sip).GetAddressBytes();
                //    byteIPs.Add(bip);
                //}
                //return byteIPs;
                return stringIPs;
            }
            return null;
        }

        private bool CheckRequestedResourcesAgainstLimitations(ref JobSpecification specification, ResourceUsage currentUsage) {
			if (currentUsage.Limitation == null || !currentUsage.Limitation.TotalMaxCores.HasValue)
				return true;
			int availableCores = currentUsage.Limitation.TotalMaxCores.Value - currentUsage.CoresUsed;
			if (currentUsage.Limitation.MaxCoresPerJob.HasValue && availableCores > currentUsage.Limitation.MaxCoresPerJob.Value)
				availableCores = currentUsage.Limitation.MaxCoresPerJob.Value;
			if (availableCores < specification.MinCores)
				return false;
			if (availableCores < specification.MaxCores)
				specification.MaxCores = availableCores;
			return true;
		}

		private void CombineSpecificationWithJobTemplate(JobSpecification specification, JobTemplate jobTemplate) {
			if (jobTemplate != null && jobTemplate.PropertyChangeSpecification != null) {
				foreach (PropertyChangeSpecification propertyChange in jobTemplate.PropertyChangeSpecification) {
					PropertyInfo property = specification.GetType().GetProperty(propertyChange.PropertyName);
					object clientPropertyValue = property.GetValue(specification, null);
					if (clientPropertyValue != null) {
						object newPropertyValue = CombinePropertyValues(propertyChange, property.GetValue(jobTemplate, null), clientPropertyValue);
						property.SetValue(specification, newPropertyValue, null);
					}
				}
			}
		}

		private object CombinePropertyValues(PropertyChangeSpecification propertyChange, object templateValue, object clientValue) {
			switch (propertyChange.ChangeMethod) {
				case PropertyChangeMethod.Append:
					if (templateValue == null)
						return clientValue;
					if (clientValue == null)
						return templateValue;
					if (clientValue is bool) {
						return (((bool) templateValue) || ((bool) clientValue));
					}
					if (clientValue is string) {
						return ((string) templateValue) + ((string) clientValue);
					}
					if (clientValue is int) {
						return ((int) templateValue) + ((int) clientValue);
					}
					if (clientValue is float) {
						return ((float) templateValue) + ((float) clientValue);
					}
					if (clientValue is double) {
						return ((double) templateValue) + ((double) clientValue);
					}
					if (clientValue is ICollection) {

						ICollection arrayClientValue = (ICollection)clientValue;
						ArrayList arrayTemplateValue = new ArrayList();
						foreach (var item in (IEnumerable)templateValue)
						{
							arrayTemplateValue.Add((item as ICloneable).Clone());
						}
						Array returnArray = Array.CreateInstance(arrayClientValue.GetType().GetElementType(), arrayTemplateValue.Count + arrayClientValue.Count);
						arrayTemplateValue.CopyTo(returnArray, 0);
						arrayClientValue.CopyTo(returnArray, arrayTemplateValue.Count);
						return returnArray;
					}
					log.Error("Property with name \"" + propertyChange.PropertyName + "\" with values \"" + templateValue + "\",\"" + clientValue +
					          "\" could not be appended because its type cannot be appended.");
					throw new UnableToAppendToJobTemplatePropertyException("Property with name \"" + propertyChange.PropertyName + "\" with values \"" + templateValue +
					                                                       "\",\"" + clientValue + "\" could not be appended because its type cannot be appended.");
				case PropertyChangeMethod.Rewrite:
					return clientValue;
				default:
					log.Error("Method \"" + propertyChange.ChangeMethod + "\" for changing the properties values is not supported.");
					throw new ArgumentException("Method \"" + propertyChange.ChangeMethod +
					                                                       "\" for changing the properties values is not supported.");
			}
		}

		private void CompleteJobSpecification(JobSpecification specification, AdaptorUser loggedUser) {
			specification.ClusterUser =
				LogicFactory.GetLogicFactory().CreateClusterInformationLogic(unitOfWork).GetNextAvailableUserCredentials(specification.NodeType.Cluster.Id);
			specification.Submitter = loggedUser;
			if (specification.SubmitterGroup == null)
				specification.SubmitterGroup = LogicFactory.GetLogicFactory().CreateUserAndLimitationManagementLogic(unitOfWork).GetDefaultSubmitterGroup(loggedUser);
			foreach (TaskSpecification task in specification.Tasks) {
				task.EnvironmentVariables = CombineJobAndTaskEnvironmentVariables(specification.EnvironmentVariables, task.EnvironmentVariables);
				task.MinCores = task.MinCores ?? specification.MinCores;
				task.MaxCores = task.MaxCores ?? specification.MaxCores;
			}
		}

		private EnvironmentVariable[] CombineJobAndTaskEnvironmentVariables(IEnumerable<EnvironmentVariable> jobVariables,
			IEnumerable<EnvironmentVariable> taskVariables) {
			Dictionary<string, EnvironmentVariable> variables = new Dictionary<string, EnvironmentVariable>();
			if (jobVariables != null)
				foreach (EnvironmentVariable jobVariable in jobVariables)
					variables[jobVariable.Name] = jobVariable;
			if (taskVariables != null)
				foreach (EnvironmentVariable taskVariable in taskVariables)
					variables[taskVariable.Name] = taskVariable;
			return (from v in variables.Values select v).ToArray();
		}

		private SubmittedJobInfo CreateSubmittedJobInfo(JobSpecification specification) {
			SubmittedJobInfo result = new SubmittedJobInfo {
				CreationTime = DateTime.Now,
				Name = specification.Name,
				NodeType = specification.NodeType,
				Priority = specification.Priority ?? JobPriority.Average,
				Project = specification.Project,
				Specification = specification,
				State = JobState.Configuring,
				Submitter = specification.Submitter,
				Tasks = (from taskSpecification in specification.Tasks select CreateSubmittedTaskInfo(taskSpecification)).ToList()
			};
			return result;
		}

		private SubmittedTaskInfo CreateSubmittedTaskInfo(TaskSpecification taskSpecification) {
			SubmittedTaskInfo result = new SubmittedTaskInfo {
				Name = taskSpecification.Name,
				Specification = taskSpecification,
				State = TaskState.Configuring
			};
			return result;
		}

		private SubmittedJobInfo CombineSubmittedJobInfoFromCluster(SubmittedJobInfo dbJobInfo, SubmittedJobInfo clusterJobInfo) {
			dbJobInfo.AllParameters = clusterJobInfo.AllParameters;
			dbJobInfo.EndTime = clusterJobInfo.EndTime;
			//dbJobInfo.Name = clusterJobInfo.Name; /* do not replace name (should be set to jobId in DB in qstat) */
			dbJobInfo.Priority = clusterJobInfo.Priority;
			dbJobInfo.Project = clusterJobInfo.Project;
			dbJobInfo.ScheduledJobId = clusterJobInfo.ScheduledJobId;
			dbJobInfo.StartTime = clusterJobInfo.StartTime;
			dbJobInfo.State = clusterJobInfo.State;
			dbJobInfo.SubmitTime = clusterJobInfo.SubmitTime;
			dbJobInfo.TotalAllocatedTime = clusterJobInfo.TotalAllocatedTime;
			dbJobInfo.Tasks = (from dbTask in dbJobInfo.Tasks
				join clusterTask in clusterJobInfo.Tasks on dbTask.Specification.Id.ToString(CultureInfo.InvariantCulture) equals clusterTask.Name
				select CombineSubmittedTaskInfoFromCluster(dbTask, clusterTask)).ToList();
			return dbJobInfo;
		}

		private SubmittedTaskInfo CombineSubmittedTaskInfoFromCluster(SubmittedTaskInfo dbTaskInfo, SubmittedTaskInfo clusterTaskInfo) {
			dbTaskInfo.AllParameters = clusterTaskInfo.AllParameters;
			dbTaskInfo.AllocatedCoreIds = clusterTaskInfo.AllocatedCoreIds;
			dbTaskInfo.AllocatedTime = clusterTaskInfo.AllocatedTime;
			dbTaskInfo.EndTime = clusterTaskInfo.EndTime;
			dbTaskInfo.ErrorMessage = clusterTaskInfo.ErrorMessage;
			dbTaskInfo.StartTime = clusterTaskInfo.StartTime;
			dbTaskInfo.State = clusterTaskInfo.State;
			return dbTaskInfo;
		}
    }
}