/
oms.go
1256 lines (994 loc) · 53.5 KB
/
oms.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
// Copyright (c) 2016 OpenM++
// This code is licensed under the MIT license (see LICENSE.txt for details)
/*
oms is openM++ JSON web-service which is also used as simple web-server for openM++ UI html pages.
Web-service allow to view and update model database(s) and run openM++ models from models/bin subdirectory.
Web-server allow to serve static html (css, images, javascipt) content from html subdirectory.
Arguments for oms can be specified on command line or through .ini file:
oms -ini my-oms.ini
oms -OpenM.IniFile my-oms.ini
Command line arguments take precedence over ini-file options.
Following arguments supporetd by oms:
-oms.RootDir om/root
oms root directory, default: current directory.
Recommended to have log/ subdirectory to store oms web-service log files.
-oms.ModelDir models/bin
models executable and model.sqlite database files directory, default: models/bin,
If relative then must be relative to oms root directory.
-oms.ModelLogDir models/log
models log directory, default: models/log, if relative then must be relative to oms root directory.
-oms.HtmlDir html
front-end UI directory, default: html.
If relative then must be relative to oms root directory.
It is not used if -oms.ApiOnly specified.
-oms.EtcDir etc
configuration files directory, default: etc.
If relative then must be relative to oms root directory.
It is an optional directory, it may contain configuration files,for example, templates to run models on MPI cluster.
-oms.JobDir job
jobs control directory.
If relative then must be relative to oms root directory.
Jobs control allow to manage computational resources (e.g. CPUs) and organize model run queue.
Default value is empty "" string and it is disable jobs control.
-oms.Name someName
instance name which used for job control.
-oms.HomeDir models/home
user personal home directory to store files and settings.
If relative then must be relative to oms root directory.
Default value is empty "" string and it is disable use of home directory.
-oms.AllowDownload false
if true then allow download from user home/io/download directory.
-oms.AllowUpload false
if true then allow upload to user home/io/upload directory.
-l localhost:4040
-oms.Listen localhost:4040
address to listen, default: localhost:4040.
Use -l :4040 if you need to access oms web-service from other computer (make sure firewall configured properly).
-oms.UrlSaveTo someModel.ui.url.txt
file path to save oms URL which can be used to open web UI in browser.
Default: empty value, URL is not saved in a file by default.
Example of URL file content: http://localhost:4040
-oms.ApiOnly false
if true then API only web-service, it is false by default and oms also act as http server for openM++ UI.
-oms.LogRequest false
if true then log HTTP requests on console and/or log file.
-oms.MaxRowCount 100
default number of rows to return from read parameters or output tables, default: 100.
This value is used if web-service method call does not provide explicit number of rows to read.
-oms.Languages en
comma-separated list of supported languages, default: en.
That list is matched with request language list and model language list in order to return proper text results.
-oms.DoubleFormat %.15g
format to convert float or double value to string, default: %.15g.
OpenM++ is using hash digest to compare models, input parameters and output values.
By default float and double values converted into text with "%.15g" format.
-oms.CodePage
"code page" to convert source file into utf-8, for example: windows-1252.
It is used only for compatibility with old Windows files.
-oms.MaxRunHistory 100
max number of completed model runs to keep in run list history, default: 100.
Also oms support OpenM++ standard log settings (described in openM++ wiki):
-OpenM.LogToConsole: if true then log to standard output, default: true
-v: short form of: -OpenM.LogToConsole
-OpenM.LogToFile: if true then log to file
-OpenM.LogFilePath: path to log file, default = current/dir/exeName.log
-OpenM.LogUseDailyStamp: if true then use dayily stamp in log file name (rotate log files dayily)
-OpenM.LogUseTs: if true then use time-stamp in log file name
-OpenM.LogUsePid: if true then use pid-stamp in log file name
-OpenM.LogSql: if true then log sql statements into log file
*/
package main
import (
"context"
"errors"
"flag"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/husobee/vestigo"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/text/language"
"github.com/openmpp/go/ompp/config"
"github.com/openmpp/go/ompp/helper"
"github.com/openmpp/go/ompp/omppLog"
)
// config keys to get values from ini-file or command line arguments.
const (
listenArgKey = "oms.Listen" // address to listen, default: localhost:4040
listenShortKey = "l" // address to listen (short form)
omsNameArgKey = "oms.Name" // oms instance name, if empty then derived from address to listen
urlFileArgKey = "oms.UrlSaveTo" // file path to save oms URL in form of: http://localhost:4040, if relative then must be relative to oms root directory
rootDirArgKey = "oms.RootDir" // oms root directory, expected to contain log subfolder
modelDirArgKey = "oms.ModelDir" // models executable and model.sqlite directory, if relative then must be relative to oms root directory
modelLogDirArgKey = "oms.ModelLogDir" // models log directory, if relative then must be relative to oms root directory
etcDirArgKey = "oms.EtcDir" // configuration files directory, if relative then must be relative to oms root directory
htmlDirArgKey = "oms.HtmlDir" // front-end UI directory, if relative then must be relative to oms root directory
jobDirArgKey = "oms.JobDir" // job control directory, if relative then must be relative to oms root directory
homeDirArgKey = "oms.HomeDir" // user personal home directory, if relative then must be relative to oms root directory
isDownloadArgKey = "oms.AllowDownload" // if true then allow download from user home sub-directory: home/io/download
isUploadArgKey = "oms.AllowUpload" // if true then allow upload to user home sub-directory: home/io/upload
isMicrodataArgKey = "oms.AllowMicrodata" // if true then allow model run microdata
logRequestArgKey = "oms.LogRequest" // if true then log http request
apiOnlyArgKey = "oms.ApiOnly" // if true then API only web-service, no web UI
uiLangsArgKey = "oms.Languages" // list of supported languages
encodingArgKey = "oms.CodePage" // code page for converting source files, e.g. windows-1252
pageSizeAgrKey = "oms.MaxRowCount" // max number of rows to return from read parameters or output tables
runHistorySizeAgrKey = "oms.MaxRunHistory" // max number of completed model runs to keep in run list history
doubleFormatArgKey = "oms.DoubleFormat" // format to convert float or double value to string, e.g. %.15g
)
// max number of completed model run states to keep in run list history
const runHistoryDefaultSize int = 1000
// server run configuration
var theCfg = struct {
rootDir string // server root directory
htmlDir string // front-end UI directory with html and javascript
etcDir string // configuration files directory
isHome bool // if true then it is a single user mode
homeDir string // user home directory
downloadDir string // if download allowed then it is home/io/download directory
uploadDir string // if upload allowed then it is home/io/upload directory
inOutDir string // if download or upload allowed then it is home/io directory
isMicrodata bool // if true then allow model run microdata
isJobControl bool // if true then do job control: model run queue and resource allocation
jobDir string // job control directory
omsName string // oms instance name, if empty then derived from address to listen
dbcopyPath string // if download or upload allowed then it is path to dbcopy.exe
pageMaxSize int64 // default "page" size: row count to read parameters or output tables
runHistoryMaxSize int // max number of completed model run states to keep in run list history
doubleFmt string // format to convert float or double value to string
codePage string // "code page" to convert source file into utf-8, for example: windows-1252
env map[string]string // server config environmemt variables
}{
pageMaxSize: 100,
htmlDir: "html",
etcDir: "etc",
isHome: false,
homeDir: "",
downloadDir: "",
uploadDir: "",
isMicrodata: false,
isJobControl: false,
jobDir: "",
omsName: "",
runHistoryMaxSize: runHistoryDefaultSize,
doubleFmt: "%.15g",
env: map[string]string{},
}
// if true then log http requests
var isLogRequest bool
// matcher to find UI supported language corresponding to request
var uiLangMatcher language.Matcher
// main entry point: wrapper to handle errors
func main() {
defer exitOnPanic() // fatal error handler: log and exit
err := mainBody(os.Args)
if err != nil {
omppLog.Log(err.Error())
os.Exit(1)
}
omppLog.Log("Done.") // compeleted OK
}
// actual main body
func mainBody(args []string) error {
// set command line argument keys and ini-file keys
_ = flag.String(rootDirArgKey, "", "root directory, default: current directory")
_ = flag.String(modelDirArgKey, "models/bin", "models directory, if relative then must be relative to root directory")
_ = flag.String(modelLogDirArgKey, "models/log", "models log directory, if relative then must be relative to root directory")
_ = flag.String(etcDirArgKey, theCfg.etcDir, "configuration files directory, if relative then must be relative to oms root directory")
_ = flag.String(htmlDirArgKey, theCfg.htmlDir, "front-end UI directory, if relative then must be relative to root directory")
_ = flag.String(homeDirArgKey, "", "user personal home directory, if relative then must be relative to root directory")
_ = flag.Bool(isDownloadArgKey, false, "if true then allow download from user home/io/download directory")
_ = flag.Bool(isUploadArgKey, false, "if true then allow upload to user home/io/upload directory")
_ = flag.Bool(isMicrodataArgKey, false, "if true then allow model run microdata")
_ = flag.String(jobDirArgKey, "", "job control directory, if relative then must be relative to root directory")
_ = flag.String(listenArgKey, "localhost:4040", "address to listen")
_ = flag.String(listenShortKey, "localhost:4040", "address to listen (short form of "+listenArgKey+")")
_ = flag.String(omsNameArgKey, "", "instance name, automatically generated if empty")
_ = flag.Bool(logRequestArgKey, false, "if true then log HTTP requests")
_ = flag.String(urlFileArgKey, "", "file path to save oms URL, if relative then must be relative to root directory")
_ = flag.Bool(apiOnlyArgKey, false, "if true then API only web-service, no web UI")
_ = flag.String(uiLangsArgKey, "en", "comma-separated list of supported languages")
_ = flag.String(encodingArgKey, "", "code page to convert source file into utf-8, e.g.: windows-1252")
_ = flag.Int64(pageSizeAgrKey, theCfg.pageMaxSize, "max number of rows to return from read parameters or output tables")
_ = flag.Int(runHistorySizeAgrKey, runHistoryDefaultSize, "max number of model runs to keep in run list history")
_ = flag.String(doubleFormatArgKey, theCfg.doubleFmt, "format to convert float or double value to string")
// pairs of full and short argument names to map short name to full name
optFs := []config.FullShort{
{Full: listenArgKey, Short: listenShortKey},
}
// parse command line arguments and ini-file
runOpts, logOpts, extraArgs, err := config.New(encodingArgKey, optFs)
if err != nil {
return errors.New("Invalid arguments: " + err.Error())
}
if len(extraArgs) > 0 {
return errors.New("Invalid arguments: " + strings.Join(extraArgs, " "))
}
isLogRequest = runOpts.Bool(logRequestArgKey)
isApiOnly := runOpts.Bool(apiOnlyArgKey)
theCfg.isMicrodata = runOpts.Bool(isMicrodataArgKey)
theCfg.pageMaxSize = runOpts.Int64(pageSizeAgrKey, theCfg.pageMaxSize)
theCfg.doubleFmt = runOpts.String(doubleFormatArgKey)
theCfg.runHistoryMaxSize = runOpts.Int(runHistorySizeAgrKey, runHistoryDefaultSize)
if theCfg.runHistoryMaxSize <= 0 {
theCfg.runHistoryMaxSize = runHistoryDefaultSize
}
theCfg.codePage = runOpts.String(encodingArgKey)
// get server config environmemt variables
env := os.Environ()
for _, e := range env {
if strings.HasPrefix(e, "OM_CFG_") {
if kv := strings.SplitN(e, "=", 2); len(kv) == 2 {
theCfg.env[kv[0]] = kv[1]
}
}
}
omsAbsPath, err := filepath.Abs(args[0])
if err != nil {
return errors.New("Error: unable to make absolute path to oms: " + err.Error())
}
// change to root directory
theCfg.rootDir = runOpts.String(rootDirArgKey) // server root directory
if theCfg.rootDir != "" && theCfg.rootDir != "." {
if err := os.Chdir(theCfg.rootDir); err != nil {
return errors.New("Error: unable to change directory: " + err.Error())
}
}
omppLog.New(logOpts) // adjust log options, log path can be relative to root directory
if theCfg.rootDir != "" && theCfg.rootDir != "." {
omppLog.Log("Change directory to: ", theCfg.rootDir)
}
// model directory required to build initial list of model sqlite files
modelLogDir := runOpts.String(modelLogDirArgKey)
modelDir := filepath.Clean(runOpts.String(modelDirArgKey))
if modelDir == "" || modelDir == "." {
return errors.New("Error: model directory argument cannot be empty or . dot")
}
omppLog.Log("Models directory: ", modelDir)
if err := theCatalog.refreshSqlite(modelDir, modelLogDir); err != nil {
return err
}
// check if it is single user run mode and use of home directory enabled
if theCfg.homeDir = runOpts.String(homeDirArgKey); theCfg.homeDir != "" {
if !dirExist(theCfg.homeDir) {
omppLog.Log("Warning: user home directory not found: ", theCfg.homeDir)
theCfg.homeDir = ""
}
theCfg.isHome = theCfg.homeDir != ""
if theCfg.isHome {
omppLog.Log("User directory: ", theCfg.homeDir)
}
}
// check download and upload options:
// home/io/download or home/io/upload directory must exist and dbcopy.exe must exist
isInOut := runOpts.Bool(isDownloadArgKey) || runOpts.Bool(isUploadArgKey)
isDownload := false
isUpload := false
if isInOut {
if theCfg.homeDir != "" {
theCfg.inOutDir = filepath.Join(theCfg.homeDir, "io") // download and upload directory for web-server, to serve static content
if dirExist(theCfg.inOutDir) {
theCfg.dbcopyPath = dbcopyPath(omsAbsPath)
}
}
isInOut = theCfg.inOutDir != "" && theCfg.dbcopyPath != ""
if !isInOut {
theCfg.inOutDir = ""
theCfg.dbcopyPath = ""
}
}
if runOpts.Bool(isDownloadArgKey) {
if isInOut && theCfg.inOutDir != "" {
theCfg.downloadDir = filepath.Join(theCfg.inOutDir, "download") // download directory UI
if !dirExist(theCfg.downloadDir) {
theCfg.downloadDir = ""
}
}
isDownload = isInOut && theCfg.downloadDir != ""
if !isDownload {
theCfg.downloadDir = ""
omppLog.Log("Warning: user home download directory not found or dbcopy not found, download disabled")
} else {
omppLog.Log("Download directory: ", theCfg.downloadDir)
}
}
if runOpts.Bool(isUploadArgKey) {
if isInOut && theCfg.inOutDir != "" {
theCfg.uploadDir = filepath.Join(theCfg.inOutDir, "upload") // upload directory UI
if !dirExist(theCfg.uploadDir) {
theCfg.uploadDir = ""
}
}
isUpload = isInOut && theCfg.uploadDir != ""
if !isUpload {
theCfg.uploadDir = ""
omppLog.Log("Warning: user home upload directory not found or dbcopy not found, upload disabled")
} else {
omppLog.Log("Upload directory: ", theCfg.uploadDir)
}
}
// if UI required then server root directory must have html subdir
if !isApiOnly {
theCfg.htmlDir = runOpts.String(htmlDirArgKey)
if !dirExist(theCfg.htmlDir) {
isApiOnly = true
omppLog.Log("Warning: serving API only because UI directory not found: ", theCfg.htmlDir)
} else {
omppLog.Log("HTML UI directory: ", theCfg.htmlDir)
}
}
// check if job control is required:
theCfg.jobDir = runOpts.String(jobDirArgKey)
if err := jobDirValid(theCfg.jobDir); err != nil {
return errors.New("Error: invalid job control directory: " + err.Error())
}
theCfg.isJobControl = theCfg.jobDir != ""
if theCfg.isJobControl {
omppLog.Log("Jobs directory: ", theCfg.jobDir)
}
// etc subdirectory required to run MPI models
theCfg.etcDir = runOpts.String(etcDirArgKey)
if !dirExist(theCfg.etcDir) {
omppLog.Log("Warning: configuration files directory not found, it is required to run models on MPI cluster: ", filepath.Join(theCfg.etcDir))
} else {
omppLog.Log("Etc directory: ", theCfg.etcDir)
}
// make instance name, use address to listen if name not specified
theCfg.omsName = runOpts.String(omsNameArgKey)
if theCfg.omsName == "" {
theCfg.omsName = runOpts.String(listenArgKey)
}
theCfg.omsName = helper.CleanPath(theCfg.omsName)
omppLog.Log("Oms instance name: ", theCfg.omsName)
// refresh run state catalog and start scanning model log files
jsc, _ := jobStateRead()
if err := theRunCatalog.refreshCatalog(theCfg.etcDir, jsc); err != nil {
return err
}
doneLogScanC := make(chan bool)
go scanModelLogDirs(doneLogScanC)
// start scanning for model run jobs
doneOuterJobScanC := make(chan bool)
go scanOuterJobs(doneOuterJobScanC)
doneStateJobScanC := make(chan bool)
go scanStateJobs(doneStateJobScanC)
doneRunScanC := make(chan bool)
go scanRunJobs(doneRunScanC)
// set UI languages to find model text in browser language
ll := strings.Split(runOpts.String(uiLangsArgKey), ",")
var lt []language.Tag
for _, ls := range ll {
if ls != "" {
lt = append(lt, language.Make(ls))
}
}
if len(lt) <= 0 {
lt = append(lt, language.English)
}
uiLangMatcher = language.NewMatcher(lt)
// setup router and start server
router := vestigo.NewRouter()
router.SetGlobalCors(&vestigo.CorsAccessControl{
AllowOrigin: []string{"*"},
AllowCredentials: true,
AllowHeaders: []string{"Content-Type"},
ExposeHeaders: []string{"Content-Type", "Content-Location"},
})
apiGetRoutes(router) // web-service /api routes to get metadata
apiReadRoutes(router) // web-service /api routes to read values
apiReadCsvRoutes(router) // web-service /api routes to read values into csv stream
if isDownload {
apiDownloadRoutes(router) // web-service /api routes to download files from home/io/download
}
if isUpload {
apiUploadRoutes(router) // web-service /api routes to upload files to home/io/upload
}
apiUpdateRoutes(router) // web-service /api routes to update metadata
apiRunModelRoutes(router) // web-service /api routes to run the model
apiUserRoutes(router) // web-service /api routes for user-specific requests
apiServiceRoutes(router) // web-service /api routes for service state
apiAdminRoutes(router) // web-service /api routes for administrative tasks
// serve static content from home/io/download folder
if isDownload {
router.Get("/download/*", downloadHandler, logRequest)
}
// serve static content from home/io/upload folder
if isUpload {
router.Get("/upload/*", downloadHandler, logRequest)
}
// set web root handler: UI web pages or "not found" if this is web-service mode
if !isApiOnly {
router.Get("/*", homeHandler, logRequest) // serve UI web pages
} else {
router.Get("/*", http.NotFound) // only /api, any other pages not found
}
// initialize server
addr := runOpts.String(listenArgKey)
srv := http.Server{Addr: addr, Handler: router}
// add shutdown handler, it does not wait for requests, it does reset connections and exit
// PUT /api/admin/shutdown
ctx, cancel := context.WithCancel((context.Background()))
defer cancel()
adminShutdownHandler := func(w http.ResponseWriter, r *http.Request) {
// close models catalog
omppLog.Log("Shutdown server...")
if err := theCatalog.close(); err != nil {
omppLog.Log(err)
}
// send response: confirm shutdown
srv.SetKeepAlivesEnabled(false)
w.Write([]byte("Shutdown completed"))
cancel() // send shutdown completed to the main
}
router.Put("/api/admin/shutdown", adminShutdownHandler, logRequest)
// start to listen at specified TCP address
ln, err := net.Listen("tcp", addr)
if err != nil {
omppLog.Log("Error at start of TCP listen: ", addr)
return err
}
ta, ok := ln.Addr().(*net.TCPAddr)
if !ok {
return errors.New("Error: unable to find TCP port of: " + addr)
}
localUrl := "http://localhost:" + strconv.Itoa(ta.Port)
// if url file path specified then write oms url into that url file
if urlFile := runOpts.String(urlFileArgKey); urlFile != "" {
if err = os.WriteFile(urlFile, []byte(localUrl), 0644); err != nil {
omppLog.Log("Error at writing into: ", urlFile)
return err
}
}
// initialization completed, notify user and start the server
omppLog.Log("Listen at ", addr)
if !isApiOnly {
omppLog.Log("To start open in your browser: ", localUrl)
}
omppLog.Log("To finish press Ctrl+C")
go func() {
if err = srv.Serve(ln); err != nil {
// if err = srv.ListenAndServe(); err != nil {
// send completed by error to the main
// error may be http.ErrServerClosed by shutdown which is not an actual error
cancel()
}
}()
// wait for shutdown or Ctrl+C interupt signal
<-ctx.Done()
if e := srv.Shutdown(context.Background()); e != nil && e != http.ErrServerClosed {
omppLog.Log("Shutdown error: ", e)
} else {
// shutdown completed without error: clean main error code
if err == http.ErrServerClosed {
err = nil
}
}
doneRunScanC <- true
doneStateJobScanC <- true
doneOuterJobScanC <- true
doneLogScanC <- true
return err
}
// exitOnPanic log error message and exit with return = 2
func exitOnPanic() {
r := recover()
if r == nil {
return // not in panic
}
switch e := r.(type) {
case error:
omppLog.Log(e.Error())
case string:
omppLog.Log(e)
default:
omppLog.Log("FAILED")
}
os.Exit(2) // final exit
}
// homeHandler is static pages handler for front-end UI served on web / root.
// Only GET requests expected.
func homeHandler(w http.ResponseWriter, r *http.Request) {
setContentType(http.FileServer(http.Dir(theCfg.htmlDir))).ServeHTTP(w, r)
}
// downloadHandler is static file download handler from user home/io/download and home/io/upload folders.
// Files served from home/io directory URLs are:
//
// https://domain.name/download/file.name
// https://domain.name/upload/file.name
//
// Only GET requests expected.
func downloadHandler(w http.ResponseWriter, r *http.Request) {
setContentType(http.FileServer(http.Dir(theCfg.inOutDir))).ServeHTTP(w, r)
}
// add http GET web-service /api routes to get metadata
func apiGetRoutes(router *vestigo.Router) {
//
// GET model definition
//
// GET /api/model-list
router.Get("/api/model-list", modelListHandler, logRequest)
// GET /api/model-list/text
// GET /api/model-list/text/lang/:lang
router.Get("/api/model-list/text", modelTextListHandler, logRequest)
router.Get("/api/model-list/text/lang/:lang", modelTextListHandler, logRequest)
router.Get("/api/model-list/text/lang/", http.NotFound)
// GET /api/model/:model
router.Get("/api/model/:model", modelMetaHandler, logRequest)
router.Get("/api/model/", http.NotFound)
// GET /api/model/:model/text
// GET /api/model/:model/text/lang/:lang
router.Get("/api/model/:model/text", modelTextHandler, logRequest)
router.Get("/api/model/:model/text/lang/:lang", modelTextHandler, logRequest)
router.Get("/api/model/:model/text/lang/", http.NotFound)
// GET /api/model/:model/text/all
router.Get("/api/model/:model/text/all", modelAllTextHandler, logRequest)
//
// GET model extra: languages, profile(s)
//
// GET /api/model/:model/lang-list
router.Get("/api/model/:model/lang-list", langListHandler, logRequest)
// GET /api/model/:model/word-list
// GET /api/model/:model/word-list/lang/:lang
router.Get("/api/model/:model/word-list", wordListHandler, logRequest)
router.Get("/api/model/:model/word-list/lang/:lang", wordListHandler, logRequest)
router.Get("/api/model/:model/word-list/lang/", http.NotFound)
// GET /api/model/:model/profile/:profile
router.Get("/api/model/:model/profile/:profile", modelProfileHandler, logRequest)
router.Get("/api/model/:model/profile/", http.NotFound)
// GET /api/model/:model/profile-list
router.Get("/api/model/:model/profile-list", modelProfileListHandler, logRequest)
//
// GET model run results
//
// GET /api/model/:model/run-list
router.Get("/api/model/:model/run-list", runListHandler, logRequest)
// GET /api/model/:model/run-list/text
// GET /api/model/:model/run-list/text/lang/:lang
router.Get("/api/model/:model/run-list/text", runListTextHandler, logRequest)
router.Get("/api/model/:model/run-list/text/lang/:lang", runListTextHandler, logRequest)
router.Get("/api/model/:model/run-list/text/lang/", http.NotFound)
// GET /api/model/:model/run/:run/status
router.Get("/api/model/:model/run/:run/status", runStatusHandler, logRequest)
// GET /api/model/:model/run/:run/status/list
router.Get("/api/model/:model/run/:run/status/list", runStatusListHandler, logRequest)
// GET /api/model/:model/run/status/first
router.Get("/api/model/:model/run/status/first", firstRunStatusHandler, logRequest)
// GET /api/model/:model/run/status/last
router.Get("/api/model/:model/run/status/last", lastRunStatusHandler, logRequest)
// GET /api/model/:model/run/status/last-completed
router.Get("/api/model/:model/run/status/last-completed", lastCompletedRunStatusHandler, logRequest)
// GET /api/model/:model/run/:run
router.Get("/api/model/:model/run/:run", runFullHandler, logRequest)
router.Get("/api/model/:model/run/", http.NotFound)
router.Get("/api/model/:model/run/:run/", http.NotFound)
// GET /api/model/:model/run/:run/text
// GET /api/model/:model/run/:run/text/lang/:lang
router.Get("/api/model/:model/run/:run/text", runTextHandler, logRequest)
router.Get("/api/model/:model/run/:run/text/lang/:lang", runTextHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/run/:run/text/", http.NotFound)
router.Get("/api/model/:model/run/:run/text/lang/", http.NotFound)
// GET /api/model/:model/run/:run/text/all
router.Get("/api/model/:model/run/:run/text/all", runAllTextHandler, logRequest)
//
// GET model set of input parameters (workset)
//
// GET /api/model/:model/workset-list
router.Get("/api/model/:model/workset-list", worksetListHandler, logRequest)
// GET /api/model/:model/workset-list/text
// GET /api/model/:model/workset-list/text/lang/:lang
router.Get("/api/model/:model/workset-list/text", worksetListTextHandler, logRequest)
router.Get("/api/model/:model/workset-list/text/lang/:lang", worksetListTextHandler, logRequest)
router.Get("/api/model/:model/workset-list/text/lang/", http.NotFound)
// GET /api/model/:model/workset/:set/status
router.Get("/api/model/:model/workset/:set/status", worksetStatusHandler, logRequest)
// GET /api/model/:model/workset/status/default
router.Get("/api/model/:model/workset/status/default", worksetDefaultStatusHandler, logRequest)
// GET /api/model/:model/workset/:set/text
// GET /api/model/:model/workset/:set/text/lang/:lang
router.Get("/api/model/:model/workset/:set/text", worksetTextHandler, logRequest)
router.Get("/api/model/:model/workset/:set/text/lang/:lang", worksetTextHandler, logRequest)
router.Get("/api/model/:model/workset/:set/text/lang/", http.NotFound)
router.Get("/api/model/:model/workset/:set/", http.NotFound)
router.Get("/api/model/:model/workset/:set/text/", http.NotFound)
// GET /api/model/:model/workset/:set/text/all
router.Get("/api/model/:model/workset/:set/text/all", worksetAllTextHandler, logRequest)
//
// GET modeling tasks and task run history
//
// GET /api/model/:model/task-list
router.Get("/api/model/:model/task-list", taskListHandler, logRequest)
// GET /api/model/:model/task-list/text
// GET /api/model/:model/task-list/text/lang/:lang
router.Get("/api/model/:model/task-list/text", taskListTextHandler, logRequest)
router.Get("/api/model/:model/task-list/text/lang/:lang", taskListTextHandler, logRequest)
router.Get("/api/model/:model/task-list/text/lang/", http.NotFound)
// GET /api/model/:model/task/:task/sets
router.Get("/api/model/:model/task/:task/sets", taskSetsHandler, logRequest)
// GET /api/model/:model/task/:task/runs
router.Get("/api/model/:model/task/:task/runs", taskRunsHandler, logRequest)
// GET /api/model/:model/task/:task/run-status/run/:run
router.Get("/api/model/:model/task/:task/run-status/run/:run", taskRunStatusHandler, logRequest)
router.Get("/api/model/:model/task/:task/run-status/run/", http.NotFound)
// GET /api/model/:model/task/:task/run-status/list/:run
router.Get("/api/model/:model/task/:task/run-status/list/:run", taskRunStatusListHandler, logRequest)
router.Get("/api/model/:model/task/:task/run-status/list/", http.NotFound)
// GET /api/model/:model/task/:task/run-status/first
router.Get("/api/model/:model/task/:task/run-status/first", firstTaskRunStatusHandler, logRequest)
// GET /api/model/:model/task/:task/run-status/last
router.Get("/api/model/:model/task/:task/run-status/last", lastTaskRunStatusHandler, logRequest)
// GET /api/model/:model/task/:task/run-status/last-completed
router.Get("/api/model/:model/task/:task/run-status/last-completed", lastCompletedTaskRunStatusHandler, logRequest)
// GET /api/model/:model/task/:task/text
// GET /api/model/:model/task/:task/text/lang/:lang
router.Get("/api/model/:model/task/:task/text", taskTextHandler, logRequest)
router.Get("/api/model/:model/task/:task/text/lang/:lang", taskTextHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/task/:task/", http.NotFound)
router.Get("/api/model/:model/task/:task/text/", http.NotFound)
router.Get("/api/model/:model/task/:task/text/lang/", http.NotFound)
// GET /api/model/:model/task/:task/text/all
router.Get("/api/model/:model/task/:task/text/all", taskAllTextHandler, logRequest)
}
// add http GET or POST web-service /api routes to read parameters or output tables
func apiReadRoutes(router *vestigo.Router) {
// POST /api/model/:model/workset/:set/parameter/value
// POST /api/model/:model/workset/:set/parameter/value-id
router.Post("/api/model/:model/workset/:set/parameter/value", worksetParameterPageReadHandler, logRequest)
router.Post("/api/model/:model/workset/:set/parameter/value-id", worksetParameterIdPageReadHandler, logRequest)
// POST /api/model/:model/run/:run/parameter/value
// POST /api/model/:model/run/:run/parameter/value-id
router.Post("/api/model/:model/run/:run/parameter/value", runParameterPageReadHandler, logRequest)
router.Post("/api/model/:model/run/:run/parameter/value-id", runParameterIdPageReadHandler, logRequest)
// POST /api/model/:model/run/:run/table/value
// POST /api/model/:model/run/:run/table/value-id
router.Post("/api/model/:model/run/:run/table/value", runTablePageReadHandler, logRequest)
router.Post("/api/model/:model/run/:run/table/value-id", runTableIdPageReadHandler, logRequest)
if theCfg.isMicrodata {
// POST /api/model/:model/run/:run/microdata/value
// POST /api/model/:model/run/:run/microdata/value-id
router.Post("/api/model/:model/run/:run/microdata/value", runMicrodataPageReadHandler, logRequest)
router.Post("/api/model/:model/run/:run/microdata/value-id", runMicrodataIdPageReadHandler, logRequest)
}
// GET /api/model/:model/workset/:set/parameter/:name/value
// GET /api/model/:model/workset/:set/parameter/:name/value/start/:start
// GET /api/model/:model/workset/:set/parameter/:name/value/start/:start/count/:count
router.Get("/api/model/:model/workset/:set/parameter/:name/value", worksetParameterPageGetHandler, logRequest)
router.Get("/api/model/:model/workset/:set/parameter/:name/value/start/:start", worksetParameterPageGetHandler, logRequest)
router.Get("/api/model/:model/workset/:set/parameter/:name/value/start/:start/count/:count", worksetParameterPageGetHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/workset/:set/parameter/:name/", http.NotFound)
router.Get("/api/model/:model/workset/:set/parameter/:name/value/", http.NotFound)
router.Get("/api/model/:model/workset/:set/parameter/:name/value/start/", http.NotFound)
router.Get("/api/model/:model/workset/:set/parameter/:name/value/start/:start/count/", http.NotFound)
// GET /api/model/:model/run/:run/parameter/:name/value
// GET /api/model/:model/run/:run/parameter/:name/value/start/:start
// GET /api/model/:model/run/:run/parameter/:name/value/start/:start/count/:count
router.Get("/api/model/:model/run/:run/parameter/:name/value", runParameterPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/parameter/:name/value/start/:start", runParameterPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/parameter/:name/value/start/:start/count/:count", runParameterPageGetHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/run/:run/parameter/:name/", http.NotFound)
router.Get("/api/model/:model/run/:run/parameter/:name/value/", http.NotFound)
router.Get("/api/model/:model/run/:run/parameter/:name/value/start/", http.NotFound)
router.Get("/api/model/:model/run/:run/parameter/:name/value/start/:start/count/", http.NotFound)
// GET /api/model/:model/run/:run/table/:name/expr
// GET /api/model/:model/run/:run/table/:name/expr/start/:start
// GET /api/model/:model/run/:run/table/:name/expr/start/:start/count/:count
router.Get("/api/model/:model/run/:run/table/:name/expr", runTableExprPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/expr/start/:start", runTableExprPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/expr/start/:start/count/:count", runTableExprPageGetHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/run/:run/table/:name/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/expr/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/expr/start/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/expr/start/:start/count/", http.NotFound)
// GET /api/model/:model/run/:run/table/:name/acc/start/:start
// GET /api/model/:model/run/:run/table/:name/acc/start/:start/count/:count
router.Get("/api/model/:model/run/:run/table/:name/acc", runTableAccPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/acc/start/:start", runTableAccPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/acc/start/:start/count/:count", runTableAccPageGetHandler, logRequest)
// reject if request ill-formed
// router.Get("/api/model/:model/run/:run/table/:name/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/acc/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/acc/start/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/acc/start/:start/count/", http.NotFound)
// GET /api/model/:model/run/:run/table/:name/all-acc
// GET /api/model/:model/run/:run/table/:name/all-acc/start/:start
// GET /api/model/:model/run/:run/table/:name/all-acc/start/:start/count/:count
router.Get("/api/model/:model/run/:run/table/:name/all-acc", runTableAllAccPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/all-acc/start/:start", runTableAllAccPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/table/:name/all-acc/start/:start/count/:count", runTableAllAccPageGetHandler, logRequest)
// reject if request ill-formed
// router.Get("/api/model/:model/run/:run/table/:name/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/all-acc/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/all-acc/start/", http.NotFound)
router.Get("/api/model/:model/run/:run/table/:name/all-acc/start/:start/count/", http.NotFound)
if theCfg.isMicrodata {
// GET /api/model/:model/run/:run/microdata/:name/value
// GET /api/model/:model/run/:run/microdata/:name/value/start/:start
// GET /api/model/:model/run/:run/microdata/:name/value/start/:start/count/:count
router.Get("/api/model/:model/run/:run/microdata/:name/value", runMicrodatarPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/microdata/:name/value/start/:start", runMicrodatarPageGetHandler, logRequest)
router.Get("/api/model/:model/run/:run/microdata/:name/value/start/:start/count/:count", runMicrodatarPageGetHandler, logRequest)
// reject if request ill-formed
router.Get("/api/model/:model/run/:run/microdata/:name/", http.NotFound)
router.Get("/api/model/:model/run/:run/microdata/:name/value/", http.NotFound)
router.Get("/api/model/:model/run/:run/microdata/:name/value/start/", http.NotFound)
router.Get("/api/model/:model/run/:run/microdata/:name/value/start/:start/count/", http.NotFound)
}
}
// add http GET web-service /api routes to read parameters or output tables as csv stream
func apiReadCsvRoutes(router *vestigo.Router) {
// GET /api/model/:model/workset/:set/parameter/:name/csv
router.Get("/api/model/:model/workset/:set/parameter/:name/csv", worksetParameterCsvGetHandler, logRequest)
// GET /api/model/:model/workset/:set/parameter/:name/csv-bom
router.Get("/api/model/:model/workset/:set/parameter/:name/csv-bom", worksetParameterCsvBomGetHandler, logRequest)
// GET /api/model/:model/workset/:set/parameter/:name/csv-id
router.Get("/api/model/:model/workset/:set/parameter/:name/csv-id", worksetParameterIdCsvGetHandler, logRequest)
// GET /api/model/:model/workset/:set/parameter/:name/csv-id-bom
router.Get("/api/model/:model/workset/:set/parameter/:name/csv-id-bom", worksetParameterIdCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/parameter/:name/csv
router.Get("/api/model/:model/run/:run/parameter/:name/csv", runParameterCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/parameter/:name/csv-bom
router.Get("/api/model/:model/run/:run/parameter/:name/csv-bom", runParameterCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/parameter/:name/csv-id
router.Get("/api/model/:model/run/:run/parameter/:name/csv-id", runParameterIdCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/parameter/:name/csv-id-bom
router.Get("/api/model/:model/run/:run/parameter/:name/csv-id-bom", runParameterIdCsvBomGetHandler, logRequest)
if theCfg.isMicrodata {
// GET /api/model/:model/run/:run/microdata/:name/csv
router.Get("/api/model/:model/run/:run/microdata/:name/csv", runMicrodataCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/microdata/:name/csv-bom
router.Get("/api/model/:model/run/:run/microdata/:name/csv-bom", runMicrodataCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/microdata/:name/csv-id
router.Get("/api/model/:model/run/:run/microdata/:name/csv-id", runMicrodataIdCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/microdata/:name/csv-id-bom
router.Get("/api/model/:model/run/:run/microdata/:name/csv-id-bom", runMicrodataIdCsvBomGetHandler, logRequest)
}
// GET /api/model/:model/run/:run/table/:name/expr/csv
router.Get("/api/model/:model/run/:run/table/:name/expr/csv", runTableExprCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/expr/csv-bom
router.Get("/api/model/:model/run/:run/table/:name/expr/csv-bom", runTableExprCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/expr/csv-id
router.Get("/api/model/:model/run/:run/table/:name/expr/csv-id", runTableExprIdCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/expr/csv-id-bom
router.Get("/api/model/:model/run/:run/table/:name/expr/csv-id-bom", runTableExprIdCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/acc/csv
router.Get("/api/model/:model/run/:run/table/:name/acc/csv", runTableAccCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/acc/csv-bom
router.Get("/api/model/:model/run/:run/table/:name/acc/csv-bom", runTableAccCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/acc/csv-id
router.Get("/api/model/:model/run/:run/table/:name/acc/csv-id", runTableAccIdCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/acc/csv-id-bom
router.Get("/api/model/:model/run/:run/table/:name/acc/csv-id-bom", runTableAccIdCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/all-acc/csv
router.Get("/api/model/:model/run/:run/table/:name/all-acc/csv", runTableAllAccCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/all-acc/csv-bom
router.Get("/api/model/:model/run/:run/table/:name/all-acc/csv-bom", runTableAllAccCsvBomGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/all-acc/csv-id
router.Get("/api/model/:model/run/:run/table/:name/all-acc/csv-id", runTableAllAccIdCsvGetHandler, logRequest)
// GET /api/model/:model/run/:run/table/:name/all-acc/csv-id-bom
router.Get("/api/model/:model/run/:run/table/:name/all-acc/csv-id-bom", runTableAllAccIdCsvBomGetHandler, logRequest)
}
// add web-service /api routes to update metadata
func apiUpdateRoutes(router *vestigo.Router) {
//
// update profile
//
// PATCH /api/model/:model/profile
router.Patch("/api/model/:model/profile", profileReplaceHandler, logRequest)
router.Patch("/api/model/:model/profile/", http.NotFound)
// DELETE /api/model/:model/profile/:profile
router.Delete("/api/model/:model/profile/:profile", profileDeleteHandler, logRequest)
router.Delete("/api/model/:model/profile/", http.NotFound)
// POST /api/model/:model/profile/:profile/key/:key/value/:value
router.Post("/api/model/:model/profile/:profile/key/:key/value/:value", profileOptionReplaceHandler, logRequest)
router.Post("/api/model/:model/profile/:profile/key/:key/value/", http.NotFound)
// DELETE /api/model/:model/profile/:profile/key/:key
router.Delete("/api/model/:model/profile/:profile/key/:key", profileOptionDeleteHandler, logRequest)
router.Delete("/api/model/:model/profile/:profile/key/", http.NotFound)
//
// update model set of input parameters (workset)
//
// POST /api/model/:model/workset/:set/readonly/:readonly
router.Post("/api/model/:model/workset/:set/readonly/:readonly", worksetReadonlyUpdateHandler, logRequest)
router.Post("/api/model/:model/workset/:set/readonly/", http.NotFound)
// PUT /api/workset-create
router.Put("/api/workset-create", worksetCreateHandler, logRequest)
// PUT /api/workset-replace