forked from icpac-igad/gsky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ows.go
1925 lines (1690 loc) · 59.2 KB
/
ows.go
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
package main
/* ows is a web server implementing the WMS, WCS and WPS protocols
to serve geospatial data. This server is intended to be
consumed directly by users and exposes a series of
functionalities through the GetCapabilities.xml document.
Configuration of the server is specified in the config.json
file where features such as layers or color scales can be
defined.
This server depends on two other services to operate: the
index server which registers the files involved in one operation
and the warp server which performs the actual rendering of
a tile. */
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/nci/gomemcache/memcache"
"github.com/nci/gsky/metrics"
proc "github.com/nci/gsky/processor"
"github.com/nci/gsky/utils"
geo "github.com/nci/geometry"
)
// Global variable to hold the values specified
// on the config.json document.
var configMap *sync.Map
var mutex *sync.Mutex
var fileResolver *utils.RuntimeFileResolver
var builtinPalettes *utils.BuiltinPalettes
var mc *memcache.Client
var (
port = flag.Int("p", 8080, "Server listening port.")
serverDataDir = flag.String("data_dir", utils.DataDir, "Server data directory.")
serverConfigDir = flag.String("conf_dir", utils.EtcDir, "Server config directory.")
serverLogDir = flag.String("log_dir", "", "Server log directory.")
validateConfig = flag.Bool("check_conf", false, "Validate server config files.")
dumpConfig = flag.Bool("dump_conf", false, "Dump server config files.")
mcURI = flag.String("memcache", "", "memcache uri host:port")
verbose = flag.Bool("v", false, "Verbose mode for more server outputs.")
urlBase = flag.String("url_base", "", "Advertise URLs relative to this server name and path. The default is to look this up from incoming request headers. Do not add a trailing slash")
version = flag.Bool("version", false, "Get GSKY version")
)
var reWMSMap map[string]*regexp.Regexp
var reWCSMap map[string]*regexp.Regexp
var reWPSMap map[string]*regexp.Regexp
var (
Error *log.Logger
Info *log.Logger
)
var metricsLogger metrics.Logger
// init initialises the Error logger, checks
// required files are in place and sets Config struct.
// This is the first function to be called in main.
func init() {
rand.Seed(time.Now().UnixNano())
Error = log.New(os.Stderr, "OWS: ", log.Ldate|log.Ltime|log.Lshortfile)
Info = log.New(os.Stdout, "OWS: ", log.Ldate|log.Ltime|log.Lshortfile)
flag.Parse()
if *version {
fmt.Printf("%s\n", utils.GSKYVersion)
os.Exit(0)
}
utils.DataDir = *serverDataDir
utils.EtcDir = *serverConfigDir
fileResolver = utils.NewRuntimeFileResolver(utils.DataDir)
filePaths := []string{
"static/index.html",
"templates/WMS_GetCapabilities.tpl",
"templates/WMS_DescribeLayer.tpl",
"templates/WMS_ServiceException.tpl",
"templates/WPS_DescribeProcess.tpl",
"templates/WPS_Execute.tpl",
"templates/WPS_GetCapabilities.tpl",
"templates/WCS_GetCapabilities.tpl",
"templates/WCS_DescribeCoverage.tpl",
"zoom.png",
}
for _, filePath := range filePaths {
_, err := fileResolver.Lookup(filePath)
if err != nil {
panic(err)
}
}
http.DefaultTransport.(*http.Transport).MaxConnsPerHost = proc.DefaultMASMaxConnsPerHost
confMap, err := utils.LoadAllConfigFiles(utils.EtcDir, *verbose)
if err != nil {
Error.Printf("Error in loading config files: %v\n", err)
panic(err)
}
if *validateConfig {
os.Exit(0)
}
if *dumpConfig {
configJson, err := utils.DumpConfig(confMap)
if err != nil {
Error.Printf("Error in dumping configs: %v\n", err)
} else {
log.Print(configJson)
}
os.Exit(0)
}
if *mcURI != "" {
// lazy connection; errors returned in .Get
mc = memcache.New(*mcURI)
}
configMap = &sync.Map{}
configMap.Store("config", confMap)
utils.WatchConfig(Info, Error, configMap, *verbose)
mutex = &sync.Mutex{}
builtinPalettes = utils.NewBuiltinPalettes()
reWMSMap = utils.CompileWMSRegexMap()
reWCSMap = utils.CompileWCSRegexMap()
reWPSMap = utils.CompileWPSRegexMap()
utils.InitGdal()
if len(*serverLogDir) > 0 {
if *serverLogDir == "-" {
metricsLogger = metrics.NewStdoutLogger()
} else {
maxLogFileSize := int64(0)
if val, ok := os.LookupEnv("GSKY_MAX_LOG_FILE_SIZE"); ok {
valInt, e := strconv.ParseInt(val, 10, 64)
if e == nil {
maxLogFileSize = valInt
} else {
Error.Printf("invalid GSKY_MAX_LOG_FILE_SIZE: %v", e)
}
}
maxLogFiles := -1
if val, ok := os.LookupEnv("GSKY_MAX_LOG_FILES"); ok {
valInt, e := strconv.ParseInt(val, 10, 32)
if e == nil {
maxLogFiles = int(valInt)
} else {
Error.Printf("invalid GSKY_MAX_LOG_FILES: %v", e)
}
}
metricsLogger = metrics.NewFileLogger(*serverLogDir, maxLogFileSize, maxLogFiles, *verbose)
}
}
}
func serveWMS(ctx context.Context, params utils.WMSParams, conf *utils.Config, r *http.Request, w http.ResponseWriter, metricsCollector *metrics.MetricsCollector) {
if params.Request == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, "Malformed WMS, a Request field needs to be specified", 400)
return
}
reqURL := r.URL.String()
switch *params.Request {
case "GetCapabilities":
if params.Version != nil && !utils.CheckWMSVersion(*params.Version) {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("This server can only accept WMS requests compliant with version 1.1.1 and 1.3.0: %s", reqURL), 400)
return
}
urlPath := strings.Trim(r.URL.Path, "/")
query := fmt.Sprintf("wms_getcaps_%s", urlPath)
gpath := utils.FindConfigGPath(conf)
owsCache := utils.NewOWSCache(conf.ServiceConfig.MASAddress, gpath, *verbose)
newConf, err := owsCache.GetConfig(query)
cacheMiss := false
if err != nil {
if *verbose {
log.Printf("WMS GetCapabilities get cache error: %v", err)
}
cacheMiss = true
} else if newConf == nil {
cacheMiss = true
} else if len(newConf.Layers) == 0 {
cacheMiss = true
}
if cacheMiss {
newConf = conf.Copy(r)
err = utils.LoadConfigTimestamps(newConf, *verbose)
if err != nil {
log.Printf("WMS GetCapabilities LoadConfigTimestamps error: %v", err)
}
}
tpl, _ := fileResolver.Lookup("templates/WMS_GetCapabilities.tpl")
err = utils.ExecuteWriteTemplateFile(w, newConf, tpl)
if err != nil {
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
}
if cacheMiss {
jsonBytes, mErr := json.Marshal(newConf)
if mErr == nil {
err = owsCache.Put(query, string(jsonBytes))
if err != nil {
if *verbose {
log.Printf("WMS GetCapabilities put cache error: %v", err)
}
}
} else {
log.Printf("json.Marshal failed for WMS GetCapabilities")
}
}
for iLayer := range conf.Layers {
if len(conf.Layers[iLayer].EffectiveStartDate) == 0 && len(newConf.Layers[iLayer].EffectiveStartDate) > 0 {
mutex.Lock()
conf.Layers[iLayer].EffectiveStartDate = newConf.Layers[iLayer].EffectiveStartDate
conf.Layers[iLayer].EffectiveEndDate = newConf.Layers[iLayer].EffectiveEndDate
mutex.Unlock()
}
}
case "GetFeatureInfo":
x, y, err := utils.GetCoordinates(params)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetFeatureInfo request: %v", err), 400)
return
}
if params.Time == nil {
idx, err := utils.GetLayerIndex(params, conf)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed getFeatureInfo request: %s", reqURL), 400)
return
}
currentTime, err := utils.GetCurrentTimeStamp(conf.Layers[idx].Dates)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("%v: %s", err, reqURL), 400)
return
}
params.Time = currentTime
}
var times []string
for _, axis := range params.Axes {
if axis.Name == utils.WeightedTimeAxis {
for _, val := range axis.InValues {
t := time.Unix(int64(val), 0).UTC().Format(utils.ISOFormat)
times = append(times, fmt.Sprintf(`"%s"`, t))
}
}
}
var timeStr string
if len(times) > 0 {
timeStr = fmt.Sprintf(`"times": [%s]`, strings.Join(times, ","))
} else {
timeStr = fmt.Sprintf(`"time": "%s"`, (*params.Time).Format(utils.ISOFormat))
}
feat_info, err := proc.GetFeatureInfo(ctx, params, conf, getConfigMap(), *verbose, metricsCollector)
if err != nil {
feat_info = fmt.Sprintf(`"error": "%v"`, err)
Error.Printf("%v\n", err)
}
resp := fmt.Sprintf(`{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"x":%f, "y":%f, %s, %s}}]}`, x, y, timeStr, feat_info)
w.Write([]byte(resp))
case "DescribeLayer":
conf = conf.Copy(r)
idx, err := utils.GetLayerIndex(params, conf)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS DescribeLayer request: %v", err), 400)
return
}
tpl, _ := fileResolver.Lookup("templates/WMS_DescribeLayer.tpl")
err = utils.ExecuteWriteTemplateFile(w, conf.Layers[idx], tpl)
if err != nil {
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
}
case "GetMap":
var geojsonClipFeature *geo.Feature
if params.GeojsonFeatureId != nil {
feat, err := utils.GetGeojsonFeature(*params.GeojsonFeatureId, conf.WmsGeojsonClipConfig, mc)
if err == nil && feat != nil {
geojsonClipFeature = feat
} else {
fmt.Println(err)
}
}
if params.Version == nil || !utils.CheckWMSVersion(*params.Version) {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("This server can only accept WMS requests compliant with version 1.1.1 and 1.3.0: %s", reqURL), 400)
return
}
idx, err := utils.GetLayerIndex(params, conf)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetMap request: %v", err), 400)
return
}
if params.Time == nil {
currentTime, err := utils.GetCurrentTimeStamp(conf.Layers[idx].Dates)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("%v: %s", err, reqURL), 400)
return
}
params.Time = currentTime
}
if params.CRS == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain a valid ISO 'crs/srs' parameter.", reqURL), 400)
return
}
if len(params.BBox) != 4 {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain a valid 'bbox' parameter.", reqURL), 400)
return
}
if params.Height == nil || params.Width == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain valid 'width' and 'height' parameters.", reqURL), 400)
return
}
if strings.ToUpper(*params.CRS) == "EPSG:4326" && *params.Version == "1.3.0" {
params.BBox = []float64{params.BBox[1], params.BBox[0], params.BBox[3], params.BBox[2]}
}
if strings.ToUpper(*params.CRS) == "CRS:84" && *params.Version == "1.3.0" {
*params.CRS = "EPSG:4326"
}
var endTime *time.Time
if conf.Layers[idx].Accum == true {
step := time.Minute * time.Duration(60*24*conf.Layers[idx].StepDays+60*conf.Layers[idx].StepHours+conf.Layers[idx].StepMinutes)
eT := params.Time.Add(step)
endTime = &eT
}
if *params.Height > conf.Layers[idx].WmsMaxHeight || *params.Width > conf.Layers[idx].WmsMaxWidth {
http.Error(w, fmt.Sprintf("Requested width/height is too large, max width:%d, height:%d", conf.Layers[idx].WmsMaxWidth, conf.Layers[idx].WmsMaxHeight), 400)
return
}
styleIdx, err := utils.GetLayerStyleIndex(params, conf, idx)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetMap request: %v", err), 400)
return
}
styleLayer := &conf.Layers[idx]
if styleIdx >= 0 {
styleLayer = &conf.Layers[idx].Styles[styleIdx]
}
if utils.CheckDisableServices(styleLayer, "wms") {
Error.Printf("WMS GetMap is disabled for this layer")
metricsCollector.Info.HTTPStatus = 400
http.Error(w, "WMS GetMap is disabled for this layer", 400)
return
}
offset := styleLayer.OffsetValue
scale := styleLayer.ScaleValue
clip := styleLayer.ClipValue
if params.Offset != nil && params.Clip != nil {
offset = *params.Offset
clip = *params.Clip
scale = 0.0
}
palette := styleLayer.Palette
if params.Palette != nil {
palettes := styleLayer.Palettes
if len(palettes) == 0 {
palettes = builtinPalettes.Palettes
}
foundPalette := false
for _, p := range palettes {
if strings.ToLower(p.Name) == strings.ToLower(*params.Palette) {
palette = p
foundPalette = true
break
}
}
if !foundPalette {
msg := fmt.Sprintf("Requested palette not found: %s", *params.Palette)
Error.Printf(msg)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, msg, 400)
return
}
}
colourScale := styleLayer.ColourScale
if params.ColourScale != nil {
colourScale = *params.ColourScale
}
bbox, err := utils.GetCanonicalBbox(*params.CRS, params.BBox)
if err != nil {
bbox = params.BBox
}
reqRes := utils.GetPixelResolution(bbox, *params.Width, *params.Height)
geoReq := &proc.GeoTileRequest{ConfigPayLoad: proc.ConfigPayLoad{NameSpaces: styleLayer.RGBExpressions.VarList,
BandExpr: styleLayer.RGBExpressions,
Mask: styleLayer.Mask,
Palette: palette,
ScaleParams: proc.ScaleParams{Offset: offset,
Scale: scale,
Clip: clip,
ColourScale: colourScale,
},
ZoomLimit: conf.Layers[idx].ZoomLimit,
PolygonSegments: conf.Layers[idx].WmsPolygonSegments,
GrpcConcLimit: conf.Layers[idx].GrpcWmsConcPerNode,
QueryLimit: -1,
UserSrcSRS: conf.Layers[idx].UserSrcSRS,
UserSrcGeoTransform: conf.Layers[idx].UserSrcGeoTransform,
AxisMapping: conf.Layers[idx].WmsAxisMapping,
GrpcTileXSize: conf.Layers[idx].GrpcTileXSize,
GrpcTileYSize: conf.Layers[idx].GrpcTileYSize,
IndexTileXSize: conf.Layers[idx].IndexTileXSize,
IndexTileYSize: conf.Layers[idx].IndexTileYSize,
SpatialExtent: conf.Layers[idx].SpatialExtent,
IndexResLimit: conf.Layers[idx].IndexResLimit,
MasQueryHint: conf.Layers[idx].MasQueryHint,
ReqRes: reqRes,
SRSCf: conf.Layers[idx].SRSCf,
MetricsCollector: metricsCollector,
},
Collection: styleLayer.DataSource,
CRS: *params.CRS,
BBox: params.BBox,
OrigBBox: params.BBox,
Height: *params.Height,
Width: *params.Width,
StartTime: params.Time,
EndTime: endTime,
ClipFeature: geojsonClipFeature,
}
if len(params.Axes) > 0 {
geoReq.Axes = make(map[string]*proc.GeoTileAxis)
for _, axis := range params.Axes {
geoReq.Axes[axis.Name] = &proc.GeoTileAxis{Start: axis.Start, End: axis.End, InValues: axis.InValues, Order: axis.Order, Aggregate: axis.Aggregate}
}
}
if params.BandExpr != nil {
if len(params.BandExpr.Expressions) > 0 && len(params.BandExpr.Expressions) != 1 && len(params.BandExpr.Expressions) != 3 {
err = fmt.Errorf("Number of band expressions must be either 1 or 3 for WMS")
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetMap request: %v", err), 400)
return
}
err := utils.CheckBandExpressionsComplexity(params.BandExpr, conf.Layers[idx].WmsBandExpressionCriteria)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetMap request: %v", err), 400)
return
}
geoReq.ConfigPayLoad.NameSpaces = params.BandExpr.VarList
geoReq.ConfigPayLoad.BandExpr = params.BandExpr
}
ctx, ctxCancel := context.WithCancel(ctx)
defer ctxCancel()
errChan := make(chan error, 100)
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), time.Duration(conf.Layers[idx].WmsTimeout)*time.Second)
defer timeoutCancel()
tp := proc.InitTilePipeline(ctx, styleLayer.MASAddress, conf.ServiceConfig.WorkerNodes, conf.Layers[idx].MaxGrpcRecvMsgSize, conf.Layers[idx].WmsPolygonShardConcLimit, conf.ServiceConfig.MaxGrpcBufferSize, errChan)
tp.CurrentLayer = styleLayer
tp.DataSources = getConfigMap()
hasOverview := len(styleLayer.Overviews) > 0
if hasOverview {
allowExtrapolation := styleLayer.ZoomLimit > 0
iOvr := utils.FindLayerBestOverview(styleLayer, reqRes, allowExtrapolation)
if iOvr >= 0 {
geoReq.Overview = &styleLayer.Overviews[iOvr]
}
}
if !hasOverview && styleLayer.ZoomLimit != 0.0 && reqRes > styleLayer.ZoomLimit {
hasData := tp.HasFiles(geoReq, *verbose)
if hasData {
zoomFile, _ := fileResolver.Lookup("zoom.png")
out, err := utils.GetEmptyTile(zoomFile, *params.Height, *params.Width)
if err != nil {
Info.Printf("Error in the utils.GetEmptyTile(zoom.png): %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
return
}
w.Write(out)
} else {
out, err := utils.GetEmptyTile("", *params.Height, *params.Width)
if err != nil {
Info.Printf("Error in the utils.GetEmptyTile(): %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
} else {
w.Write(out)
}
}
return
}
select {
case res := <-tp.Process(geoReq, *verbose):
scaleParams := utils.ScaleParams{Offset: geoReq.ScaleParams.Offset,
Scale: geoReq.ScaleParams.Scale,
Clip: geoReq.ScaleParams.Clip,
ColourScale: geoReq.ScaleParams.ColourScale,
}
norm, err := utils.Scale(res, scaleParams)
if err != nil {
Info.Printf("Error in the utils.Scale: %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
return
}
if len(norm) == 0 || norm[0].Width == 0 || norm[0].Height == 0 {
out, err := utils.GetEmptyTile(conf.Layers[idx].NoDataLegendPath, *params.Height, *params.Width)
if err != nil {
Info.Printf("Error in the utils.GetEmptyTile(): %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
} else {
w.Write(out)
}
return
}
out, err := utils.EncodePNG(norm, palette)
if err != nil {
Info.Printf("Error in the utils.EncodePNG: %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
return
}
w.Write(out)
case err := <-errChan:
Info.Printf("Error in the pipeline: %v\n", err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
case <-ctx.Done():
Error.Printf("Context cancelled with message: %v\n", ctx.Err())
metricsCollector.Info.HTTPStatus = 500
http.Error(w, ctx.Err().Error(), 500)
case <-timeoutCtx.Done():
Error.Printf("WMS pipeline timed out, threshold:%v seconds", conf.Layers[idx].WmsTimeout)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, "WMS request timed out", 500)
}
return
case "GetLegendGraphic":
idx, err := utils.GetLayerIndex(params, conf)
if err != nil {
Error.Printf("%s\n", err)
if len(params.Layers) > 0 {
tpl, _ := fileResolver.Lookup("templates/WMS_ServiceException.tpl")
utils.ExecuteWriteTemplateFile(w, params.Layers[0], tpl)
} else {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, err.Error(), 400)
}
return
}
styleIdx, err := utils.GetLayerStyleIndex(params, conf, idx)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS GetMap request: %v", err), 400)
return
}
styleLayer := &conf.Layers[idx]
if styleIdx >= 0 {
styleLayer = &conf.Layers[idx].Styles[styleIdx]
}
b, err := ioutil.ReadFile(styleLayer.LegendPath)
if err != nil {
Error.Printf("Error reading legend image: %v, %v\n", styleLayer.LegendPath, err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, "Legend graphics not found", 500)
return
}
w.Write(b)
default:
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("%s not recognised.", *params.Request), 400)
}
}
func serveWCS(ctx context.Context, params utils.WCSParams, conf *utils.Config, r *http.Request, w http.ResponseWriter, query map[string][]string, metricsCollector *metrics.MetricsCollector) {
if params.Request == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, "Malformed WCS, a Request field needs to be specified", 400)
}
reqURL := r.URL.String()
switch *params.Request {
case "GetCapabilities":
if params.Version != nil && !utils.CheckWCSVersion(*params.Version) {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("This server can only accept WCS requests compliant with version 1.0.0: %s", reqURL), 400)
return
}
newConf := conf.Copy(r)
for iLayer := range conf.Layers {
if len(conf.Layers[iLayer].EffectiveStartDate) == 0 {
newConf.GetLayerDates(iLayer, *verbose)
if len(newConf.Layers[iLayer].EffectiveStartDate) > 0 {
mutex.Lock()
conf.Layers[iLayer].EffectiveStartDate = newConf.Layers[iLayer].EffectiveStartDate
conf.Layers[iLayer].EffectiveEndDate = newConf.Layers[iLayer].EffectiveEndDate
mutex.Unlock()
}
}
}
tpl, _ := fileResolver.Lookup("templates/WCS_GetCapabilities.tpl")
err := utils.ExecuteWriteTemplateFile(w, &newConf, tpl)
if err != nil {
metricsCollector.Info.HTTPStatus = 500
http.Error(w, err.Error(), 500)
}
case "DescribeCoverage":
idx, err := utils.GetCoverageIndex(params, conf)
if err != nil {
Info.Printf("Error in the pipeline: %v\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WMS DescribeCoverage request: %v", err), 400)
return
}
newConf := conf.Copy(r)
newConf.GetLayerDates(idx, *verbose)
tpl, _ := fileResolver.Lookup("templates/WCS_DescribeCoverage.tpl")
err = utils.ExecuteWriteTemplateFile(w, newConf.Layers[idx], tpl)
if err != nil {
http.Error(w, err.Error(), 500)
}
case "GetCoverage":
if params.Version == nil || !utils.CheckWCSVersion(*params.Version) {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("This server can only accept WCS requests compliant with version 1.0.0: %s", reqURL), 400)
return
}
idx, err := utils.GetCoverageIndex(params, conf)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("%v: %s", err, reqURL), 400)
return
}
if params.Time == nil {
currentTime, err := utils.GetCurrentTimeStamp(conf.Layers[idx].Dates)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("%v: %s", err, reqURL), 400)
return
}
params.Time = currentTime
}
if params.CRS == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain a valid ISO 'crs/srs' parameter.", reqURL), 400)
return
}
if len(params.BBox) != 4 {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain a valid 'bbox' parameter.", reqURL), 400)
return
}
if params.Height == nil || params.Width == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Request %s should contain valid 'width' and 'height' parameters.", reqURL), 400)
return
}
if params.Format == nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Unsupported encoding format"), 400)
return
}
var endTime *time.Time
if conf.Layers[idx].Accum == true {
step := time.Minute * time.Duration(60*24*conf.Layers[idx].StepDays+60*conf.Layers[idx].StepHours+conf.Layers[idx].StepMinutes)
eT := params.Time.Add(step)
endTime = &eT
}
styleIdx, err := utils.GetCoverageStyleIndex(params, conf, idx)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WCS GetCoverage request: %v", err), 400)
return
} else if styleIdx < 0 {
styleCount := len(conf.Layers[idx].Styles)
if styleCount > 1 && params.BandExpr == nil {
Error.Printf("WCS style not specified")
metricsCollector.Info.HTTPStatus = 400
http.Error(w, "WCS style not specified", 400)
return
} else if styleCount == 1 {
styleIdx = 0
}
}
styleLayer := &conf.Layers[idx]
if styleIdx >= 0 {
styleLayer = &conf.Layers[idx].Styles[styleIdx]
}
if utils.CheckDisableServices(styleLayer, "wcs") {
Error.Printf("WCS GetCoverage is disabled for this layer")
metricsCollector.Info.HTTPStatus = 400
http.Error(w, "WCS GetCoverage is disabled for this layer", 400)
return
}
if params.BandExpr != nil {
err := utils.CheckBandExpressionsComplexity(params.BandExpr, conf.Layers[idx].WcsBandExpressionCriteria)
if err != nil {
Error.Printf("%s\n", err)
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Malformed WCS GetCoverage request: %v", err), 400)
return
}
}
maxXTileSize := conf.Layers[idx].WcsMaxTileWidth
maxYTileSize := conf.Layers[idx].WcsMaxTileHeight
checkpointThreshold := 300
minTilesPerWorker := 5
var wcsWorkerNodes []string
workerTileRequests := [][]*proc.GeoTileRequest{}
_, isWorker := query["wbbox"]
getGeoTileRequest := func(width int, height int, bbox []float64, offX int, offY int) *proc.GeoTileRequest {
geoReq := &proc.GeoTileRequest{ConfigPayLoad: proc.ConfigPayLoad{NameSpaces: styleLayer.RGBExpressions.VarList,
BandExpr: styleLayer.RGBExpressions,
Mask: styleLayer.Mask,
Palette: styleLayer.Palette,
ScaleParams: proc.ScaleParams{Offset: styleLayer.OffsetValue,
Scale: styleLayer.ScaleValue,
Clip: styleLayer.ClipValue,
},
ZoomLimit: 0.0,
PolygonSegments: conf.Layers[idx].WcsPolygonSegments,
GrpcConcLimit: conf.Layers[idx].GrpcWcsConcPerNode,
QueryLimit: -1,
UserSrcSRS: conf.Layers[idx].UserSrcSRS,
UserSrcGeoTransform: conf.Layers[idx].UserSrcGeoTransform,
NoReprojection: params.NoReprojection,
AxisMapping: params.AxisMapping,
GrpcTileXSize: conf.Layers[idx].GrpcTileXSize,
GrpcTileYSize: conf.Layers[idx].GrpcTileYSize,
IndexTileXSize: conf.Layers[idx].IndexTileXSize,
IndexTileYSize: conf.Layers[idx].IndexTileYSize,
SpatialExtent: conf.Layers[idx].SpatialExtent,
IndexResLimit: conf.Layers[idx].IndexResLimit,
MasQueryHint: conf.Layers[idx].MasQueryHint,
SRSCf: conf.Layers[idx].SRSCf,
FusionUnscale: 1,
MetricsCollector: metricsCollector,
},
Collection: styleLayer.DataSource,
CRS: *params.CRS,
BBox: bbox,
OrigBBox: params.BBox,
Height: height,
Width: width,
StartTime: params.Time,
EndTime: endTime,
OffX: offX,
OffY: offY,
}
if len(params.Axes) > 0 {
geoReq.Axes = make(map[string]*proc.GeoTileAxis)
for _, axis := range params.Axes {
geoReq.Axes[axis.Name] = &proc.GeoTileAxis{Start: axis.Start, End: axis.End, InValues: axis.InValues, Order: axis.Order, Aggregate: axis.Aggregate}
for _, sel := range axis.IdxSelectors {
tileIdxSel := &proc.GeoTileIdxSelector{Start: sel.Start, End: sel.End, Step: sel.Step, IsRange: sel.IsRange, IsAll: sel.IsAll}
geoReq.Axes[axis.Name].IdxSelectors = append(geoReq.Axes[axis.Name].IdxSelectors, tileIdxSel)
}
}
}
if params.BandExpr != nil {
geoReq.ConfigPayLoad.NameSpaces = params.BandExpr.VarList
geoReq.ConfigPayLoad.BandExpr = params.BandExpr
}
return geoReq
}
ctx, ctxCancel := context.WithCancel(ctx)
defer ctxCancel()
errChan := make(chan error, 100)
epsg, err := utils.ExtractEPSGCode(*params.CRS)
if err != nil {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Invalid CRS code %s", *params.CRS), 400)
return
}
if *params.Width <= 0 || *params.Height <= 0 {
if isWorker {
msg := "WCS: worker width or height negative"
Info.Printf(msg)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, msg, 500)
return
}
geoReq := getGeoTileRequest(0, 0, params.BBox, 0, 0)
maxWidth, maxHeight, err := proc.ComputeReprojectionExtent(ctx, geoReq, conf.ServiceConfig.MASAddress, conf.ServiceConfig.WorkerNodes, epsg, params.BBox, *verbose)
if *verbose {
Info.Printf("WCS: Output image size: width=%v, height=%v", maxWidth, maxHeight)
}
if maxWidth > 0 && maxHeight > 0 {
*params.Width = maxWidth
*params.Height = maxHeight
rex := regexp.MustCompile(`(?i)&width\s*=\s*[-+]?[0-9]+`)
reqURL = rex.ReplaceAllString(reqURL, ``)
rex = regexp.MustCompile(`(?i)&height\s*=\s*[-+]?[0-9]+`)
reqURL = rex.ReplaceAllString(reqURL, ``)
reqURL += fmt.Sprintf("&width=%d&height=%d", maxWidth, maxHeight)
} else {
errMsg := "WCS: failed to compute output extent"
Info.Printf(errMsg, err)
metricsCollector.Info.HTTPStatus = 500
http.Error(w, errMsg, 500)
return
}
}
if *params.Height > conf.Layers[idx].WcsMaxHeight || *params.Width > conf.Layers[idx].WcsMaxWidth {
metricsCollector.Info.HTTPStatus = 400
http.Error(w, fmt.Sprintf("Requested width/height is too large, max width:%d, height:%d", conf.Layers[idx].WcsMaxWidth, conf.Layers[idx].WcsMaxHeight), 400)
return
}
if !isWorker {
if *params.Width > maxXTileSize || *params.Height > maxYTileSize {
tmpTileRequests := []*proc.GeoTileRequest{}
xRes := (params.BBox[2] - params.BBox[0]) / float64(*params.Width)
yRes := (params.BBox[3] - params.BBox[1]) / float64(*params.Height)
for y := 0; y < *params.Height; y += maxYTileSize {
for x := 0; x < *params.Width; x += maxXTileSize {
yMin := params.BBox[1] + float64(y)*yRes
yMax := math.Min(params.BBox[1]+float64(y+maxYTileSize)*yRes, params.BBox[3])
xMin := params.BBox[0] + float64(x)*xRes
xMax := math.Min(params.BBox[0]+float64(x+maxXTileSize)*xRes, params.BBox[2])
tileXSize := int(.5 + (xMax-xMin)/xRes)
tileYSize := int(.5 + (yMax-yMin)/yRes)
geoReq := getGeoTileRequest(tileXSize, tileYSize, []float64{xMin, yMin, xMax, yMax}, x, *params.Height-y-tileYSize)
tmpTileRequests = append(tmpTileRequests, geoReq)
}
}
for iw, worker := range conf.ServiceConfig.OWSClusterNodes {
parsedURL, err := url.Parse(worker)
if err != nil {
if *verbose {
Info.Printf("WCS: invalid worker hostname %v, (%v of %v)\n", worker, iw, len(conf.ServiceConfig.OWSClusterNodes))
}
continue
}
if parsedURL.Host == conf.ServiceConfig.OWSHostname {
if *verbose {
Info.Printf("WCS: skipping worker whose hostname == OWSHostName %v, (%v of %v)\n", worker, iw, len(conf.ServiceConfig.OWSClusterNodes))
}
continue
}
wcsWorkerNodes = append(wcsWorkerNodes, worker)
}
nWorkers := len(wcsWorkerNodes) + 1
tilesPerWorker := int(math.Round(float64(len(tmpTileRequests)) / float64(nWorkers)))
if tilesPerWorker < minTilesPerWorker {
tilesPerWorker = minTilesPerWorker
}
isLastWorker := false
for i := 0; i < nWorkers; i++ {
iBgn := i * tilesPerWorker
iEnd := iBgn + tilesPerWorker
if iEnd > len(tmpTileRequests) {
iEnd = len(tmpTileRequests)
isLastWorker = true
}
workerTileRequests = append(workerTileRequests, tmpTileRequests[iBgn:iEnd])
if isLastWorker {
break
}
}
} else {
geoReq := getGeoTileRequest(*params.Width, *params.Height, params.BBox, 0, 0)
workerTileRequests = append(workerTileRequests, []*proc.GeoTileRequest{geoReq})
}
} else {
for _, qParams := range []string{"wwidth", "wheight", "woffx", "woffy"} {