-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
GWC.java
2744 lines (2466 loc) · 108 KB
/
GWC.java
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
93
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* (c) 2014 - 2016 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.gwc;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.getRootCause;
import static com.google.common.collect.Iterators.forEnumeration;
import static com.google.common.collect.Lists.newArrayList;
import static org.geowebcache.grid.GridUtil.findBestMatchingGrid;
import static org.geowebcache.seed.GWCTask.TYPE.TRUNCATE;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.io.IOException;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.XMLConstants;
import org.apache.http.client.utils.DateUtils;
import org.geoserver.catalog.Catalog;
import org.geoserver.catalog.CatalogInfo;
import org.geoserver.catalog.FeatureTypeInfo;
import org.geoserver.catalog.LayerGroupInfo;
import org.geoserver.catalog.LayerInfo;
import org.geoserver.catalog.NamespaceInfo;
import org.geoserver.catalog.PublishedInfo;
import org.geoserver.catalog.PublishedType;
import org.geoserver.catalog.ResourceInfo;
import org.geoserver.catalog.StyleInfo;
import org.geoserver.catalog.impl.ProxyUtils;
import org.geoserver.catalog.util.CloseableIterator;
import org.geoserver.gwc.config.GWCConfig;
import org.geoserver.gwc.config.GWCConfigPersister;
import org.geoserver.gwc.layer.CatalogConfiguration;
import org.geoserver.gwc.layer.CatalogLayerEventListener;
import org.geoserver.gwc.layer.CatalogStyleChangeListener;
import org.geoserver.gwc.layer.GeoServerTileLayer;
import org.geoserver.gwc.layer.GeoServerTileLayerInfo;
import org.geoserver.gwc.layer.GeoServerTileLayerInfoImpl;
import org.geoserver.ows.Dispatcher;
import org.geoserver.ows.HttpErrorCodeException;
import org.geoserver.ows.Request;
import org.geoserver.ows.Response;
import org.geoserver.platform.GeoServerEnvironment;
import org.geoserver.platform.GeoServerExtensions;
import org.geoserver.platform.Operation;
import org.geoserver.security.AccessLimits;
import org.geoserver.security.CoverageAccessLimits;
import org.geoserver.security.DataAccessLimits;
import org.geoserver.security.WMSAccessLimits;
import org.geoserver.security.WrapperPolicy;
import org.geoserver.security.decorators.SecuredLayerInfo;
import org.geoserver.threadlocals.ThreadLocalsTransfer;
import org.geoserver.util.HTTPWarningAppender;
import org.geoserver.wfs.kvp.BBoxKvpParser;
import org.geoserver.wms.GetMapRequest;
import org.geoserver.wms.WMS;
import org.geoserver.wms.map.RenderedImageMap;
import org.geoserver.wms.map.RenderedImageMapResponse;
import org.geotools.api.filter.Filter;
import org.geotools.api.filter.FilterFactory;
import org.geotools.api.filter.MultiValuedFilter.MatchAction;
import org.geotools.api.filter.Or;
import org.geotools.api.metadata.extent.GeographicBoundingBox;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.NoSuchAuthorityCodeException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.filter.visitor.ExtractBoundsFilterVisitor;
import org.geotools.geometry.GeneralBounds;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.CRS;
import org.geotools.referencing.CRS.AxisOrder;
import org.geotools.util.logging.Logging;
import org.geowebcache.GeoWebCacheEnvironment;
import org.geowebcache.GeoWebCacheException;
import org.geowebcache.GeoWebCacheExtensions;
import org.geowebcache.config.BlobStoreInfo;
import org.geowebcache.config.ConfigurationException;
import org.geowebcache.config.ConfigurationPersistenceException;
import org.geowebcache.config.TileLayerConfiguration;
import org.geowebcache.conveyor.Conveyor;
import org.geowebcache.conveyor.ConveyorTile;
import org.geowebcache.diskquota.DiskQuotaConfig;
import org.geowebcache.diskquota.DiskQuotaMonitor;
import org.geowebcache.diskquota.jdbc.JDBCConfiguration;
import org.geowebcache.diskquota.storage.LayerQuota;
import org.geowebcache.diskquota.storage.Quota;
import org.geowebcache.diskquota.storage.TileSetVisitor;
import org.geowebcache.filter.parameters.ParameterFilter;
import org.geowebcache.grid.BoundingBox;
import org.geowebcache.grid.GridSet;
import org.geowebcache.grid.GridSetBroker;
import org.geowebcache.grid.GridSubset;
import org.geowebcache.grid.GridSubsetFactory;
import org.geowebcache.grid.SRS;
import org.geowebcache.io.ByteArrayResource;
import org.geowebcache.io.Resource;
import org.geowebcache.layer.TileLayer;
import org.geowebcache.layer.TileLayerDispatcher;
import org.geowebcache.locks.LockProvider;
import org.geowebcache.locks.LockProvider.Lock;
import org.geowebcache.locks.MemoryLockProvider;
import org.geowebcache.mime.MimeException;
import org.geowebcache.mime.MimeType;
import org.geowebcache.seed.GWCTask;
import org.geowebcache.seed.GWCTask.TYPE;
import org.geowebcache.seed.SeedRequest;
import org.geowebcache.seed.TileBreeder;
import org.geowebcache.seed.TruncateAllRequest;
import org.geowebcache.seed.TruncateBboxRequest;
import org.geowebcache.service.Service;
import org.geowebcache.storage.BlobStore;
import org.geowebcache.storage.BlobStoreAggregator;
import org.geowebcache.storage.CompositeBlobStore;
import org.geowebcache.storage.DefaultStorageFinder;
import org.geowebcache.storage.StorageBroker;
import org.geowebcache.storage.StorageException;
import org.geowebcache.storage.TileRange;
import org.geowebcache.util.ServletUtils;
import org.locationtech.jts.densify.Densifier;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring bean acting as a mediator between GWC and GeoServer for the GWC integration classes so
* that they don't need to worry about complexities nor API changes in either.
*
* @author Gabriel Roldan
* @version $Id$
*/
public class GWC implements DisposableBean, InitializingBean, ApplicationContextAware {
private static final String GLOBAL_LOCK_KEY = "global";
public static final String WORKSPACE_PARAM = "WORKSPACE";
/** @see #get() */
private static volatile GWC INSTANCE;
static final Logger log = Logging.getLogger(GWC.class);
/** @see #getResponseEncoder(MimeType, RenderedImageMap) */
private Map<String, Response> cachedTileEncoders = new HashMap<>();
private final TileLayerDispatcher tld;
private final StorageBroker storageBroker;
private final TileBreeder tileBreeder;
private final GWCConfigPersister gwcConfigPersister;
private final Dispatcher owsDispatcher;
private final GridSetBroker gridSetBroker;
private GWCSynchEnv gwcSynchEnv;
private DiskQuotaMonitor monitor;
private CatalogLayerEventListener catalogLayerEventListener;
private CatalogStyleChangeListener catalogStyleChangeListener;
/** The catalog, secured and filtered */
private final Catalog catalog;
/** The raw catalog, non secured. Use with extreme caution! */
private Catalog rawCatalog;
private ConfigurableLockProvider lockProvider;
private JDBCConfigurationStorage jdbcConfigurationStorage;
private FilterFactory ff = CommonFactoryFinder.getFilterFactory();
private GeoWebCacheEnvironment gwcEnvironment;
final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class);
// list of GeoServer contributed grid sets that should not be editable by the user
private final Set<String> geoserverEmbeddedGridSets = new HashSet<>();
private BlobStoreAggregator blobStoreAggregator;
/**
* Constructor for the GWC mediator
*
* @param sb The GeoWebCache StorageBroker
* @param tld The GeoWebCache TileLayer Aggregator
* @param gridSetBroker The GeoWebCache GridSet Aggregator
* @param tileBreeder The GeoWebCache TileBreeder (Used for seeding)
* @param monitor The GeoWebCache DiskQuota Monitor
* @param owsDispatcher The GeoServer OWS Service Dispatcher
* @param catalog The GeoServer catalog, secured and filtered
* @param rawCatalog The raw GeoServer catalog, not secured. Use with extreme caution!
* @param storageFinder GeoWebcache system variable and configuration source
* @param jdbcConfigurationStorage GeoServer integrator for GeoWebCache DiskQuota {@link
* JDBCConfiguration}
* @param blobStoreAggregator GeoWebCache BlobStore Aggregator
* @param gwcSynchEnv GeoServer integrator for GeoWebCache environment synchronization
*/
public GWC(
final GWCConfigPersister gwcConfigPersister,
final StorageBroker sb,
final TileLayerDispatcher tld,
final GridSetBroker gridSetBroker,
final TileBreeder tileBreeder,
final DiskQuotaMonitor monitor,
final Dispatcher owsDispatcher,
final Catalog catalog,
final Catalog rawCatalog,
final DefaultStorageFinder storageFinder,
final JDBCConfigurationStorage jdbcConfigurationStorage,
final BlobStoreAggregator blobStoreAggregator,
final GWCSynchEnv gwcSynchEnv) {
this.gwcConfigPersister = gwcConfigPersister;
this.tld = tld;
this.storageBroker = sb;
this.gridSetBroker = gridSetBroker;
this.tileBreeder = tileBreeder;
this.monitor = monitor;
this.owsDispatcher = owsDispatcher;
this.catalog = catalog;
this.rawCatalog = rawCatalog;
catalogLayerEventListener = new CatalogLayerEventListener(this, catalog);
catalogStyleChangeListener = new CatalogStyleChangeListener(this, catalog);
this.catalog.addListener(catalogLayerEventListener);
this.catalog.addListener(catalogStyleChangeListener);
this.lockProvider = new ConfigurableLockProvider();
updateLockProvider(getConfig().getLockProviderName());
this.jdbcConfigurationStorage = jdbcConfigurationStorage;
this.blobStoreAggregator = blobStoreAggregator;
this.gwcSynchEnv = gwcSynchEnv;
}
/** Updates the configurable lock provider to use the specified bean */
private void updateLockProvider(String lockProviderName) {
LockProvider delegate = null;
if (lockProviderName == null) {
delegate = new MemoryLockProvider();
} else {
Object provider = GeoWebCacheExtensions.bean(lockProviderName);
if (provider == null) {
throw new RuntimeException(
"Could not find lock provider "
+ lockProvider
+ " in the spring application context");
} else if (!(provider instanceof LockProvider)) {
throw new RuntimeException(
"Found bean "
+ lockProvider
+ " in the spring application context, but it was not a LockProvider");
} else {
delegate = (LockProvider) provider;
}
}
lockProvider.setDelegate(delegate);
}
/**
* Gets the singleton instance of the GeoServer GWC environment synchronizer
*
* @return the singleton instance of the GeoServer GWC environment synchronizer
*/
public GWCSynchEnv getGwcSynchEnv() {
return gwcSynchEnv;
}
/**
* Retrieves the GWC mediator bean, if registered in the spring context or set via {@link
* #set(GWC,GWCSynchEnv)}.
*
* @return The {@link GWC} mediator bean
* @throws IllegalStateException if no {@link GWC} instance was found.
*/
public static GWC get() {
GWC.INSTANCE.gwcSynchEnv.syncEnv();
return GWC.INSTANCE;
}
/**
* Only to aid in unit testing for the places where a mock GWC mediator and GeoServer
* environment synchhronizer are needed
*
* @param instance the GWC mediator instance
* @param gwcSynchEnv the GeoServer environment synchronizer instance
*/
public static void set(GWC instance, GWCSynchEnv gwcSynchEnv) {
if (instance != null) {
instance.gwcSynchEnv = gwcSynchEnv;
}
GWC.INSTANCE = instance;
}
/** @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */
@Override
public void afterPropertiesSet() throws Exception {
GWC.set(this, gwcSynchEnv);
}
/** @see org.springframework.beans.factory.DisposableBean#destroy() */
@Override
public void destroy() throws Exception {
Catalog catalog = getCatalog();
if (this.catalogLayerEventListener != null) {
catalog.removeListener(this.catalogLayerEventListener);
}
if (this.catalogStyleChangeListener != null) {
catalog.removeListener(this.catalogStyleChangeListener);
}
GWC.set(null, null);
}
public Catalog getCatalog() {
return catalog;
}
public GWCConfig getConfig() {
return gwcConfigPersister.getConfig();
}
/** Fully truncates the given layer, including any ParameterFilter */
public void truncate(final String layerName) {
checkNotNull(layerName, "layerName is null");
// easy, no need to issue truncate tasks
TileLayer layer;
try {
layer = tld.getTileLayer(layerName);
} catch (GeoWebCacheException e) {
log.log(Level.INFO, e.getMessage(), e);
return;
}
final Set<String> gridSubsets = layer.getGridSubsets();
for (String gridSetId : gridSubsets) {
deleteCacheByGridSetId(layerName, gridSetId);
}
}
/** Truncates the cache for the given layer/style combination */
public void truncateByLayerAndStyle(final String layerName, final String styleName) {
// check if the given style is actually cached
if (log.isLoggable(Level.FINE)) {
log.fine(
"Truncate for layer/style called. Checking if style '"
+ styleName
+ "' is cached for layer '"
+ layerName
+ "'");
}
if (!isStyleCached(layerName, styleName)) {
log.fine(
"Style '"
+ styleName
+ "' is not cached for layer "
+ layerName
+ "'. No need to truncate.");
return;
}
log.fine("truncating '" + layerName + "' for style '" + styleName + "'");
String gridSetId = null; // all of them
BoundingBox bounds = null; // all of them
String format = null; // all of them
truncate(layerName, styleName, gridSetId, bounds, format);
}
/** Truncates the cache for the default style of the given layer */
public void truncateByLayerDefaultStyle(final String layerName) {
checkNotNull(layerName, "layerName can't be null");
log.fine("truncating '" + layerName + "' for default style");
final TileLayer layer = getTileLayerByName(layerName);
final Set<String> gridSetIds = layer.getGridSubsets(); // all of them
final List<MimeType> mimeTypes = layer.getMimeTypes(); // all of them
final BoundingBox bounds = null; // all of them
final Map<String, String> parameters = null; // only default style
for (String gridSetId : gridSetIds) {
GridSubset gridSubset = layer.getGridSubset(gridSetId);
if (gridSubset == null) {
// layer may no longer have this gridsubset, but we want to truncate any remaining
// tiles
GridSet gridSet = gridSetBroker.get(gridSetId);
gridSubset = GridSubsetFactory.createGridSubSet(gridSet);
}
for (MimeType mime : mimeTypes) {
String formatName = mime.getFormat();
truncate(layer, bounds, gridSubset, formatName, parameters);
}
}
}
public void truncate(final String layerName, final ReferencedEnvelope bounds)
throws GeoWebCacheException {
final TileLayer tileLayer = tld.getTileLayer(layerName);
final Collection<String> gridSubSets = tileLayer.getGridSubsets();
/*
* Create a truncate task for each gridSubset (CRS), format and style
*/
for (String gridSetId : gridSubSets) {
GridSubset layerGrid = tileLayer.getGridSubset(gridSetId);
BoundingBox intersectingBounds = getIntersectingBounds(layerName, layerGrid, bounds);
if (intersectingBounds == null) {
continue;
}
try {
// This iterates over all cached parameters and all formats
new TruncateBboxRequest(layerName, intersectingBounds, gridSetId)
.doTruncate(storageBroker, tileBreeder);
} catch (StorageException | GeoWebCacheException e) {
log.log(
Level.WARNING,
e,
() ->
String.format(
"Error while truncating modified bounds for layer %s gridset %s",
layerName, gridSetId));
}
}
}
public TruncateAllRequest truncateAll() throws GeoWebCacheException, StorageException {
// creating a mock internal request
TruncateAllRequest truncateAll = new TruncateAllRequest();
// truncating everything
truncateAll.doTruncate(storageBroker, tileBreeder);
log.info("Mass Truncate Completed");
log.info("Truncated Layers : " + truncateAll.getTrucatedLayersList());
return truncateAll;
}
private BoundingBox getIntersectingBounds(
String layerName, GridSubset layerGrid, ReferencedEnvelope bounds) {
final GridSet gridSet = layerGrid.getGridSet();
final String gridSetId = gridSet.getName();
final SRS srs = gridSet.getSrs();
final CoordinateReferenceSystem gridSetCrs;
try {
gridSetCrs = CRS.decode("EPSG:" + srs.getNumber(), true);
} catch (Exception e) {
throw new RuntimeException(
"Can't decode SRS for layer '" + layerName + "': ESPG:" + srs.getNumber());
}
ReferencedEnvelope truncateBoundsInGridsetCrs;
try {
truncateBoundsInGridsetCrs = bounds.transform(gridSetCrs, true);
} catch (Exception e) {
log.warning(
"Can't truncate layer "
+ layerName
+ ": error transforming requested bounds to layer gridset "
+ gridSetId
+ ": "
+ e.getMessage());
return null;
}
final double minx = truncateBoundsInGridsetCrs.getMinX();
final double miny = truncateBoundsInGridsetCrs.getMinY();
final double maxx = truncateBoundsInGridsetCrs.getMaxX();
final double maxy = truncateBoundsInGridsetCrs.getMaxY();
final BoundingBox reqBounds = new BoundingBox(minx, miny, maxx, maxy);
/*
* layerGrid.getCoverageIntersections is not too robust, so we better check the requested
* bounds intersect the layer bounds
*/
// final BoundingBox layerBounds = layerGrid.getCoverageBestFitBounds();
final BoundingBox layerBounds = layerGrid.getOriginalExtent();
if (!layerBounds.intersects(reqBounds)) {
log.fine(
"Requested truncation bounds do not intersect cached layer bounds, ignoring truncate request");
return null;
}
final BoundingBox intersectingBounds = BoundingBox.intersection(layerBounds, reqBounds);
return intersectingBounds;
}
/**
* @param layerName name of the layer to truncate, non {@code null}
* @param styleName style to truncate, or {@code null} for all
* @param gridSetName grid set to truncate, {@code null} for all
* @param bounds bounds to truncate based on, or {@code null} for whole layer
* @param format {@link MimeType#getFormat() format} to truncate, or {@code null} for all
*/
public void truncate(
final String layerName,
final String styleName,
final String gridSetName,
final BoundingBox bounds,
final String format) {
checkNotNull(layerName, "layerName can't be null");
final TileLayer layer = getTileLayerByName(layerName);
final Set<String> styleNames;
final Set<String> gridSetIds;
final List<MimeType> mimeTypes;
if (styleName == null) {
styleNames = getCachedStyles(layerName);
if (styleNames.isEmpty()) {
styleNames.add("");
}
} else {
styleNames = Collections.singleton(styleName);
}
if (gridSetName == null) {
gridSetIds = layer.getGridSubsets();
} else {
gridSetIds = Collections.singleton(gridSetName);
}
if (format == null) {
mimeTypes = layer.getMimeTypes();
} else {
try {
mimeTypes = Collections.singletonList(MimeType.createFromFormat(format));
} catch (MimeException e) {
throw new RuntimeException();
}
}
final String defaultStyle = layer.getStyles();
for (String gridSetId : gridSetIds) {
GridSubset gridSubset = layer.getGridSubset(gridSetId);
if (gridSubset == null) {
// layer may no longer have this gridsubset, but we want to truncate any remaining
// tiles
GridSet gridSet = gridSetBroker.get(gridSetId);
gridSubset = GridSubsetFactory.createGridSubSet(gridSet);
}
for (String style : styleNames) {
Map<String, String> parameters;
if (style.length() == 0 || style.equals(defaultStyle)) {
log.finer(
"'"
+ style
+ "' is the layer's default style, "
+ "not adding a parameter filter");
parameters = null;
} else {
parameters = Collections.singletonMap("STYLES", style);
}
for (MimeType mime : mimeTypes) {
String formatName = mime.getFormat();
truncate(layer, bounds, gridSubset, formatName, parameters);
}
}
}
}
private void truncate(
final TileLayer layer,
final BoundingBox bounds,
final GridSubset gridSubset,
String formatName,
Map<String, String> parameters) {
final int threadCount = 1;
int zoomStart = gridSubset.getZoomStart();
int zoomStop = gridSubset.getZoomStop();
final TYPE taskType = TRUNCATE;
SeedRequest req =
new SeedRequest(
layer.getName(),
bounds,
gridSubset.getName(),
threadCount,
zoomStart,
zoomStop,
formatName,
taskType,
parameters);
GWCTask[] tasks;
try {
TileRange tr = TileBreeder.createTileRange(req, layer);
boolean filterUpdate = false;
tasks = tileBreeder.createTasks(tr, taskType, threadCount, filterUpdate);
} catch (GeoWebCacheException e) {
throw new RuntimeException(e);
}
tileBreeder.dispatchTasks(tasks);
}
private boolean isStyleCached(final String layerName, final String styleName) {
Set<String> cachedStyles = getCachedStyles(layerName);
boolean styleIsCached = cachedStyles.contains(styleName);
return styleIsCached;
}
/** Returns the names of the styles for the layer, including the default style */
private Set<String> getCachedStyles(final String layerName) {
final TileLayer l = getTileLayerByName(layerName);
Set<String> cachedStyles = new HashSet<>();
String defaultStyle = l.getStyles();
if (defaultStyle != null) {
cachedStyles.add(defaultStyle);
}
List<ParameterFilter> parameterFilters = l.getParameterFilters();
if (parameterFilters != null) {
for (ParameterFilter pf : parameterFilters) {
if (!"STYLES".equalsIgnoreCase(pf.getKey())) {
continue;
}
cachedStyles.add(pf.getDefaultValue());
cachedStyles.addAll(pf.getLegalValues());
break;
}
}
return cachedStyles;
}
/**
* Completely eliminates a {@link GeoServerTileLayer} from GWC.
*
* <p>This method is intended to be called whenever a {@link LayerInfo} or {@link
* LayerGroupInfo} is removed from GeoServer, or it is configured not to create a cached layer
* for it, in order to delete the cache for the layer.
*
* @param prefixedName the name of the layer to remove.
* @return {@code true} if the removal of the entire cache for the layer has succeeded, {@code
* false} if there wasn't a cache for that layer.
*/
public synchronized boolean layerRemoved(final String prefixedName) {
try {
return storageBroker.delete(prefixedName);
} catch (StorageException e) {
throw new RuntimeException(e);
}
}
public static void tryReload() {
GWC instance = GWC.INSTANCE;
if (instance != null) {
instance.reload();
}
}
/** Reloads the configuration and notifies GWC of any externally removed layer. */
@SuppressWarnings("deprecation")
void reload() {
final Set<String> currLayerNames = new HashSet<>(getTileLayerNames());
try {
tld.reInit(); // some mock testing uses this blasted method, don't know how to work
// around it
} catch (RuntimeException e) {
log.log(Level.WARNING, "Unable to reinit TileLayerDispatcher", e);
throw e;
}
Set<String> newLayerNames = getTileLayerNames();
SetView<String> removedExternally = Sets.difference(currLayerNames, newLayerNames);
for (String removedLayerName : removedExternally) {
log.info("Notifying of TileLayer '" + removedLayerName + "' removed externally");
layerRemoved(removedLayerName);
}
// reload the quota config
try {
DiskQuotaMonitor monitor = getDiskQuotaMonitor();
monitor.reloadConfig();
ConfigurableQuotaStoreProvider provider =
(ConfigurableQuotaStoreProvider) monitor.getQuotaStoreProvider();
provider.reloadQuotaStore();
// restart the monitor, the quota store might have been changed and pointed to another
// DB
// and we need to re-init the tile pages
monitor.shutDown(1);
monitor.startUp();
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to reload the disk quoa configuration", e);
}
}
/**
* Tries to dispatch a tile request represented by a GeoServer WMS {@link GetMapRequest} through
* GeoWebCache, and returns the {@link ConveyorTile} if succeeded or {@code null} if it wasn't
* possible.
*
* <p>Preconditions:
*
* <ul>
* <li><code>{@link GetMapRequest#isTiled() request.isTiled()} == true</code>
* </ul>
*
* @param requestMistmatchTarget target string builder where to write the reason of the request
* mismatch with the tile cache
* @return the GWC generated tile result if the request matches a tile cache, or {@code null}
* otherwise.
*/
public final ConveyorTile dispatch(
final GetMapRequest request, StringBuilder requestMistmatchTarget) {
final String layerName = request.getRawKvp().get("LAYERS");
/*
* This is a quick way of checking if the request was for a single layer. We can't really
* use request.getLayers() because in the event that a layerGroup was requested, the request
* parser turned it into a list of actual Layers
*/
if (layerName.indexOf(',') != -1) {
requestMistmatchTarget.append("more than one layer requested");
return null;
}
// GEOS-9431 acquire prefixed name if not prefixed already
final String getPrefixedName =
(!layerName.contains(":")) ? getPrefixedName(layerName) : layerName;
if (!tld.layerExists(getPrefixedName)) {
requestMistmatchTarget.append("not a tile layer");
return null;
}
final TileLayer tileLayer;
try {
tileLayer = this.tld.getTileLayer(getPrefixedName);
} catch (GeoWebCacheException e) {
throw new RuntimeException(e);
}
if (!tileLayer.isEnabled()) {
requestMistmatchTarget.append("tile layer disabled");
return null;
}
if (getConfig().isSecurityEnabled()) {
String bboxstr = request.getRawKvp().get("BBOX");
String srs = request.getRawKvp().get("SRS");
ReferencedEnvelope bbox = null;
try {
bbox = (ReferencedEnvelope) new BBoxKvpParser().parse(bboxstr);
} catch (Exception e) {
throw new RuntimeException(
"Invalid bbox for layer '" + layerName + "': " + bboxstr);
}
if (srs != null) {
try {
bbox = new ReferencedEnvelope(bbox, CRS.decode(srs));
} catch (Exception e) {
throw new RuntimeException(
"Can't decode SRS for layer '" + layerName + "': " + srs);
}
}
try {
verifyAccessLayer(layerName, bbox);
} catch (ServiceException | SecurityException e) {
return null;
}
}
ConveyorTile tileReq = prepareRequest(tileLayer, request, requestMistmatchTarget);
if (null == tileReq) {
return null;
}
ConveyorTile tileResp = null;
try {
tileResp = tileLayer.getTile(tileReq);
} catch (Exception e) {
log.log(Level.INFO, "Error dispatching tile request to GeoServer", e);
}
return tileResp;
}
private String getPrefixedName(String layerName) {
PublishedInfo info = catalog.getLayerByName(layerName);
if (info == null) info = catalog.getLayerGroupByName(layerName);
if (info != null) return info.prefixedName();
if (log.isLoggable(Level.INFO)) log.info("Unable to find a prefix for : " + layerName);
return layerName;
}
ConveyorTile prepareRequest(
TileLayer tileLayer, GetMapRequest request, StringBuilder requestMistmatchTarget) {
if (!isCachingPossible(tileLayer, request, requestMistmatchTarget)) {
return null;
}
final MimeType mimeType;
try {
mimeType = MimeType.createFromFormat(request.getFormat());
List<MimeType> tileLayerFormats = tileLayer.getMimeTypes();
if (!tileLayerFormats.contains(mimeType)) {
requestMistmatchTarget.append("no tile cache for requested format");
return null;
}
} catch (MimeException me) {
// not a GWC supported format
requestMistmatchTarget.append("not a GWC supported format: ").append(me.getMessage());
return null;
}
final GridSubset gridSubset;
final long[] tileIndex;
final Map<String, String> fullParameters;
try {
boolean axisFlip = false;
final List<GridSubset> crsMatchingGridSubsets;
{
CoordinateReferenceSystem crs = request.getCrs();
// are we in wms 1.3 land?
if (CRS.getAxisOrder(crs) == AxisOrder.NORTH_EAST) {
axisFlip = true;
}
String srs = request.getSRS();
int epsgId = Integer.parseInt(srs.substring(srs.lastIndexOf(':') + 1));
SRS srs2 = SRS.getSRS(epsgId);
crsMatchingGridSubsets = tileLayer.getGridSubsetsForSRS(srs2);
}
final BoundingBox tileBounds;
{
Envelope bbox = request.getBbox();
if (axisFlip) {
tileBounds =
new BoundingBox(
bbox.getMinY(), bbox.getMinX(), bbox.getMaxY(), bbox.getMaxX());
} else {
tileBounds =
new BoundingBox(
bbox.getMinX(), bbox.getMinY(), bbox.getMaxX(), bbox.getMaxY());
}
}
if (crsMatchingGridSubsets.isEmpty()) {
requestMistmatchTarget.append("no cache exists for requested CRS");
return null;
}
{
long[] matchingTileIndex = new long[3];
final int reqW = request.getWidth();
final int reqH = request.getHeight();
gridSubset =
findBestMatchingGrid(
tileBounds, crsMatchingGridSubsets, reqW, reqH, matchingTileIndex);
if (gridSubset == null) {
requestMistmatchTarget.append("request does not align to grid(s) ");
for (GridSubset gs : crsMatchingGridSubsets) {
requestMistmatchTarget.append('\'').append(gs.getName()).append("' ");
}
return null;
}
tileIndex = matchingTileIndex;
}
{
Map<String, String> requestParameterMap = request.getRawKvp();
fullParameters = tileLayer.getModifiableParameters(requestParameterMap, "UTF-8");
}
} catch (Exception e) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Exception caught checking gwc dispatch preconditions", e);
}
Throwable rootCause = getRootCause(e);
requestMistmatchTarget
.append("exception occurred: ")
.append(rootCause.getClass().getSimpleName())
.append(": ")
.append(e.getMessage());
return null;
}
final String gridSetId = gridSubset.getName();
HttpServletRequest servletReq = null;
HttpServletResponse servletResp = null;
String layerName = tileLayer.getName();
ConveyorTile tileReq =
new ConveyorTile(
storageBroker,
layerName,
gridSetId,
tileIndex,
mimeType,
fullParameters,
servletReq,
servletResp);
return tileReq;
}
/**
* Determines whether the given {@link GetMapRequest} is a candidate to match a GWC tile or not.
*
* @param layer the layer name to check against
* @param request the GetMap request to check whether it might match a tile
*/
boolean isCachingPossible(
TileLayer layer, GetMapRequest request, StringBuilder requestMistmatchTarget) {
if (null != request.getRemoteOwsType() || null != request.getRemoteOwsURL()) {
requestMistmatchTarget.append("request uses remote OWS");
return false;
}
Map<String, ParameterFilter> filters;
{
List<ParameterFilter> parameterFilters = layer.getParameterFilters();
if (null == parameterFilters || parameterFilters.isEmpty()) {
filters = Collections.emptyMap();
} else {
filters = new HashMap<>();
for (ParameterFilter pf : parameterFilters) {
filters.put(pf.getKey().toUpperCase(), pf);
}
}
}
// if (request.isTransparent()) {
// if (!filterApplies(filters, request, "TRANSPARENT")) {
// return false;
// }
// }
if (request.getEnv() != null && !request.getEnv().isEmpty()) {
if (!filterApplies(filters, request, "ENV", requestMistmatchTarget)) {
return false;
}
}
if (request.getFormatOptions() != null && !request.getFormatOptions().isEmpty()) {
if (!filterApplies(filters, request, "FORMAT_OPTIONS", requestMistmatchTarget)) {
return false;
}
}
if (0.0 != request.getAngle()) {
if (!filterApplies(filters, request, "ANGLE", requestMistmatchTarget)) {
return false;
}
}
if (null != request.getRawKvp().get("BGCOLOR")) {
if (!filterApplies(filters, request, "BGCOLOR", requestMistmatchTarget)) {
return false;
}
}
if (0 != request.getBuffer()) {
if (!filterApplies(filters, request, "BUFFER", requestMistmatchTarget)) {
return false;
}
}
if (null != request.getCQLFilter() && !request.getCQLFilter().isEmpty()) {
if (!filterApplies(filters, request, "CQL_FILTER", requestMistmatchTarget)) {
return false;
}
}
if (request.getElevation() != null && !request.getElevation().isEmpty()) {
if (null != request.getElevation().get(0)
&& !filterApplies(filters, request, "ELEVATION", requestMistmatchTarget)) {
return false;
}
}
if (null != request.getFeatureId() && !request.getFeatureId().isEmpty()) {
if (!filterApplies(filters, request, "FEATUREID", requestMistmatchTarget)) {
return false;