/
v1alpha1_server.go
1955 lines (1598 loc) · 50.5 KB
/
v1alpha1_server.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package runtime
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/AlekSi/pointer"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/oci"
criconstants "github.com/containerd/cri/pkg/constants"
multierror "github.com/hashicorp/go-multierror"
"github.com/prometheus/procfs"
"github.com/rs/xid"
"github.com/talos-systems/go-blockdevice/blockdevice/partition/gpt"
"github.com/talos-systems/go-kmsg"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
installer "github.com/talos-systems/talos/cmd/installer/pkg/install"
"github.com/talos-systems/talos/internal/app/machined/internal/install"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime/disk"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader/adv"
"github.com/talos-systems/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader/grub"
"github.com/talos-systems/talos/internal/app/machined/pkg/system"
networkserver "github.com/talos-systems/talos/internal/app/networkd/pkg/server"
storaged "github.com/talos-systems/talos/internal/app/storaged"
"github.com/talos-systems/talos/internal/pkg/configuration"
"github.com/talos-systems/talos/internal/pkg/containers"
taloscontainerd "github.com/talos-systems/talos/internal/pkg/containers/containerd"
"github.com/talos-systems/talos/internal/pkg/containers/cri"
"github.com/talos-systems/talos/internal/pkg/containers/image"
"github.com/talos-systems/talos/internal/pkg/etcd"
"github.com/talos-systems/talos/internal/pkg/kubeconfig"
"github.com/talos-systems/talos/internal/pkg/mount"
"github.com/talos-systems/talos/pkg/archiver"
"github.com/talos-systems/talos/pkg/chunker"
"github.com/talos-systems/talos/pkg/chunker/stream"
"github.com/talos-systems/talos/pkg/machinery/api/cluster"
"github.com/talos-systems/talos/pkg/machinery/api/common"
"github.com/talos-systems/talos/pkg/machinery/api/inspect"
"github.com/talos-systems/talos/pkg/machinery/api/machine"
"github.com/talos-systems/talos/pkg/machinery/api/network"
"github.com/talos-systems/talos/pkg/machinery/api/resource"
"github.com/talos-systems/talos/pkg/machinery/api/storage"
timeapi "github.com/talos-systems/talos/pkg/machinery/api/time"
clientconfig "github.com/talos-systems/talos/pkg/machinery/client/config"
"github.com/talos-systems/talos/pkg/machinery/config"
"github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/generate"
machinetype "github.com/talos-systems/talos/pkg/machinery/config/types/v1alpha1/machine"
"github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/role"
timeresource "github.com/talos-systems/talos/pkg/resources/time"
"github.com/talos-systems/talos/pkg/version"
)
// MinimumEtcdUpgradeLeaseLockSeconds indicates the minimum number of seconds for which we open a lease lock for upgrading Etcd nodes.
// This is not intended to lock for the duration of an upgrade.
// Rather, it is intended to make sure only one node processes the various pre-upgrade checks at a time.
// Thus, this timeout should be reflective of the expected time for the pre-upgrade checks, NOT the time to perform the upgrade itself.
const MinimumEtcdUpgradeLeaseLockSeconds = 60
// OSPathSeparator is the string version of the os.PathSeparator.
const OSPathSeparator = string(os.PathSeparator)
// Server implements ClusterService and MachineService APIs
// and is also responsible for registering ResourceServer and InspectServer.
type Server struct {
cluster.UnimplementedClusterServiceServer
machine.UnimplementedMachineServiceServer
Controller runtime.Controller
server *grpc.Server
}
func (s *Server) checkSupported(feature runtime.ModeCapability) error {
mode := s.Controller.Runtime().State().Platform().Mode()
if !mode.Supports(feature) {
return fmt.Errorf("method is not supported in %s mode", mode.String())
}
return nil
}
// Register implements the factory.Registrator interface.
func (s *Server) Register(obj *grpc.Server) {
s.server = obj
machine.RegisterMachineServiceServer(obj, s)
cluster.RegisterClusterServiceServer(obj, s)
resource.RegisterResourceServiceServer(obj, &ResourceServer{server: s})
inspect.RegisterInspectServiceServer(obj, &InspectServer{server: s})
storage.RegisterStorageServiceServer(obj, &storaged.Server{})
timeapi.RegisterTimeServiceServer(obj, &TimeServer{ConfigProvider: s.Controller.Runtime()})
network.RegisterNetworkServiceServer(obj, &networkserver.NetworkServer{})
}
// ApplyConfiguration implements machine.MachineService.
//
//nolint:gocyclo
func (s *Server) ApplyConfiguration(ctx context.Context, in *machine.ApplyConfigurationRequest) (*machine.ApplyConfigurationResponse, error) {
log.Printf("apply config request: immediate %v, on reboot %v", in.Immediate, in.OnReboot)
applyDynamicConfig := func() ([]byte, error) {
cfg, err := s.Controller.Runtime().ValidateConfig(in.GetData())
if err != nil {
return nil, err
}
err = cfg.ApplyDynamicConfig(ctx, s.Controller.Runtime().State().Platform())
if err != nil {
return nil, err
}
return cfg.Bytes()
}
switch {
// --immediate
case in.Immediate:
if err := s.Controller.Runtime().CanApplyImmediate(in.GetData()); err != nil {
return nil, err
}
cfg, err := applyDynamicConfig()
if err != nil {
return nil, err
}
if err := s.Controller.Runtime().SetConfig(cfg); err != nil {
return nil, err
}
if err := ioutil.WriteFile(constants.ConfigPath, in.GetData(), 0o600); err != nil {
return nil, err
}
// default (no flags)
case !in.OnReboot:
if err := s.Controller.Runtime().SetConfig(in.GetData()); err != nil {
return nil, err
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceApplyConfiguration, in); err != nil {
if !runtime.IsRebootError(err) {
log.Println("apply configuration failed:", err)
}
if err != runtime.ErrLocked {
s.server.GracefulStop()
}
}
}()
// --no-reboot
case in.OnReboot:
cfg, err := applyDynamicConfig()
if err != nil {
return nil, err
}
if err = ioutil.WriteFile(constants.ConfigPath, cfg, 0o600); err != nil {
return nil, err
}
}
return &machine.ApplyConfigurationResponse{
Messages: []*machine.ApplyConfiguration{
{},
},
}, nil
}
// GenerateConfiguration implements the machine.MachineServer interface.
func (s *Server) GenerateConfiguration(ctx context.Context, in *machine.GenerateConfigurationRequest) (reply *machine.GenerateConfigurationResponse, err error) {
if s.Controller.Runtime().Config().Machine().Type() == machinetype.TypeWorker {
return nil, fmt.Errorf("config can't be generated on worker nodes")
}
return configuration.Generate(ctx, in)
}
// Reboot implements the machine.MachineServer interface.
//
//nolint:dupl
func (s *Server) Reboot(ctx context.Context, in *emptypb.Empty) (reply *machine.RebootResponse, err error) {
log.Printf("reboot via API received")
if err := s.checkSupported(runtime.Reboot); err != nil {
return nil, err
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceReboot, in, runtime.WithTakeover()); err != nil {
if !runtime.IsRebootError(err) {
log.Println("reboot failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
reply = &machine.RebootResponse{
Messages: []*machine.Reboot{
{},
},
}
return reply, nil
}
// Rollback implements the machine.MachineServer interface.
//
//nolint:gocyclo
func (s *Server) Rollback(ctx context.Context, in *machine.RollbackRequest) (*machine.RollbackResponse, error) {
log.Printf("rollback via API received")
if err := s.checkSupported(runtime.Rollback); err != nil {
return nil, err
}
if err := func() error {
if err := mount.SystemPartitionMount(s.Controller.Runtime(), constants.BootPartitionLabel); err != nil {
return fmt.Errorf("error mounting boot partition: %w", err)
}
defer func() {
if err := mount.SystemPartitionUnmount(s.Controller.Runtime(), constants.BootPartitionLabel); err != nil {
log.Printf("failed unmounting boot partition: %s", err)
}
}()
disk := s.Controller.Runtime().State().Machine().Disk(disk.WithPartitionLabel(constants.BootPartitionLabel))
if disk == nil {
return fmt.Errorf("boot disk not found")
}
grub := &grub.Grub{
BootDisk: disk.Device().Name(),
}
_, next, err := grub.Labels()
if err != nil {
return err
}
if _, err = os.Stat(filepath.Join(constants.BootMountPoint, next)); errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("cannot rollback to %q, label does not exist", next)
}
if err := grub.Default(next); err != nil {
return fmt.Errorf("failed to revert bootloader: %v", err)
}
return nil
}(); err != nil {
return nil, err
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceReboot, in, runtime.WithForce(), runtime.WithTakeover()); err != nil {
if !runtime.IsRebootError(err) {
log.Println("reboot failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
return &machine.RollbackResponse{
Messages: []*machine.Rollback{
{},
},
}, nil
}
// Bootstrap implements the machine.MachineServer interface.
func (s *Server) Bootstrap(ctx context.Context, in *machine.BootstrapRequest) (reply *machine.BootstrapResponse, err error) {
log.Printf("bootstrap request received")
if s.Controller.Runtime().Config().Machine().Type() == machinetype.TypeWorker {
return nil, status.Error(codes.FailedPrecondition, "bootstrap can only be performed on a control plane node")
}
timeCtx, timeCtxCancel := context.WithTimeout(ctx, 5*time.Second)
defer timeCtxCancel()
if err := timeresource.NewSyncCondition(s.Controller.Runtime().State().V1Alpha2().Resources()).Wait(timeCtx); err != nil {
return nil, status.Error(codes.FailedPrecondition, "time is not in sync yet")
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceBootstrap, in); err != nil {
log.Println("bootstrap failed:", err)
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
reply = &machine.BootstrapResponse{
Messages: []*machine.Bootstrap{
{},
},
}
return reply, nil
}
// Shutdown implements the machine.MachineServer interface.
//
//nolint:dupl
func (s *Server) Shutdown(ctx context.Context, in *emptypb.Empty) (reply *machine.ShutdownResponse, err error) {
log.Printf("shutdown via API received")
if err = s.checkSupported(runtime.Shutdown); err != nil {
return nil, err
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceShutdown, in, runtime.WithTakeover()); err != nil {
if !runtime.IsRebootError(err) {
log.Println("shutdown failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
reply = &machine.ShutdownResponse{
Messages: []*machine.Shutdown{
{},
},
}
return reply, nil
}
// Upgrade initiates an upgrade.
//
//nolint:gocyclo,cyclop
func (s *Server) Upgrade(ctx context.Context, in *machine.UpgradeRequest) (reply *machine.UpgradeResponse, err error) {
var mu *concurrency.Mutex
if err = s.checkSupported(runtime.Upgrade); err != nil {
return nil, err
}
log.Printf("upgrade request received: preserve %v, staged %v, force %v", in.GetPreserve(), in.GetStage(), in.GetForce())
log.Printf("validating %q", in.GetImage())
if err = pullAndValidateInstallerImage(ctx, s.Controller.Runtime().Config().Machine().Registries(), in.GetImage()); err != nil {
return nil, fmt.Errorf("error validating installer image %q: %w", in.GetImage(), err)
}
if s.Controller.Runtime().Config().Machine().Type() != machinetype.TypeWorker && !in.GetForce() {
client, err := etcd.NewClientFromControlPlaneIPs(ctx, s.Controller.Runtime().Config().Cluster().CA(), s.Controller.Runtime().Config().Cluster().Endpoint())
if err != nil {
return nil, fmt.Errorf("failed to create etcd client: %w", err)
}
// acquire the upgrade mutex
if mu, err = upgradeMutex(client); err != nil {
return nil, fmt.Errorf("failed to acquire upgrade mutex: %w", err)
}
if err = mu.TryLock(ctx); err != nil {
return nil, fmt.Errorf("failed to acquire upgrade lock: %w", err)
}
if err = client.ValidateForUpgrade(ctx, s.Controller.Runtime().Config(), in.GetPreserve()); err != nil {
mu.Unlock(ctx) //nolint:errcheck
return nil, fmt.Errorf("error validating etcd for upgrade: %w", err)
}
}
if in.GetStage() {
meta, err := bootloader.NewMeta()
if err != nil {
return nil, fmt.Errorf("error reading meta: %w", err)
}
//nolint:errcheck
defer meta.Close()
if !meta.ADV.SetTag(adv.StagedUpgradeImageRef, in.GetImage()) {
return nil, fmt.Errorf("error adding staged upgrade image ref tag")
}
opts := install.DefaultInstallOptions()
if err = opts.Apply(install.OptionsFromUpgradeRequest(s.Controller.Runtime(), in)...); err != nil {
return nil, fmt.Errorf("error applying install options: %w", err)
}
serialized, err := json.Marshal(opts)
if err != nil {
return nil, fmt.Errorf("error serializing install options: %s", err)
}
if !meta.ADV.SetTag(adv.StagedUpgradeInstallOptions, string(serialized)) {
return nil, fmt.Errorf("error adding staged upgrade install options tag")
}
if err = meta.Write(); err != nil {
return nil, fmt.Errorf("error writing meta: %w", err)
}
go func() {
if mu != nil {
defer mu.Unlock(ctx) //nolint:errcheck
}
if err := s.Controller.Run(context.Background(), runtime.SequenceStageUpgrade, in); err != nil {
if !runtime.IsRebootError(err) {
log.Println("reboot for staged upgrade failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
} else {
go func() {
if mu != nil {
defer mu.Unlock(ctx) //nolint:errcheck
}
if err := s.Controller.Run(context.Background(), runtime.SequenceUpgrade, in); err != nil {
if !runtime.IsRebootError(err) {
log.Println("upgrade failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
}
reply = &machine.UpgradeResponse{
Messages: []*machine.Upgrade{
{
Ack: "Upgrade request received",
},
},
}
return reply, nil
}
// ResetOptions implements runtime.ResetOptions interface.
type ResetOptions struct {
*machine.ResetRequest
systemDiskTargets []*installer.Target
}
// GetSystemDiskTargets implements runtime.ResetOptions interface.
func (opt *ResetOptions) GetSystemDiskTargets() []runtime.PartitionTarget {
if opt.systemDiskTargets == nil {
return nil
}
result := make([]runtime.PartitionTarget, len(opt.systemDiskTargets))
for i := range result {
result[i] = opt.systemDiskTargets[i]
}
return result
}
// Reset resets the node.
//
//nolint:gocyclo
func (s *Server) Reset(ctx context.Context, in *machine.ResetRequest) (reply *machine.ResetResponse, err error) {
log.Printf("reset request received")
opts := ResetOptions{
ResetRequest: in,
}
if len(in.GetSystemPartitionsToWipe()) > 0 {
bd := s.Controller.Runtime().State().Machine().Disk().BlockDevice
var pt *gpt.GPT
pt, err = bd.PartitionTable()
if err != nil {
return nil, fmt.Errorf("error reading partition table: %w", err)
}
for _, spec := range in.GetSystemPartitionsToWipe() {
var target *installer.Target
switch spec.Label {
case constants.EFIPartitionLabel:
target = installer.EFITarget(bd.Device().Name(), nil)
case constants.BIOSGrubPartitionLabel:
target = installer.BIOSTarget(bd.Device().Name(), nil)
case constants.BootPartitionLabel:
target = installer.BootTarget(bd.Device().Name(), nil)
case constants.MetaPartitionLabel:
target = installer.MetaTarget(bd.Device().Name(), nil)
case constants.StatePartitionLabel:
target = installer.StateTarget(bd.Device().Name(), installer.NoFilesystem)
case constants.EphemeralPartitionLabel:
target = installer.EphemeralTarget(bd.Device().Name(), installer.NoFilesystem)
default:
return nil, fmt.Errorf("label %q is not supported", spec.Label)
}
_, err = target.Locate(pt)
if err != nil {
return nil, fmt.Errorf("failed location partition with label %q: %w", spec.Label, err)
}
if spec.Wipe {
opts.systemDiskTargets = append(opts.systemDiskTargets, target)
}
}
}
go func() {
if err := s.Controller.Run(context.Background(), runtime.SequenceReset, &opts); err != nil {
if !runtime.IsRebootError(err) {
log.Println("reset failed:", err)
}
if err != runtime.ErrLocked {
// NB: We stop the gRPC server since a failed sequence triggers a
// reboot.
s.server.GracefulStop()
}
}
}()
reply = &machine.ResetResponse{
Messages: []*machine.Reset{
{},
},
}
return reply, nil
}
// ServiceList returns list of the registered services and their status.
func (s *Server) ServiceList(ctx context.Context, in *emptypb.Empty) (result *machine.ServiceListResponse, err error) {
services := system.Services(s.Controller.Runtime()).List()
result = &machine.ServiceListResponse{
Messages: []*machine.ServiceList{
{
Services: make([]*machine.ServiceInfo, len(services)),
},
},
}
for i := range services {
result.Messages[0].Services[i] = services[i].AsProto()
}
return result, nil
}
// ServiceStart implements the machine.MachineServer interface and starts a
// service running on Talos.
func (s *Server) ServiceStart(ctx context.Context, in *machine.ServiceStartRequest) (reply *machine.ServiceStartResponse, err error) {
if err = system.Services(s.Controller.Runtime()).APIStart(ctx, in.Id); err != nil {
return &machine.ServiceStartResponse{}, err
}
reply = &machine.ServiceStartResponse{
Messages: []*machine.ServiceStart{
{
Resp: fmt.Sprintf("Service %q started", in.Id),
},
},
}
return reply, err
}
// ServiceStop implements the machine.MachineServer interface and stops a
// service running on Talos.
func (s *Server) ServiceStop(ctx context.Context, in *machine.ServiceStopRequest) (reply *machine.ServiceStopResponse, err error) {
if err = system.Services(s.Controller.Runtime()).APIStop(ctx, in.Id); err != nil {
return &machine.ServiceStopResponse{}, err
}
reply = &machine.ServiceStopResponse{
Messages: []*machine.ServiceStop{
{
Resp: fmt.Sprintf("Service %q stopped", in.Id),
},
},
}
return reply, err
}
// ServiceRestart implements the machine.MachineServer interface and stops a
// service running on Talos.
func (s *Server) ServiceRestart(ctx context.Context, in *machine.ServiceRestartRequest) (reply *machine.ServiceRestartResponse, err error) {
if err = system.Services(s.Controller.Runtime()).APIRestart(ctx, in.Id); err != nil {
return &machine.ServiceRestartResponse{}, err
}
reply = &machine.ServiceRestartResponse{
Messages: []*machine.ServiceRestart{
{
Resp: fmt.Sprintf("Service %q restarted", in.Id),
},
},
}
return reply, err
}
// Copy implements the machine.MachineServer interface and copies data out of Talos node.
func (s *Server) Copy(req *machine.CopyRequest, obj machine.MachineService_CopyServer) error {
path := req.RootPath
path = filepath.Clean(path)
if !filepath.IsAbs(path) {
return fmt.Errorf("path is not absolute %v", path)
}
pr, pw := io.Pipe()
errCh := make(chan error, 1)
ctx, ctxCancel := context.WithCancel(obj.Context())
defer ctxCancel()
go func() {
//nolint:errcheck
defer pw.Close()
errCh <- archiver.TarGz(ctx, path, pw)
}()
chunker := stream.NewChunker(ctx, pr)
chunkCh := chunker.Read()
for data := range chunkCh {
err := obj.SendMsg(&common.Data{Bytes: data})
if err != nil {
ctxCancel()
}
}
archiveErr := <-errCh
if archiveErr != nil {
return obj.SendMsg(&common.Data{
Metadata: &common.Metadata{
Error: archiveErr.Error(),
},
})
}
return nil
}
// List implements the machine.MachineServer interface.
//
//nolint:gocyclo
func (s *Server) List(req *machine.ListRequest, obj machine.MachineService_ListServer) error {
if req == nil {
req = new(machine.ListRequest)
}
if !strings.HasPrefix(req.Root, OSPathSeparator) {
// Make sure we use complete paths
req.Root = OSPathSeparator + req.Root
}
req.Root = strings.TrimSuffix(req.Root, OSPathSeparator)
if req.Root == "" {
req.Root = "/"
}
var recursionDepth int
if req.Recurse {
if req.RecursionDepth == 0 {
recursionDepth = -1
} else {
recursionDepth = int(req.RecursionDepth)
}
}
opts := []archiver.WalkerOption{
archiver.WithMaxRecurseDepth(recursionDepth),
}
if len(req.Types) > 0 {
types := make([]archiver.FileType, 0, len(req.Types))
for _, t := range req.Types {
switch t {
case machine.ListRequest_REGULAR:
types = append(types, archiver.RegularFileType)
case machine.ListRequest_DIRECTORY:
types = append(types, archiver.DirectoryFileType)
case machine.ListRequest_SYMLINK:
types = append(types, archiver.SymlinkFileType)
}
}
opts = append(opts, archiver.WithFileTypes(types...))
}
files, err := archiver.Walker(obj.Context(), req.Root, opts...)
if err != nil {
return err
}
for fi := range files {
if fi.Error != nil {
err = obj.Send(&machine.FileInfo{
Name: fi.FullPath,
RelativeName: fi.RelPath,
Error: fi.Error.Error(),
})
} else {
err = obj.Send(&machine.FileInfo{
Name: fi.FullPath,
RelativeName: fi.RelPath,
Size: fi.FileInfo.Size(),
Mode: uint32(fi.FileInfo.Mode()),
Modified: fi.FileInfo.ModTime().Unix(),
IsDir: fi.FileInfo.IsDir(),
Link: fi.Link,
})
}
if err != nil {
return err
}
}
return nil
}
// DiskUsage implements the machine.MachineServer interface.
//nolint:cyclop
func (s *Server) DiskUsage(req *machine.DiskUsageRequest, obj machine.MachineService_DiskUsageServer) error { //nolint:gocyclo
if req == nil {
req = new(machine.DiskUsageRequest)
}
for _, path := range req.Paths {
if !strings.HasPrefix(path, OSPathSeparator) {
// Make sure we use complete paths
path = OSPathSeparator + path
}
path = strings.TrimSuffix(path, OSPathSeparator)
if path == "" {
path = "/"
}
_, err := os.Stat(path)
if err == os.ErrNotExist {
err = obj.Send(
&machine.DiskUsageInfo{
Name: path,
RelativeName: path,
Error: err.Error(),
},
)
if err != nil {
return err
}
continue
}
files, err := archiver.Walker(obj.Context(), path, archiver.WithMaxRecurseDepth(-1))
if err != nil {
err = obj.Send(
&machine.DiskUsageInfo{
Name: path,
RelativeName: path,
Error: err.Error(),
},
)
if err != nil {
return err
}
continue
}
folders := map[string]*machine.DiskUsageInfo{}
// send a record back to client if the message shouldn't be skipped
// at the same time use record information for folder size estimation
sendSize := func(info *machine.DiskUsageInfo, depth int32, isDir bool) error {
prefix := strings.TrimRight(filepath.Dir(info.Name), "/")
if folder, ok := folders[prefix]; ok {
folder.Size += info.Size
}
// recursion depth check
skip := depth >= req.RecursionDepth && req.RecursionDepth > 0
// skip files check
skip = skip || !isDir && !req.All
// threshold check
skip = skip || req.Threshold > 0 && info.Size < req.Threshold
skip = skip || req.Threshold < 0 && info.Size > -req.Threshold
if skip {
return nil
}
return obj.Send(info)
}
var (
depth int32
prefix = path
rootDepth = int32(strings.Count(path, archiver.OSPathSeparator))
)
// flush all folder sizes until we get to the common prefix
flushFolders := func(prefix, nextPrefix string) error {
for !strings.HasPrefix(nextPrefix, prefix) {
currentDepth := int32(strings.Count(prefix, archiver.OSPathSeparator)) - rootDepth
if folder, ok := folders[prefix]; ok {
err = sendSize(folder, currentDepth, true)
if err != nil {
return err
}
delete(folders, prefix)
}
prefix = strings.TrimRight(filepath.Dir(prefix), "/")
}
return nil
}
for fi := range files {
if fi.Error != nil {
err = obj.Send(
&machine.DiskUsageInfo{
Name: fi.FullPath,
RelativeName: fi.RelPath,
Error: fi.Error.Error(),
},
)
} else {
currentDepth := int32(strings.Count(fi.FullPath, archiver.OSPathSeparator)) - rootDepth
size := fi.FileInfo.Size()
if size < 0 {
size = 0
}
// kcore file size gives wrong value, this code should be smarter when it reads it
// TODO: figure out better way to skip such file
if fi.FullPath == "/proc/kcore" {
size = 0
}
if fi.FileInfo.IsDir() {
folders[strings.TrimRight(fi.FullPath, "/")] = &machine.DiskUsageInfo{
Name: fi.FullPath,
RelativeName: fi.RelPath,
Size: size,
}
} else {
err = sendSize(&machine.DiskUsageInfo{
Name: fi.FullPath,
RelativeName: fi.RelPath,
Size: size,
}, currentDepth, false)
if err != nil {
return err
}
}
// depth goes down when walker gets to the next sibling folder
if currentDepth < depth {
nextPrefix := fi.FullPath
err = flushFolders(prefix, nextPrefix)
if err != nil {
return err
}
prefix = nextPrefix
}
if fi.FileInfo.IsDir() {
prefix = fi.FullPath
}
depth = currentDepth
}
}
if path != "" {
p := strings.TrimRight(path, "/")
if folder, ok := folders[p]; ok {
err = flushFolders(prefix, p)
if err != nil {
return err
}
err = sendSize(folder, 0, true)
if err != nil {
return err
}
}
}
return nil
}
return nil
}
// Mounts implements the machine.MachineServer interface.
func (s *Server) Mounts(ctx context.Context, in *emptypb.Empty) (reply *machine.MountsResponse, err error) {
file, err := os.Open("/proc/mounts")
if err != nil {
return nil, err
}
//nolint:errcheck
defer file.Close()
var (
stat unix.Statfs_t
multiErr *multierror.Error
)
stats := []*machine.MountStat{}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 2 {
continue
}
filesystem := fields[0]
mountpoint := fields[1]