forked from elastic/package-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
144 lines (116 loc) · 3.7 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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/elastic/package-registry/util"
ucfgYAML "github.com/elastic/go-ucfg/yaml"
"github.com/gorilla/mux"
)
const (
packageDir = "package"
)
var (
packagesBasePath string
address string
configPath = "config.yml"
defaultConfig = Config{
PublicDir: "config.yml",
CacheTimeSearch: 10 * time.Minute,
CacheTimeCategories: 10 * time.Minute,
CacheTimeCatchAll: 10 * time.Minute,
}
)
func init() {
flag.StringVar(&address, "address", "localhost:8080", "Address of the package-registry service.")
}
type Config struct {
PublicDir string `config:"public_dir"`
CacheTimeSearch time.Duration `config:"cache_time.search"`
CacheTimeCategories time.Duration `config:"cache_time.categories"`
CacheTimeCatchAll time.Duration `config:"cache_time.catch_all"`
}
func main() {
flag.Parse()
log.Println("Package registry started.")
defer log.Println("Package registry stopped.")
config, err := getConfig()
if err != nil {
log.Fatal(err)
}
log.Println("Cache time for /search: ", config.CacheTimeSearch)
log.Println("Cache time for /categories: ", config.CacheTimeCategories)
log.Println("Cache time for all others: ", config.CacheTimeCatchAll)
packagesBasePath := filepath.Join(config.PublicDir, packageDir)
packages, err := util.GetPackages(packagesBasePath)
if err != nil {
log.Fatal(err)
}
if len(packages) == 0 {
log.Fatal("No packages available")
}
log.Printf("%v package manifests loaded into memory.\n", len(packages))
server := &http.Server{Addr: address, Handler: getRouter(*config, packagesBasePath)}
go func() {
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatalf("Error occurred while serving: %s", err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
ctx := context.TODO()
if err := server.Shutdown(ctx); err != nil {
log.Fatal(err)
}
}
func getConfig() (*Config, error) {
cfg, err := ucfgYAML.NewConfigWithFile(configPath)
if err != nil {
return nil, err
}
config := defaultConfig
err = cfg.Unpack(&config)
if err != nil {
return nil, err
}
return &config, nil
}
func getRouter(config Config, packagesBasePath string) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/search", searchHandler(packagesBasePath, config.CacheTimeSearch))
router.HandleFunc("/categories", categoriesHandler(packagesBasePath, config.CacheTimeCategories))
router.HandleFunc("/health", healthHandler)
router.PathPrefix("/").HandlerFunc(catchAll(http.Dir(config.PublicDir), config.CacheTimeCatchAll))
router.Use(loggingMiddleware)
return router
}
// healthHandler is used for Docker/K8s deployments. It returns 200 if the service is live
// In addition ?ready=true can be used for a ready request. Currently both are identical.
func healthHandler(w http.ResponseWriter, r *http.Request) {}
// logging middle to log all requests
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logRequest(r)
next.ServeHTTP(w, r)
})
}
// logRequest converts a request object into a proper logging event
func logRequest(r *http.Request) {
// Do not log requests to the health endpoint
if r.RequestURI == "/health" {
return
}
log.Println(fmt.Sprintf("source.ip: %s, url.original: %s", r.RemoteAddr, r.RequestURI))
}