-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathserve.go
More file actions
208 lines (181 loc) · 5.71 KB
/
Copy pathserve.go
File metadata and controls
208 lines (181 loc) · 5.71 KB
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
package serve
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
"charm.land/log/v2"
"github.com/charmbracelet/soft-serve/cmd"
"github.com/charmbracelet/soft-serve/pkg/access"
"github.com/charmbracelet/soft-serve/pkg/backend"
"github.com/charmbracelet/soft-serve/pkg/config"
"github.com/charmbracelet/soft-serve/pkg/db"
"github.com/charmbracelet/soft-serve/pkg/db/migrate"
"github.com/spf13/cobra"
)
var (
syncHooks bool
// Command is the serve command.
Command = &cobra.Command{
Use: "serve",
Short: "Start the server",
Args: cobra.NoArgs,
PersistentPreRunE: cmd.InitBackendContext,
PersistentPostRunE: cmd.CloseDBContext,
RunE: func(c *cobra.Command, _ []string) error {
ctx := c.Context()
cfg := config.DefaultConfig()
if cfg.Exist() {
if err := cfg.ParseFile(); err != nil {
return fmt.Errorf("parse config file: %w", err)
}
} else {
if err := cfg.WriteConfig(); err != nil {
return fmt.Errorf("write config file: %w", err)
}
}
if err := cfg.ParseEnv(); err != nil {
return fmt.Errorf("parse environment variables: %w", err)
}
// Create custom hooks directory if it doesn't exist
customHooksPath := filepath.Join(cfg.DataPath, "hooks")
if _, err := os.Stat(customHooksPath); err != nil && os.IsNotExist(err) {
os.MkdirAll(customHooksPath, os.ModePerm) //nolint: errcheck
// Generate update hook example without executable permissions
hookPath := filepath.Join(customHooksPath, "update.sample")
//nolint: gosec
if err := os.WriteFile(hookPath, []byte(updateHookExample), 0o644); err != nil {
return fmt.Errorf("failed to generate update hook example: %w", err)
}
}
// Create log directory if it doesn't exist
logPath := filepath.Join(cfg.DataPath, "log")
if _, err := os.Stat(logPath); err != nil && os.IsNotExist(err) {
os.MkdirAll(logPath, os.ModePerm) //nolint: errcheck
}
db := db.FromContext(ctx)
if err := migrate.Migrate(ctx, db); err != nil {
return fmt.Errorf("migration error: %w", err)
}
// Apply config-driven settings so operators can automate
// server setup without a post-start SSH session.
{
cfgCtx := config.FromContext(ctx)
be := backend.FromContext(ctx)
logger := log.FromContext(ctx).WithPrefix("server")
if cfgCtx.AnonAccess != "" {
if err := be.SetAnonAccess(ctx, access.ParseAccessLevel(cfgCtx.AnonAccess)); err != nil {
return fmt.Errorf("set anon_access: %w", err)
}
logger.Debug("applied anon_access from config", "level", cfgCtx.AnonAccess)
}
if cfgCtx.AllowKeyless != nil {
if err := be.SetAllowKeyless(ctx, *cfgCtx.AllowKeyless); err != nil {
return fmt.Errorf("set allow_keyless: %w", err)
}
logger.Debug("applied allow_keyless from config", "value", *cfgCtx.AllowKeyless)
}
}
s, err := NewServer(ctx)
if err != nil {
return fmt.Errorf("start server: %w", err)
}
if syncHooks {
be := backend.FromContext(ctx)
if err := cmd.InitializeHooks(ctx, cfg, be); err != nil {
return fmt.Errorf("initialize hooks: %w", err)
}
}
lch := make(chan error, 1)
done := make(chan os.Signal, 1)
doneOnce := sync.OnceFunc(func() { close(done) })
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
// This endpoint is added for testing purposes
// It allows us to stop the server from the test suite.
// This is needed since Windows doesn't support signals.
if testRun, _ := strconv.ParseBool(os.Getenv("SOFT_SERVE_TESTRUN")); testRun {
h := s.HTTPServer.Server.Handler
s.HTTPServer.Server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/__stop" && r.Method == http.MethodHead {
doneOnce()
return
}
h.ServeHTTP(w, r)
})
}
go func() {
lch <- s.Start()
doneOnce()
}()
for {
select {
case err := <-lch:
if err != nil {
return fmt.Errorf("server error: %w", err)
}
case sig := <-done:
if sig == syscall.SIGHUP {
s.logger.Info("received SIGHUP signal, reloading TLS certificates if enabled")
if err := s.ReloadCertificates(); err != nil {
s.logger.Error("failed to reload TLS certificates", "err", err)
}
continue
}
}
break
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
return err
}
return nil
},
}
)
func init() {
Command.Flags().BoolVarP(&syncHooks, "sync-hooks", "", false, "synchronize hooks for all repositories before running the server")
}
const updateHookExample = `#!/bin/sh
#
# An example hook script to echo information about the push
# and send it to the client.
#
# To enable this hook, rename this file to "update" and make it executable.
refname="$1"
oldrev="$2"
newrev="$3"
# Safety check
if [ -z "$GIT_DIR" ]; then
echo "Don't run this script from the command line." >&2
echo " (if you want, you could supply GIT_DIR then run" >&2
echo " $0 <ref> <oldrev> <newrev>)" >&2
exit 1
fi
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
echo "usage: $0 <ref> <oldrev> <newrev>" >&2
exit 1
fi
# Check types
# if $newrev is 0000...0000, it's a commit to delete a ref.
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
if [ "$newrev" = "$zero" ]; then
newrev_type=delete
else
newrev_type=$(git cat-file -t $newrev)
fi
echo "Hi from Soft Serve update hook!"
echo
echo "Repository: $SOFT_SERVE_REPO_NAME"
echo "RefName: $refname"
echo "Change Type: $newrev_type"
echo "Old SHA1: $oldrev"
echo "New SHA1: $newrev"
exit 0
`