Welcome to mirror list, hosted at ThFree Co, Russian Federation.

map.go « disk « source « internal - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bae4b76410257ad0e764280b27c080115dd0f094 (plain)
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
package disk

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/karrick/godirwalk"
	log "github.com/sirupsen/logrus"

	"gitlab.com/gitlab-org/gitlab-pages/internal/domain"
	"gitlab.com/gitlab-org/gitlab-pages/metrics"
)

// Map maps domain names to Domain instances.
type Map map[string]*domain.Domain

type domainsUpdater func(Map)

func (dm Map) updateDomainMap(domainName string, domain *domain.Domain) {
	if _, ok := dm[domainName]; ok {
		log.WithFields(log.Fields{
			"domain_name": domainName,
		}).Error("Duplicate domain")
	}

	dm[domainName] = domain
}

func (dm Map) addDomain(rootDomain, groupName, projectName string, config *domainConfig) {
	newDomain := &domain.Domain{
		Name:            strings.ToLower(config.Domain),
		CertificateCert: config.Certificate,
		CertificateKey:  config.Key,
		Resolver: &customProjectResolver{
			config: config,
			path:   filepath.Join(groupName, projectName, "public"),
		},
	}

	dm.updateDomainMap(newDomain.Name, newDomain)
}

func (dm Map) updateGroupDomain(rootDomain, groupName, projectPath string, httpsOnly bool, accessControl bool, id uint64) {
	domainName := strings.ToLower(groupName + "." + rootDomain)
	groupDomain := dm[domainName]

	if groupDomain == nil {
		groupResolver := &Group{
			name:      groupName,
			projects:  make(projects),
			subgroups: make(subgroups),
		}

		groupDomain = &domain.Domain{
			Name:     domainName,
			Resolver: groupResolver,
		}
	}

	split := strings.SplitN(strings.ToLower(projectPath), "/", maxProjectDepth)
	projectName := split[len(split)-1]
	g := groupDomain.Resolver.(*Group)

	for i := 0; i < len(split)-1; i++ {
		subgroupName := split[i]
		subgroup := g.subgroups[subgroupName]
		if subgroup == nil {
			subgroup = &Group{
				name:      subgroupName,
				projects:  make(projects),
				subgroups: make(subgroups),
			}
			g.subgroups[subgroupName] = subgroup
		}

		g = subgroup
	}

	g.projects[projectName] = &projectConfig{
		NamespaceProject: domainName == projectName,
		HTTPSOnly:        httpsOnly,
		AccessControl:    accessControl,
		ID:               id,
	}

	dm[domainName] = groupDomain
}

func (dm Map) readProjectConfig(rootDomain string, group, projectName string, config *multiDomainConfig) {
	if config == nil {
		// This is necessary to preserve the previous behaviour where a
		// group domain is created even if no config.json files are
		// loaded successfully. Is it safe to remove this?
		dm.updateGroupDomain(rootDomain, group, projectName, false, false, 0)
		return
	}

	dm.updateGroupDomain(rootDomain, group, projectName, config.HTTPSOnly, config.AccessControl, config.ID)

	for _, domainConfig := range config.Domains {
		config := domainConfig // domainConfig is reused for each loop iteration
		if domainConfig.Valid(rootDomain) {
			dm.addDomain(rootDomain, group, projectName, &config)
		}
	}
}

func readProject(group, parent, projectName string, level int, fanIn chan<- jobResult) {
	if strings.HasPrefix(projectName, ".") {
		return
	}

	// Ignore projects that have .deleted in name
	if strings.HasSuffix(projectName, ".deleted") {
		return
	}

	projectPath := filepath.Join(parent, projectName)
	if _, err := os.Lstat(filepath.Join(group, projectPath, "public")); err != nil {
		// maybe it's a subgroup
		if level <= subgroupScanLimit {
			buf := make([]byte, 2*os.Getpagesize())
			readProjects(group, projectPath, level+1, buf, fanIn)
		}

		return
	}

	// We read the config.json file _before_ fanning in, because it does disk
	// IO and it does not need access to the domains map.
	config := &multiDomainConfig{}
	if err := config.Read(group, projectPath); err != nil {
		config = nil
	}

	fanIn <- jobResult{group: group, project: projectPath, config: config}
}

func readProjects(group, parent string, level int, buf []byte, fanIn chan<- jobResult) {
	subgroup := filepath.Join(group, parent)
	fis, err := godirwalk.ReadDirents(subgroup, buf)
	if err != nil {
		log.WithError(err).WithFields(log.Fields{
			"group":  group,
			"parent": parent,
		}).Print("readdir failed")
		return
	}

	for _, project := range fis {
		// Ignore non directories
		if !project.IsDir() {
			continue
		}

		readProject(group, parent, project.Name(), level, fanIn)
	}
}

type jobResult struct {
	group   string
	project string
	config  *multiDomainConfig
}

// ReadGroups walks the pages directory and populates dm with all the domains it finds.
func (dm Map) ReadGroups(rootDomain string, fis godirwalk.Dirents) {
	fanOutGroups := make(chan string)
	fanIn := make(chan jobResult)
	wg := &sync.WaitGroup{}
	for i := 0; i < 4; i++ {
		wg.Add(1)

		go func() {
			buf := make([]byte, 2*os.Getpagesize())

			for group := range fanOutGroups {
				started := time.Now()

				readProjects(group, "", 0, buf, fanIn)

				log.WithFields(log.Fields{
					"group":    group,
					"duration": time.Since(started).Seconds(),
				}).Debug("Loaded projects for group")
			}

			wg.Done()
		}()
	}

	go func() {
		wg.Wait()
		close(fanIn)
	}()

	done := make(chan struct{})
	go func() {
		for result := range fanIn {
			dm.readProjectConfig(rootDomain, result.group, result.project, result.config)
		}

		close(done)
	}()

	for _, group := range fis {
		if !group.IsDir() {
			continue
		}
		if strings.HasPrefix(group.Name(), ".") {
			continue
		}
		fanOutGroups <- group.Name()
	}
	close(fanOutGroups)

	<-done
}

const (
	updateFile = ".update"
)

// Watch polls the filesystem and kicks off a new domain directory scan when needed.
func Watch(rootDomain string, updater domainsUpdater, interval time.Duration) {
	lastUpdate := []byte("no-update")

	for {
		// Read the update file
		update, err := ioutil.ReadFile(updateFile)
		if err != nil && !os.IsNotExist(err) {
			log.WithError(err).Print("failed to read update timestamp")
			time.Sleep(interval)
			continue
		}

		// If it's the same ignore
		if bytes.Equal(lastUpdate, update) {
			time.Sleep(interval)
			continue
		}
		lastUpdate = update

		started := time.Now()
		dm := make(Map)

		fis, err := godirwalk.ReadDirents(".", nil)
		if err != nil {
			log.WithError(err).Warn("domain scan failed")
			metrics.FailedDomainUpdates.Inc()
			continue
		}

		dm.ReadGroups(rootDomain, fis)
		duration := time.Since(started).Seconds()

		var hash string
		if len(update) < 1 {
			hash = "<empty>"
		} else {
			hash = strings.TrimSpace(string(update))
		}

		logConfiguredDomains(dm)

		log.WithFields(log.Fields{
			"count(domains)": len(dm),
			"duration":       duration,
			"hash":           hash,
		}).Info("Updated all domains")

		if updater != nil {
			updater(dm)
		}

		// Update prometheus metrics
		metrics.DomainLastUpdateTime.Set(float64(time.Now().UTC().Unix()))
		metrics.DomainsServed.Set(float64(len(dm)))
		metrics.DomainsConfigurationUpdateDuration.Set(duration)
		metrics.DomainUpdates.Inc()

		time.Sleep(interval)
	}
}

func logConfiguredDomains(dm Map) {
	if log.GetLevel() != log.DebugLevel {
		return
	}

	for h, d := range dm {
		log.WithFields(log.Fields{
			"domain": d,
			"host":   h,
		}).Debug("Configured domain")
	}
}