/
daemon.go
2164 lines (1793 loc) · 62.9 KB
/
daemon.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
package main
import (
"bytes"
"context"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"sync"
"time"
dqliteClient "github.com/canonical/go-dqlite/client"
"github.com/canonical/go-dqlite/driver"
"github.com/go-macaroon-bakery/macaroon-bakery/v3/bakery"
"github.com/gorilla/mux"
liblxc "github.com/lxc/go-lxc"
"golang.org/x/sys/unix"
"github.com/lxc/lxd/lxd/acme"
"github.com/lxc/lxd/lxd/apparmor"
"github.com/lxc/lxd/lxd/auth/candid"
"github.com/lxc/lxd/lxd/auth/oidc"
"github.com/lxc/lxd/lxd/bgp"
"github.com/lxc/lxd/lxd/cluster"
clusterConfig "github.com/lxc/lxd/lxd/cluster/config"
"github.com/lxc/lxd/lxd/daemon"
"github.com/lxc/lxd/lxd/db"
dbCluster "github.com/lxc/lxd/lxd/db/cluster"
"github.com/lxc/lxd/lxd/db/warningtype"
"github.com/lxc/lxd/lxd/dns"
"github.com/lxc/lxd/lxd/endpoints"
"github.com/lxc/lxd/lxd/events"
"github.com/lxc/lxd/lxd/firewall"
"github.com/lxc/lxd/lxd/fsmonitor"
"github.com/lxc/lxd/lxd/instance"
instanceDrivers "github.com/lxc/lxd/lxd/instance/drivers"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/loki"
"github.com/lxc/lxd/lxd/maas"
networkZone "github.com/lxc/lxd/lxd/network/zone"
"github.com/lxc/lxd/lxd/node"
"github.com/lxc/lxd/lxd/rbac"
"github.com/lxc/lxd/lxd/request"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/lxd/rsync"
scriptletLoad "github.com/lxc/lxd/lxd/scriptlet/load"
"github.com/lxc/lxd/lxd/seccomp"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
"github.com/lxc/lxd/lxd/storage/filesystem"
"github.com/lxc/lxd/lxd/storage/s3/miniod"
"github.com/lxc/lxd/lxd/sys"
"github.com/lxc/lxd/lxd/task"
"github.com/lxc/lxd/lxd/ucred"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/lxd/warnings"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/cancel"
"github.com/lxc/lxd/shared/idmap"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/version"
)
// A Daemon can respond to requests from a shared client.
type Daemon struct {
clientCerts *certificateCache
os *sys.OS
db *db.DB
firewall firewall.Firewall
maas *maas.Controller
bgp *bgp.Server
dns *dns.Server
rbac *rbac.Server
// Event servers
devlxdEvents *events.DevLXDServer
events *events.Server
internalListener *events.InternalListener
// Tasks registry for long-running background tasks
// Keep clustering tasks separate as they cause a lot of CPU wakeups
tasks task.Group
clusterTasks task.Group
// Indexes of tasks that need to be reset when their execution interval changes
taskPruneImages *task.Task
taskClusterHeartbeat *task.Task
// Stores startup time of daemon
startTime time.Time
// Whether daemon was started by systemd socket activation.
systemdSocketActivated bool
config *DaemonConfig
endpoints *endpoints.Endpoints
gateway *cluster.Gateway
seccomp *seccomp.Server
proxy func(req *http.Request) (*url.URL, error)
candidVerifier *candid.Verifier
oidcVerifier *oidc.Verifier
// Stores last heartbeat node information to detect node changes.
lastNodeList *cluster.APIHeartbeat
// Serialize changes to cluster membership (joins, leaves, role
// changes).
clusterMembershipMutex sync.RWMutex
serverCert func() *shared.CertInfo
serverCertInt *shared.CertInfo // Do not use this directly, use servertCert func.
// Status control.
setupChan chan struct{} // Closed when basic Daemon setup is completed
waitReady *cancel.Canceller // Cancelled when LXD is fully ready
shutdownCtx context.Context // Cancelled when shutdown starts.
shutdownCancel context.CancelFunc // Cancels the shutdownCtx to indicate shutdown starting.
shutdownDoneCh chan error // Receives the result of the d.Stop() function and tells LXD to end.
// Device monitor for watching filesystem events
devmonitor fsmonitor.FSMonitor
// Keep track of skews.
timeSkew bool
// Configuration.
globalConfig *clusterConfig.Config
localConfig *node.Config
globalConfigMu sync.Mutex
// Cluster.
serverName string
lokiClient *loki.Client
// HTTP-01 challenge provider for ACME
http01Provider acme.HTTP01Provider
}
// DaemonConfig holds configuration values for Daemon.
type DaemonConfig struct {
Group string // Group name the local unix socket should be chown'ed to
Trace []string // List of sub-systems to trace
RaftLatency float64 // Coarse grain measure of the cluster latency
DqliteSetupTimeout time.Duration // How long to wait for the cluster database to be up
}
// newDaemon returns a new Daemon object with the given configuration.
func newDaemon(config *DaemonConfig, os *sys.OS) *Daemon {
lxdEvents := events.NewServer(daemon.Debug, daemon.Verbose, cluster.EventHubPush)
devlxdEvents := events.NewDevLXDServer(daemon.Debug, daemon.Verbose)
shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
d := &Daemon{
clientCerts: &certificateCache{},
config: config,
devlxdEvents: devlxdEvents,
events: lxdEvents,
db: &db.DB{},
http01Provider: acme.NewHTTP01Provider(),
os: os,
setupChan: make(chan struct{}),
waitReady: cancel.New(context.Background()),
shutdownCtx: shutdownCtx,
shutdownCancel: shutdownCancel,
shutdownDoneCh: make(chan error),
}
d.serverCert = func() *shared.CertInfo { return d.serverCertInt }
return d
}
// defaultDaemonConfig returns a DaemonConfig object with default values.
func defaultDaemonConfig() *DaemonConfig {
return &DaemonConfig{
RaftLatency: 3.0,
DqliteSetupTimeout: 36 * time.Hour, // Account for snap refresh lag
}
}
// defaultDaemon returns a new, un-initialized Daemon object with default values.
func defaultDaemon() *Daemon {
config := defaultDaemonConfig()
os := sys.DefaultOS()
return newDaemon(config, os)
}
// APIEndpoint represents a URL in our API.
type APIEndpoint struct {
Name string // Name for this endpoint.
Path string // Path pattern for this endpoint.
Aliases []APIEndpointAlias // Any aliases for this endpoint.
Get APIEndpointAction
Head APIEndpointAction
Put APIEndpointAction
Post APIEndpointAction
Delete APIEndpointAction
Patch APIEndpointAction
}
// APIEndpointAlias represents an alias URL of and APIEndpoint in our API.
type APIEndpointAlias struct {
Name string // Name for this alias.
Path string // Path pattern for this alias.
}
// APIEndpointAction represents an action on an API endpoint.
type APIEndpointAction struct {
Handler func(d *Daemon, r *http.Request) response.Response
AccessHandler func(d *Daemon, r *http.Request) response.Response
AllowUntrusted bool
}
// allowAuthenticated is an AccessHandler which allows all requests.
// This function doesn't do anything itself, except return the EmptySyncResponse that allows the request to
// proceed. However in order to access any API route you must be authenticated, unless the handler's AllowUntrusted
// property is set to true or you are an admin.
func allowAuthenticated(d *Daemon, r *http.Request) response.Response {
return response.EmptySyncResponse
}
// allowProjectPermission is a wrapper to check access against the project, its features and RBAC permission.
func allowProjectPermission(feature string, permission string) func(d *Daemon, r *http.Request) response.Response {
return func(d *Daemon, r *http.Request) response.Response {
// Shortcut for speed
if rbac.UserIsAdmin(r) {
return response.EmptySyncResponse
}
// Get the project
projectName := projectParam(r)
// Validate whether the user has the needed permission
if !rbac.UserHasPermission(r, projectName, permission) {
return response.Forbidden(nil)
}
return response.EmptySyncResponse
}
}
// Convenience function around Authenticate.
func (d *Daemon) checkTrustedClient(r *http.Request) error {
trusted, _, _, err := d.Authenticate(nil, r)
if !trusted || err != nil {
if err != nil {
return err
}
return fmt.Errorf("Not authorized")
}
return nil
}
// getTrustedCertificates returns trusted certificates key on DB type and fingerprint.
func (d *Daemon) getTrustedCertificates() map[dbCluster.CertificateType]map[string]x509.Certificate {
d.clientCerts.Lock.Lock()
defer d.clientCerts.Lock.Unlock()
return d.clientCerts.Certificates
}
// Authenticate validates an incoming http Request
// It will check over what protocol it came, what type of request it is and
// will validate the TLS certificate or Macaroon.
//
// This does not perform authorization, only validates authentication.
// Returns whether trusted or not, the username (or certificate fingerprint) of the trusted client, and the type of
// client that has been authenticated (cluster, unix, candid or tls).
func (d *Daemon) Authenticate(w http.ResponseWriter, r *http.Request) (bool, string, string, error) {
trustedCerts := d.getTrustedCertificates()
// Allow internal cluster traffic by checking against the trusted certfificates.
if r.TLS != nil {
for _, i := range r.TLS.PeerCertificates {
trusted, fingerprint := util.CheckTrustState(*i, trustedCerts[dbCluster.CertificateTypeServer], d.endpoints.NetworkCert(), false)
if trusted {
return true, fingerprint, "cluster", nil
}
}
}
// Local unix socket queries.
if r.RemoteAddr == "@" && r.TLS == nil {
if w != nil {
cred, err := ucred.GetCredFromContext(r.Context())
if err != nil {
return false, "", "", err
}
u, err := user.LookupId(fmt.Sprintf("%d", cred.Uid))
if err != nil {
return true, fmt.Sprintf("uid=%d", cred.Uid), "unix", nil
}
return true, u.Username, "unix", nil
}
return true, "", "unix", nil
}
// Devlxd unix socket credentials on main API.
if r.RemoteAddr == "@devlxd" {
return false, "", "", fmt.Errorf("Main API query can't come from /dev/lxd socket")
}
// Cluster notification with wrong certificate.
if isClusterNotification(r) {
return false, "", "", fmt.Errorf("Cluster notification isn't using trusted server certificate")
}
// Bad query, no TLS found.
if r.TLS == nil {
return false, "", "", fmt.Errorf("Bad/missing TLS on network query")
}
if d.oidcVerifier != nil && d.oidcVerifier.IsRequest(r) {
userName, err := d.oidcVerifier.Auth(d.shutdownCtx, w, r)
if err != nil {
return false, "", "", err
}
return true, userName, "oidc", nil
} else if d.candidVerifier != nil && d.candidVerifier.IsRequest(r) {
info, err := d.candidVerifier.Auth(r)
if err != nil {
return false, "", "", err
}
if info != nil && info.Identity != nil {
// Valid identity macaroon found.
return true, info.Identity.Id(), "candid", nil
}
// Valid macaroon with no identity information.
return true, "", "candid", nil
}
// Validate normal TLS access.
trustCACertificates := d.globalConfig.TrustCACertificates()
// Validate metrics certificates.
if r.URL.Path == "/1.0/metrics" {
for _, i := range r.TLS.PeerCertificates {
trusted, username := util.CheckTrustState(*i, trustedCerts[dbCluster.CertificateTypeMetrics], d.endpoints.NetworkCert(), trustCACertificates)
if trusted {
return true, username, "tls", nil
}
}
}
for _, i := range r.TLS.PeerCertificates {
trusted, username := util.CheckTrustState(*i, trustedCerts[dbCluster.CertificateTypeClient], d.endpoints.NetworkCert(), trustCACertificates)
if trusted {
return true, username, "tls", nil
}
}
// Reject unauthorized.
return false, "", "", nil
}
// State creates a new State instance linked to our internal db and os.
func (d *Daemon) State() *state.State {
// If the daemon is shutting down, the context will be cancelled.
// This information will be available throughout the code, and can be used to prevent new
// operations from starting during shutdown.
// Build a list of instance types.
drivers := instanceDrivers.DriverStatuses()
instanceTypes := make(map[instancetype.Type]error, len(drivers))
for driverType, driver := range drivers {
instanceTypes[driverType] = driver.Info.Error
}
d.globalConfigMu.Lock()
globalConfig := d.globalConfig
localConfig := d.localConfig
d.globalConfigMu.Unlock()
return &state.State{
ShutdownCtx: d.shutdownCtx,
DB: d.db,
MAAS: d.maas,
BGP: d.bgp,
DNS: d.dns,
OS: d.os,
Endpoints: d.endpoints,
Events: d.events,
DevlxdEvents: d.devlxdEvents,
Firewall: d.firewall,
Proxy: d.proxy,
ServerCert: d.serverCert,
UpdateCertificateCache: func() { updateCertificateCache(d) },
InstanceTypes: instanceTypes,
DevMonitor: d.devmonitor,
GlobalConfig: globalConfig,
LocalConfig: localConfig,
ServerName: d.serverName,
StartTime: d.startTime,
}
}
// UnixSocket returns the full path to the unix.socket file that this daemon is
// listening on. Used by tests.
func (d *Daemon) UnixSocket() string {
path := os.Getenv("LXD_SOCKET")
if path != "" {
return path
}
return filepath.Join(d.os.VarDir, "unix.socket")
}
func (d *Daemon) createCmd(restAPI *mux.Router, version string, c APIEndpoint) {
var uri string
if c.Path == "" {
uri = fmt.Sprintf("/%s", version)
} else if version != "" {
uri = fmt.Sprintf("/%s/%s", version, c.Path)
} else {
uri = fmt.Sprintf("/%s", c.Path)
}
route := restAPI.HandleFunc(uri, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if !(r.RemoteAddr == "@" && version == "internal") {
// Block public API requests until we're done with basic
// initialization tasks, such setting up the cluster database.
select {
case <-d.setupChan:
default:
response := response.Unavailable(fmt.Errorf("LXD daemon setup in progress"))
_ = response.Render(w)
return
}
}
// Authentication
trusted, username, protocol, err := d.Authenticate(w, r)
if err != nil {
_, ok := err.(*oidc.AuthError)
if ok {
// Ensure the OIDC headers are set if needed.
if d.oidcVerifier != nil {
_ = d.oidcVerifier.WriteHeaders(w)
}
_ = response.Unauthorized(err).Render(w)
return
}
// If not a macaroon discharge request, return the error
_, ok = err.(*bakery.DischargeRequiredError)
if !ok {
_ = response.InternalError(err).Render(w)
return
}
}
// Reject internal queries to remote, non-cluster, clients
if version == "internal" && !shared.StringInSlice(protocol, []string{"unix", "cluster"}) {
// Except for the initial cluster accept request (done over trusted TLS)
if !trusted || c.Path != "cluster/accept" || protocol != "tls" {
logger.Warn("Rejecting remote internal API request", logger.Ctx{"ip": r.RemoteAddr})
_ = response.Forbidden(nil).Render(w)
return
}
}
logCtx := logger.Ctx{"method": r.Method, "url": r.URL.RequestURI(), "ip": r.RemoteAddr, "protocol": protocol}
if protocol == "cluster" {
logCtx["fingerprint"] = username
} else {
logCtx["username"] = username
}
untrustedOk := (r.Method == "GET" && c.Get.AllowUntrusted) || (r.Method == "POST" && c.Post.AllowUntrusted)
if trusted {
logger.Debug("Handling API request", logCtx)
// Get user access data.
userAccess, err := func() (*rbac.UserAccess, error) {
ua := &rbac.UserAccess{}
ua.Admin = true
// Internal cluster communications.
if protocol == "cluster" {
return ua, nil
}
// Regular TLS clients.
if protocol == "tls" {
d.clientCerts.Lock.Lock()
certProjects := d.clientCerts.Projects
d.clientCerts.Lock.Unlock()
// Check if we have restrictions on the key.
if certProjects != nil {
projects, ok := certProjects[username]
if ok {
ua.Admin = false
ua.Projects = map[string][]string{}
for _, projectName := range projects {
ua.Projects[projectName] = []string{
"view",
"manage-containers",
"manage-images",
"manage-networks",
"manage-profiles",
"manage-storage-volumes",
"operate-containers",
}
}
}
}
return ua, nil
}
// If no external authentication configured, we're done now.
if d.candidVerifier == nil || d.rbac == nil || r.RemoteAddr == "@" {
return ua, nil
}
// Validate RBAC permissions.
ua, err = d.rbac.UserAccess(username)
if err != nil {
return nil, err
}
return ua, nil
}()
if err != nil {
logCtx["err"] = err
logger.Warn("Rejecting remote API request", logCtx)
_ = response.Forbidden(nil).Render(w)
return
}
// Add authentication/authorization context data.
ctx := context.WithValue(r.Context(), request.CtxUsername, username)
ctx = context.WithValue(ctx, request.CtxProtocol, protocol)
ctx = context.WithValue(ctx, request.CtxAccess, userAccess)
// Add forwarded requestor data.
if protocol == "cluster" {
// Add authentication/authorization context data.
ctx = context.WithValue(ctx, request.CtxForwardedAddress, r.Header.Get(request.HeaderForwardedAddress))
ctx = context.WithValue(ctx, request.CtxForwardedUsername, r.Header.Get(request.HeaderForwardedUsername))
ctx = context.WithValue(ctx, request.CtxForwardedProtocol, r.Header.Get(request.HeaderForwardedProtocol))
}
r = r.WithContext(ctx)
} else if untrustedOk && r.Header.Get("X-LXD-authenticated") == "" {
logger.Debug(fmt.Sprintf("Allowing untrusted %s", r.Method), logger.Ctx{"url": r.URL.RequestURI(), "ip": r.RemoteAddr})
} else if derr, ok := err.(*bakery.DischargeRequiredError); ok {
d.candidVerifier.WriteRequest(r, w, derr)
return
} else {
if d.oidcVerifier != nil {
_ = d.oidcVerifier.WriteHeaders(w)
}
logger.Warn("Rejecting request from untrusted client", logger.Ctx{"ip": r.RemoteAddr})
_ = response.Forbidden(nil).Render(w)
return
}
// Dump full request JSON when in debug mode
if daemon.Debug && r.Method != "GET" && util.IsJSONRequest(r) {
newBody := &bytes.Buffer{}
captured := &bytes.Buffer{}
multiW := io.MultiWriter(newBody, captured)
_, err := io.Copy(multiW, r.Body)
if err != nil {
_ = response.InternalError(err).Render(w)
return
}
r.Body = shared.BytesReadCloser{Buf: newBody}
util.DebugJSON("API Request", captured, logger.AddContext(logCtx))
}
// Actually process the request
var resp response.Response
// Return Unavailable Error (503) if daemon is shutting down.
// There are some exceptions:
// - internal calls, e.g. lxd shutdown
// - events endpoint as this is accessed when running `lxd shutdown`
// - /1.0 endpoint
// - /1.0/operations endpoints
// - GET queries
allowedDuringShutdown := func() bool {
if version == "internal" {
return true
}
if c.Path == "" || c.Path == "events" || c.Path == "operations" || strings.HasPrefix(c.Path, "operations/") {
return true
}
if r.Method == "GET" {
return true
}
return false
}
if d.shutdownCtx.Err() == context.Canceled && !allowedDuringShutdown() {
_ = response.Unavailable(fmt.Errorf("LXD is shutting down")).Render(w)
return
}
handleRequest := func(action APIEndpointAction) response.Response {
if action.Handler == nil {
return response.NotImplemented(nil)
}
if action.AccessHandler != nil {
// Defer access control to custom handler
resp := action.AccessHandler(d, r)
if resp != response.EmptySyncResponse {
return resp
}
} else if !action.AllowUntrusted {
// Require admin privileges
if !rbac.UserIsAdmin(r) {
return response.Forbidden(nil)
}
}
return action.Handler(d, r)
}
switch r.Method {
case "GET":
resp = handleRequest(c.Get)
case "HEAD":
resp = handleRequest(c.Head)
case "PUT":
resp = handleRequest(c.Put)
case "POST":
resp = handleRequest(c.Post)
case "DELETE":
resp = handleRequest(c.Delete)
case "PATCH":
resp = handleRequest(c.Patch)
default:
resp = response.NotFound(fmt.Errorf("Method %q not found", r.Method))
}
// Handle errors
err = resp.Render(w)
if err != nil {
writeErr := response.SmartError(err).Render(w)
if writeErr != nil {
logger.Error("Failed writing error for HTTP response", logger.Ctx{"url": uri, "err": err, "writeErr": writeErr})
}
}
})
// If the endpoint has a canonical name then record it so it can be used to build URLS
// and accessed in the context of the request by the handler function.
if c.Name != "" {
route.Name(c.Name)
}
}
// have we setup shared mounts?
var sharedMountsLock sync.Mutex
// setupSharedMounts will mount any shared mounts needed, and set daemon.SharedMountsSetup to true.
func setupSharedMounts() error {
// Check if we already went through this
if daemon.SharedMountsSetup {
return nil
}
// Get a lock to prevent races
sharedMountsLock.Lock()
defer sharedMountsLock.Unlock()
// Check if already setup
path := shared.VarPath("shmounts")
if filesystem.IsMountPoint(path) {
daemon.SharedMountsSetup = true
return nil
}
// Mount a new tmpfs
err := unix.Mount("tmpfs", path, "tmpfs", 0, "size=100k,mode=0711")
if err != nil {
return err
}
// Mark as MS_SHARED and MS_REC
var flags uintptr = unix.MS_SHARED | unix.MS_REC
err = unix.Mount(path, path, "none", flags, "")
if err != nil {
return err
}
daemon.SharedMountsSetup = true
return nil
}
// Init starts daemon process.
func (d *Daemon) Init() error {
d.startTime = time.Now()
err := d.init()
// If an error occurred synchronously while starting up, let's try to
// cleanup any state we produced so far. Errors happening here will be
// ignored.
if err != nil {
logger.Error("Failed to start the daemon", logger.Ctx{"err": err})
_ = d.Stop(context.Background(), unix.SIGINT)
return err
}
return nil
}
func (d *Daemon) setupLoki(URL string, cert string, key string, caCert string, labels []string, logLevel string, types []string) error {
if d.lokiClient != nil {
d.lokiClient.Stop()
}
if URL == "" || logLevel == "" || len(types) == 0 {
return nil
}
u, err := url.Parse(URL)
if err != nil {
return err
}
d.lokiClient = loki.NewClient(d.shutdownCtx, u, cert, key, caCert, labels, logLevel, types)
d.internalListener.AddHandler("loki", d.lokiClient.HandleEvent)
return nil
}
func (d *Daemon) init() error {
var dbWarnings []dbCluster.Warning
// Setup logger
events.LoggingServer = d.events
// Setup internal event listener
d.internalListener = events.NewInternalListener(d.shutdownCtx, d.events)
// Lets check if there's an existing LXD running
err := endpoints.CheckAlreadyRunning(d.UnixSocket())
if err != nil {
return err
}
/* Set the LVM environment */
err = os.Setenv("LVM_SUPPRESS_FD_WARNINGS", "1")
if err != nil {
return err
}
/* Print welcome message */
mode := "normal"
if d.os.MockMode {
mode = "mock"
}
logger.Info("LXD is starting", logger.Ctx{"version": version.Version, "mode": mode, "path": shared.VarPath("")})
/* List of sub-systems to trace */
trace := d.config.Trace
/* Initialize the operating system facade */
dbWarnings, err = d.os.Init()
if err != nil {
return err
}
// Setup AppArmor wrapper.
rsync.RunWrapper = func(cmd *exec.Cmd, source string, destination string) (func(), error) {
return apparmor.RsyncWrapper(d.os, cmd, source, destination)
}
// Bump some kernel limits to avoid issues
for _, limit := range []int{unix.RLIMIT_NOFILE} {
rLimit := unix.Rlimit{}
err := unix.Getrlimit(limit, &rLimit)
if err != nil {
return err
}
rLimit.Cur = rLimit.Max
err = unix.Setrlimit(limit, &rLimit)
if err != nil {
return err
}
}
// Detect LXC features
d.os.LXCFeatures = map[string]bool{}
lxcExtensions := []string{
"mount_injection_file",
"seccomp_notify",
"network_ipvlan",
"network_l2proxy",
"network_gateway_device_route",
"network_phys_macvlan_mtu",
"network_veth_router",
"cgroup2",
"pidfd",
"seccomp_allow_deny_syntax",
"devpts_fd",
"seccomp_proxy_send_notify_fd",
"idmapped_mounts_v2",
"core_scheduling",
}
for _, extension := range lxcExtensions {
d.os.LXCFeatures[extension] = liblxc.HasAPIExtension(extension)
}
// Look for kernel features
logger.Infof("Kernel features:")
d.os.CloseRange = canUseCloseRange()
if d.os.CloseRange {
logger.Info(" - closing multiple file descriptors efficiently: yes")
} else {
logger.Info(" - closing multiple file descriptors efficiently: no")
}
d.os.NetnsGetifaddrs = canUseNetnsGetifaddrs()
if d.os.NetnsGetifaddrs {
logger.Info(" - netnsid-based network retrieval: yes")
} else {
logger.Info(" - netnsid-based network retrieval: no")
}
if canUsePidFds() && d.os.LXCFeatures["pidfd"] {
d.os.PidFds = true
}
if d.os.PidFds {
logger.Info(" - pidfds: yes")
} else {
logger.Info(" - pidfds: no")
}
if canUseCoreScheduling() {
d.os.CoreScheduling = true
logger.Info(" - core scheduling: yes")
if d.os.LXCFeatures["core_scheduling"] {
d.os.ContainerCoreScheduling = true
}
} else {
logger.Info(" - core scheduling: no")
}
d.os.UeventInjection = canUseUeventInjection()
if d.os.UeventInjection {
logger.Info(" - uevent injection: yes")
} else {
logger.Info(" - uevent injection: no")
}
d.os.SeccompListener = canUseSeccompListener()
if d.os.SeccompListener {
logger.Info(" - seccomp listener: yes")
} else {
logger.Info(" - seccomp listener: no")
}
d.os.SeccompListenerContinue = canUseSeccompListenerContinue()
if d.os.SeccompListenerContinue {
logger.Info(" - seccomp listener continue syscalls: yes")
} else {
logger.Info(" - seccomp listener continue syscalls: no")
}
if canUseSeccompListenerAddfd() && d.os.LXCFeatures["seccomp_proxy_send_notify_fd"] {
d.os.SeccompListenerAddfd = true
logger.Info(" - seccomp listener add file descriptors: yes")
} else {
logger.Info(" - seccomp listener add file descriptors: no")
}
d.os.PidFdSetns = canUsePidFdSetns()
if d.os.PidFdSetns {
logger.Info(" - attach to namespaces via pidfds: yes")
} else {
logger.Info(" - attach to namespaces via pidfds: no")
}
if d.os.LXCFeatures["devpts_fd"] && canUseNativeTerminals() {
d.os.NativeTerminals = true
logger.Info(" - safe native terminal allocation : yes")
} else {
logger.Info(" - safe native terminal allocation : no")
}
/*
* During daemon startup we're the only thread that touches VFS3Fscaps
* so we don't need to bother with atomic.StoreInt32() when touching
* VFS3Fscaps.
*/
d.os.VFS3Fscaps = idmap.SupportsVFS3Fscaps("")
if d.os.VFS3Fscaps {
idmap.VFS3Fscaps = idmap.VFS3FscapsSupported
logger.Infof(" - unprivileged file capabilities: yes")
} else {
idmap.VFS3Fscaps = idmap.VFS3FscapsUnsupported
logger.Infof(" - unprivileged file capabilities: no")
}
dbWarnings = append(dbWarnings, d.os.CGInfo.Warnings()...)
logger.Infof(" - cgroup layout: %s", d.os.CGInfo.Mode())
for _, w := range dbWarnings {
logger.Warnf(" - %s, %s", warningtype.TypeNames[warningtype.Type(w.TypeCode)], w.LastMessage)
}
// Detect shiftfs support.
if shared.IsTrue(os.Getenv("LXD_SHIFTFS_DISABLE")) {
logger.Info(" - shiftfs support: disabled")
} else {
if canUseShiftfs() && (util.SupportsFilesystem("shiftfs") || util.LoadModule("shiftfs") == nil) {
d.os.Shiftfs = true
logger.Info(" - shiftfs support: yes")
} else {
logger.Info(" - shiftfs support: no")
}
}
// Detect idmapped mounts support.
if shared.IsTrue(os.Getenv("LXD_IDMAPPED_MOUNTS_DISABLE")) {
logger.Info(" - idmapped mounts kernel support: disabled")
} else if kernelSupportsIdmappedMounts() {
d.os.IdmappedMounts = true
logger.Info(" - idmapped mounts kernel support: yes")
} else {
logger.Info(" - idmapped mounts kernel support: no")
}
// Detect and cached available instance types from operational drivers.
drivers := instanceDrivers.DriverStatuses()
for _, driver := range drivers {
if driver.Warning != nil {
dbWarnings = append(dbWarnings, *driver.Warning)
}
}
// Validate the devices storage.
testDev := shared.VarPath("devices", ".test")
testDevNum := int(unix.Mkdev(0, 0))
_ = os.Remove(testDev)
err = unix.Mknod(testDev, 0600|unix.S_IFCHR, testDevNum)
if err == nil {
fd, err := os.Open(testDev)
if err != nil && os.IsPermission(err) {
logger.Warn("Unable to access device nodes, LXD likely running on a nodev mount")
d.os.Nodev = true
}
_ = fd.Close()
_ = os.Remove(testDev)
}
/* Initialize the database */
err = initializeDbObject(d)
if err != nil {
return err
}
/* Setup network endpoint certificate */
networkCert, err := util.LoadCert(d.os.VarDir)