-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
168 lines (142 loc) · 4.88 KB
/
main.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
package main
import (
"fmt"
"github.com/HISP-Uganda/mfl-integrator/config"
"github.com/HISP-Uganda/mfl-integrator/controllers"
"github.com/HISP-Uganda/mfl-integrator/models"
"github.com/gin-gonic/gin"
"github.com/go-co-op/gocron"
"github.com/jmoiron/sqlx"
"github.com/samply/golang-fhir-models/fhir-models/fhir"
log "github.com/sirupsen/logrus"
"os"
"sync"
"time"
)
func init() {
formatter := new(log.TextFormatter)
formatter.TimestampFormat = time.RFC3339
formatter.FullTimestamp = true
//file, err := os.OpenFile(
// config.MFLIntegratorConf.Server.LogDirectory+string(os.PathSeparator)+"server.log",
// os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
//if err != nil {
// log.Fatal(err)
//}
//log.SetOutput(io.MultiWriter(os.Stdout, file))
// defer file.Close()
log.SetFormatter(formatter)
log.SetOutput(os.Stdout)
}
type LocationEntry struct {
FullURL string `json:"fullUrl"`
Resource fhir.Location `json:"resource"`
}
var splash = `
┏┳┓┏━╸╻ ╺┳╸┏━┓ ╺┳┓╻ ╻╻┏━┓┏━┓
┃┃┃┣╸ ┃ ┃ ┃ ┃ ┃┃┣━┫┃┗━┓┏━┛
╹ ╹╹ ┗━╸ ╹ ┗━┛ ╺┻┛╹ ╹╹┗━┛┗━
`
func main() {
fmt.Printf(splash)
dbConn, err := sqlx.Connect("postgres", config.MFLIntegratorConf.Database.URI)
if err != nil {
log.Fatalln(err)
}
// log.WithField("DHIS2_SERVER_CONFIGS", config.MFLDHIS2ServersConfigMap).Info("SERVER: =======>")
LoadServersFromConfigFiles(config.MFLDHIS2ServersConfigMap)
// log.WithFields(log.Fields{"Servers": models.ServerMapByName["localhost"]}).Info("SERVERS==>>")
// os.Exit(1)
go func() {
// Create a new scheduler
s := gocron.NewScheduler(time.UTC)
// Schedule the task to run "30 minutes after midn, 4am, 8am, 12pm..., everyday"
// if --skip-ousync flag is on we ignore
if !*config.SkipOUSync {
log.WithFields(log.Fields{"SyncCronExpression": config.MFLIntegratorConf.API.MFLSyncCronExpression}).Info(
"Facility Synchronisation Cron Expression")
_, err := s.Cron(config.MFLIntegratorConf.API.MFLSyncCronExpression).Do(FetchFacilitiesByDistrict)
// _, err := s.CronWithSeconds("* * * * * *").Do(task)
if err != nil {
log.WithError(err).Error("Error scheduling facility sync task:")
return
}
}
// retrying incomplete requests runs every 5 minutes
log.WithFields(log.Fields{"RetryCronExpression": config.MFLIntegratorConf.API.MFLRetryCronExpression}).Info(
"Request Retry Cron Expression")
if !*config.SkipRequestProcessing {
_, err = s.Cron(config.MFLIntegratorConf.API.MFLRetryCronExpression).Do(RetryIncompleteRequests)
if err != nil {
log.WithError(err).Error("Error scheduling incomplete request retry task:")
}
}
s.StartAsync()
}()
go func() {
if !*config.SkipOUSync {
LoadOuLevels()
LoadOuGroups()
LoadAttributes()
LoadLocations() // Load organisation units - before facility in base DHIS2 instance
MatchLocationsWithMFL()
SyncLocationsToDHIS2Instances()
// fetch facilities after initial run, just use a scheduled job.
FetchFacilitiesByDistrict()
}
}()
jobs := make(chan int)
var wg sync.WaitGroup
seenMap := make(map[models.RequestID]bool)
mutex := &sync.Mutex{}
rWMutex := &sync.RWMutex{}
if !*config.SkipRequestProcessing {
// don't produce anything if skip processing is enabled
// Start the producer goroutine
wg.Add(1)
go Produce(dbConn, jobs, &wg, mutex, seenMap)
// Start the consumer goroutine
wg.Add(1)
go StartConsumers(jobs, &wg, rWMutex, seenMap)
}
// Start the backend API gin server
if !*config.DisableHTTPServer {
wg.Add(1)
go startAPIServer(&wg)
}
wg.Wait()
}
func startAPIServer(wg *sync.WaitGroup) {
defer wg.Done()
router := gin.Default()
v2 := router.Group("/api", BasicAuth())
{
v2.GET("/test2", func(c *gin.Context) {
c.String(200, "Authorized")
})
q := new(controllers.QueueController)
v2.POST("/queue", q.Queue)
v2.GET("/queue", q.Requests)
v2.GET("/queue/:id", q.GetRequest)
v2.DELETE("/queue/:id", q.DeleteRequest)
ou := new(controllers.OrgUnitController)
v2.POST("/organisationUnits", ou.OrgUnit)
v2.GET("/organisationUnits", ou.GetOrganisationUnits)
s := new(controllers.ServerController)
v2.POST("/servers", s.CreateServer)
v2.POST("/importServers", s.ImportServers)
ot := new(controllers.OrgUnitTreeController)
v2.GET("/outree/:server", ot.CreateOrgUnitTree)
at := new(controllers.AttributeController)
v2.GET("/syncAttributes/:server", at.SyncAttributes)
ad := new(controllers.AdminController)
v2.GET("/clearSyncLog/:district", ad.ClearSyncLog)
v2.GET("/clearDistrictRequests/:district", ad.ClearRequestsByDistrict)
v2.GET("/clearBatchRequests/:batch", ad.ClearRequestsByBatch)
}
// Handle error response when a route is not defined
router.NoRoute(func(c *gin.Context) {
c.String(404, "Page Not Found!")
})
_ = router.Run(":" + fmt.Sprintf("%s", config.MFLIntegratorConf.Server.Port))
}