001package ca.uhn.fhir.jpa.search.warm;
002
003/*-
004 * #%L
005 * HAPI FHIR JPA Server
006 * %%
007 * Copyright (C) 2014 - 2022 Smile CDR, Inc.
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.i18n.Msg;
024import ca.uhn.fhir.context.ConfigurationException;
025import ca.uhn.fhir.context.FhirContext;
026import ca.uhn.fhir.context.RuntimeResourceDefinition;
027import ca.uhn.fhir.jpa.api.config.DaoConfig;
028import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
029import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao;
030import ca.uhn.fhir.jpa.api.model.WarmCacheEntry;
031import ca.uhn.fhir.jpa.model.sched.HapiJob;
032import ca.uhn.fhir.jpa.model.sched.ISchedulerService;
033import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition;
034import ca.uhn.fhir.jpa.searchparam.MatchUrlService;
035import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
036import ca.uhn.fhir.util.UrlUtil;
037import org.apache.commons.lang3.time.DateUtils;
038import org.quartz.JobExecutionContext;
039import org.slf4j.Logger;
040import org.slf4j.LoggerFactory;
041import org.springframework.beans.factory.annotation.Autowired;
042import org.springframework.stereotype.Component;
043
044import javax.annotation.PostConstruct;
045import java.util.ArrayList;
046import java.util.Collections;
047import java.util.LinkedHashMap;
048import java.util.List;
049import java.util.Map;
050import java.util.Set;
051
052@Component
053public class CacheWarmingSvcImpl implements ICacheWarmingSvc {
054
055        private static final Logger ourLog = LoggerFactory.getLogger(CacheWarmingSvcImpl.class);
056        @Autowired
057        private DaoConfig myDaoConfig;
058        private Map<WarmCacheEntry, Long> myCacheEntryToNextRefresh = new LinkedHashMap<>();
059        @Autowired
060        private FhirContext myCtx;
061        @Autowired
062        private DaoRegistry myDaoRegistry;
063        @Autowired
064        private MatchUrlService myMatchUrlService;
065        @Autowired
066        private ISchedulerService mySchedulerService;
067
068        @Override
069        public synchronized void performWarmingPass() {
070                ourLog.trace("Starting cache warming pass for {} tasks", myCacheEntryToNextRefresh.size());
071
072                for (WarmCacheEntry nextCacheEntry : new ArrayList<>(myCacheEntryToNextRefresh.keySet())) {
073
074                        long nextRefresh = myCacheEntryToNextRefresh.get(nextCacheEntry);
075                        if (nextRefresh < System.currentTimeMillis()) {
076
077                                // Perform the search
078                                refreshNow(nextCacheEntry);
079
080                                // Set the next time to warm this search
081                                nextRefresh = nextCacheEntry.getPeriodMillis() + System.currentTimeMillis();
082                                myCacheEntryToNextRefresh.put(nextCacheEntry, nextRefresh);
083
084                        }
085
086                }
087
088        }
089
090        private void refreshNow(WarmCacheEntry theCacheEntry) {
091                String nextUrl = theCacheEntry.getUrl();
092
093                RuntimeResourceDefinition resourceDef = UrlUtil.parseUrlResourceType(myCtx, nextUrl);
094                IFhirResourceDao<?> callingDao = myDaoRegistry.getResourceDao(resourceDef.getName());
095                String queryPart = parseWarmUrlParamPart(nextUrl);
096                SearchParameterMap responseCriteriaUrl = myMatchUrlService.translateMatchUrl(queryPart, resourceDef);
097
098                callingDao.search(responseCriteriaUrl);
099        }
100
101        private String parseWarmUrlParamPart(String theNextUrl) {
102                int paramIndex = theNextUrl.indexOf('?');
103                if (paramIndex == -1) {
104                        throw new ConfigurationException(Msg.code(1172) + "Invalid warm cache URL (must have ? character)");
105                }
106                return theNextUrl.substring(paramIndex);
107        }
108
109        @PostConstruct
110        public void start() {
111                initCacheMap();
112                scheduleJob();
113        }
114
115        public void scheduleJob() {
116                ScheduledJobDefinition jobDetail = new ScheduledJobDefinition();
117                jobDetail.setId(getClass().getName());
118                jobDetail.setJobClass(Job.class);
119                mySchedulerService.scheduleClusteredJob(10 * DateUtils.MILLIS_PER_SECOND, jobDetail);
120        }
121
122        public static class Job implements HapiJob {
123                @Autowired
124                private ICacheWarmingSvc myTarget;
125
126                @Override
127                public void execute(JobExecutionContext theContext) {
128                        myTarget.performWarmingPass();
129                }
130        }
131
132        public synchronized Set<WarmCacheEntry> initCacheMap() {
133
134                myCacheEntryToNextRefresh.clear();
135                List<WarmCacheEntry> warmCacheEntries = myDaoConfig.getWarmCacheEntries();
136                for (WarmCacheEntry next : warmCacheEntries) {
137
138                        // Validate
139                        parseWarmUrlParamPart(next.getUrl());
140                        UrlUtil.parseUrlResourceType(myCtx, next.getUrl());
141
142                        myCacheEntryToNextRefresh.put(next, 0L);
143                }
144
145                return Collections.unmodifiableSet(myCacheEntryToNextRefresh.keySet());
146        }
147}