1 package org.onap.vid.job.impl;
3 import org.apache.commons.lang3.StringUtils;
4 import org.hibernate.SessionFactory;
5 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
6 import org.onap.portalsdk.core.service.DataAccessService;
7 import org.onap.portalsdk.core.util.SystemProperties;
8 import org.onap.vid.exceptions.GenericUncheckedException;
9 import org.onap.vid.exceptions.OperationNotAllowedException;
10 import org.onap.vid.job.Job;
11 import org.onap.vid.job.JobsBrokerService;
12 import org.onap.vid.properties.VidProperties;
13 import org.onap.vid.utils.DaoUtils;
14 import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.beans.factory.annotation.Value;
16 import org.springframework.stereotype.Service;
18 import javax.annotation.PostConstruct;
19 import java.nio.ByteBuffer;
20 import java.sql.Timestamp;
21 import java.time.LocalDateTime;
24 import static org.onap.vid.job.Job.JobStatus.CREATING;
27 public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService {
29 static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JobsBrokerServiceInDatabaseImpl.class);
31 private final DataAccessService dataAccessService;
33 private final SessionFactory sessionFactory;
34 private int maxOpenedInstantiationRequestsToMso;
35 private int pollingIntervalSeconds;
38 public JobsBrokerServiceInDatabaseImpl(DataAccessService dataAccessService, SessionFactory sessionFactory,
39 @Value("0") int maxOpenedInstantiationRequestsToMso,
40 @Value("10") int pollingIntervalSeconds) {
41 // tha @Value will inject conservative defaults; overridden in @PostConstruct from configuration
42 this.dataAccessService = dataAccessService;
43 this.sessionFactory = sessionFactory;
44 this.maxOpenedInstantiationRequestsToMso = maxOpenedInstantiationRequestsToMso;
45 this.pollingIntervalSeconds = pollingIntervalSeconds;
49 public void configure() {
50 maxOpenedInstantiationRequestsToMso = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_MAX_OPENED_INSTANTIATION_REQUESTS));
51 pollingIntervalSeconds = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_ASYNC_POLLING_INTERVAL_SECONDS));
54 public void deleteAll() {
55 dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", null);
59 public UUID add(Job job) {
60 final JobDaoImpl jobDao = castToJobDaoImpl(job);
61 dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap());
66 public Optional<Job> pull(Job.JobStatus topic, String ownerId) {
70 String query = sqlQueryForTopic(topic);
71 List<JobDaoImpl> jobs = dataAccessService.executeSQLQuery(query, JobDaoImpl.class, null);
73 return Optional.empty();
78 final UUID uuid = daoJob.getUuid();
79 final Integer age = daoJob.getAge();
81 daoJob.setTakenBy(ownerId);
83 // It might become that daoJob was taken and pushed-back already, before we
84 // arrived here, so we're verifying the age was not pushed forward.
85 // Age is actually forwarded upon pushBack().
86 String hqlUpdate = "update JobDaoImpl job set job.takenBy = :takenBy where " +
88 " and job.age = :age" +
89 " and takenBy is null";
90 updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session ->
91 session.createQuery(hqlUpdate)
92 .setText("id", uuid.toString())
93 .setInteger("age", age)
94 .setText("takenBy", ownerId)
97 } while (updatedEntities == 0);
99 return Optional.ofNullable(daoJob);
102 private java.sql.Timestamp nowMinusInterval() {
103 return Timestamp.valueOf(LocalDateTime.now().minusSeconds(pollingIntervalSeconds));
106 private String selectQueryByJobStatus(Job.JobStatus topic){
108 String intervalCondition = (topic==CREATING) ? "" : (" and MODIFIED_DATE <= '" + nowMinusInterval()+"'");
110 "select * from VID_JOB" +
112 // select only non-deleted in-progress jobs
113 " JOB_STATUS = '" + topic + "'" +
114 " and TAKEN_BY is null" +
115 " and DELETED_AT is null" +
116 // give some breath, don't select jos that were recently reached
118 // take the oldest handled one
119 " order by MODIFIED_DATE ASC" +
120 // select only one result
124 private String sqlQueryForTopic(Job.JobStatus topic) {
127 case RESOURCE_IN_PROGRESS:
129 return selectQueryByJobStatus(topic);
132 // select only pending jobs
133 "select vid_job.* from VID_JOB " +
134 // select users have in_progress jobs
136 " (select user_Id, 1 as has_any_in_progress_job from VID_JOB where JOB_STATUS = 'IN_PROGRESS' or TAKEN_BY IS NOT NULL \n" +
137 "group by user_id) users_have_any_in_progress_job_tbl\n" +
138 "on vid_job.user_id = users_have_any_in_progress_job_tbl.user_id " +
139 "where JOB_STATUS = 'PENDING' and TAKEN_BY is null" +
140 // job is not deleted
141 " AND DELETED_AT is null and (\n" +
142 // limit in-progress to some amount
143 "select sum(CASE WHEN JOB_STATUS='IN_PROGRESS' or (JOB_STATUS='PENDING' and TAKEN_BY IS NOT NULL) THEN 1 ELSE 0 END) as in_progress\n" +
144 "from VID_JOB ) <" + maxOpenedInstantiationRequestsToMso + " \n " +
145 // don't take jobs from templates that already in-progress/failed
146 "and TEMPLATE_Id not in \n" +
147 "(select TEMPLATE_Id from vid_job where" +
148 " TEMPLATE_Id IS NOT NULL and("+
149 " (JOB_STATUS='FAILED' and DELETED_AT is null)" + // failed but not deleted
150 " or JOB_STATUS='IN_PROGRESS'" +
151 " or TAKEN_BY IS NOT NULL))" + " \n " +
152 // prefer older jobs, but the earlier in each bulk
153 "order by has_any_in_progress_job, CREATED_DATE, INDEX_IN_BULK " +
154 // select only one result
157 throw new GenericUncheckedException("Unsupported topic to pull from: " + topic);
162 private byte[] getUuidAsByteArray(UUID owner) {
163 ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
164 bb.putLong(owner.getMostSignificantBits());
165 bb.putLong(owner.getLeastSignificantBits());
170 public void pushBack(Job job) {
171 final JobDaoImpl remoteDaoJob = (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, job.getUuid(), null);
173 if (remoteDaoJob == null) {
174 throw new IllegalStateException("Can push back only pulled jobs. Add new jobs using add()");
177 if (remoteDaoJob.getTakenBy() == null) {
178 throw new IllegalStateException("Can push back only pulled jobs. This one already pushed back.");
181 final JobDaoImpl jobDao = castToJobDaoImpl(job);
183 jobDao.setTakenBy(null);
185 Integer age = jobDao.getAge();
186 jobDao.setAge(age + 1);
188 logger.debug(EELFLoggerDelegate.debugLogger, "{}/{}", jobDao.getStatus(), jobDao.getType());
190 dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap());
193 private JobDaoImpl castToJobDaoImpl(Job job) {
194 if (!(job instanceof JobDaoImpl)) {
195 throw new UnsupportedOperationException("Can't add " + job.getClass() + " to " + this.getClass());
197 return (JobDaoImpl) job;
201 public Collection<Job> peek() {
202 return dataAccessService.getList(JobDaoImpl.class, null);
206 public Job peek(UUID jobId) {
207 return (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, jobId, null);
211 public void delete(UUID jobId) {
213 Date now = new Date();
215 String hqlUpdate = "update JobDaoImpl job set job.deletedAt = :now where " +
217 " and job.status in(:pending, :stopped)" +
218 " and takenBy is null";
220 updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session ->
221 session.createQuery(hqlUpdate)
222 .setTimestamp("now", now)
223 .setText("id", jobId.toString())
224 .setText("pending", Job.JobStatus.PENDING.toString())
225 .setText("stopped", Job.JobStatus.STOPPED.toString())
228 if (updatedEntities == 0) {
229 final JobDaoImpl remoteDaoJob = (JobDaoImpl) dataAccessService.getDomainObject(JobDaoImpl.class, jobId, null);
231 if (remoteDaoJob == null || remoteDaoJob.getUuid() == null) {
232 logger.debug(EELFLoggerDelegate.debugLogger,"jobId {}: Service does not exist", jobId);
233 throw new OperationNotAllowedException("Service does not exist");
236 if (!remoteDaoJob.getStatus().equals(Job.JobStatus.PENDING) && !remoteDaoJob.getStatus().equals(Job.JobStatus.STOPPED) || !StringUtils.isEmpty(remoteDaoJob.getTakenBy()) ) {
237 logger.debug(EELFLoggerDelegate.debugLogger,"jobId {}: Service status does not allow deletion from the queue, status = {}", jobId, remoteDaoJob.getStatus() +
238 ", takenBy " + remoteDaoJob.getTakenBy());
239 throw new OperationNotAllowedException("Service status does not allow deletion from the queue");
242 throw new OperationNotAllowedException("Service deletion failed");
247 public boolean mute(UUID jobId) {
252 final String prefix = "DUMP";
255 // Changing the topic (i.e. `job.status`) makes the job non-fetchable.
256 String hqlUpdate = "" +
257 "update JobDaoImpl job set" +
258 " job.status = concat('" + prefix + "_', job.status)," +
259 // empty `takenBy`, because some logics treat taken as in-progress
263 // if prefix already on the topic -- no need to do it twice.
264 " and job.status NOT LIKE '" + prefix + "\\_%'";
266 updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session ->
267 session.createQuery(hqlUpdate)
268 .setText("id", jobId.toString())
271 return updatedEntities != 0;