-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy patheosgrpc.go
1802 lines (1464 loc) · 57.2 KB
/
eosgrpc.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
// Copyright 2018-2024 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
// NOTE: compile the grpc proto with these commands
// and do not ask any questions, I don't have the answer
// protoc ./Rpc.proto --go_out=plugins=grpc:.
package eosgrpc
import (
"context"
"encoding/hex"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"time"
erpc "github.com/cern-eos/go-eosgrpc"
"github.com/cs3org/reva/pkg/appctx"
"github.com/cs3org/reva/pkg/eosclient"
"github.com/cs3org/reva/pkg/errtypes"
"github.com/cs3org/reva/pkg/storage/utils/acl"
"github.com/cs3org/reva/pkg/utils"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
const (
versionPrefix = ".sys.v#."
favoritesKey = "http://owncloud.org/ns/favorite"
)
const (
// SystemAttr is the system extended attribute.
SystemAttr eosclient.AttrType = iota
// UserAttr is the user extended attribute.
UserAttr
)
// Client performs actions against a EOS management node (MGM)
// using the EOS GRPC interface.
type Client struct {
opt *Options
httpcl *EOSHTTPClient
cl erpc.EosClient
}
// Options to configure the Client.
type Options struct {
// UseKeyTabAuth changes will authenticate requests by using an EOS keytab.
UseKeytab bool
// Whether to maintain the same inode across various versions of a file.
// Requires extra metadata operations if set to true
VersionInvariant bool
// Set to true to use the local disk as a buffer for chunk
// reads from EOS. Default is false, i.e. pure streaming
ReadUsesLocalTemp bool
// Set to true to use the local disk as a buffer for chunk
// writes to EOS. Default is false, i.e. pure streaming
// Beware: in pure streaming mode the FST must support
// the HTTP chunked encoding
WriteUsesLocalTemp bool
// Location of the xrdcopy binary.
// Default is /opt/eos/xrootd/bin/xrdcopy.
XrdcopyBinary string
// URL of the EOS MGM.
// Default is root://eos-example.org
URL string
// URI of the EOS MGM grpc server
GrpcURI string
// Location on the local fs where to store reads.
// Defaults to os.TempDir()
CacheDirectory string
// Keytab is the location of the EOS keytab file.
Keytab string
// Authkey is the key that authorizes this client to connect to the GRPC service
Authkey string
// SecProtocol is the comma separated list of security protocols used by xrootd.
// For example: "sss, unix"
SecProtocol string
// TokenExpiry stores in seconds the time after which generated tokens will expire
// Default is 3600
TokenExpiry int
}
func (opt *Options) init() {
if opt.XrdcopyBinary == "" {
opt.XrdcopyBinary = "/opt/eos/xrootd/bin/xrdcopy"
}
if opt.URL == "" {
opt.URL = "root://eos-example.org"
}
if opt.CacheDirectory == "" {
opt.CacheDirectory = os.TempDir()
}
}
func serializeAttribute(a *eosclient.Attribute) string {
return fmt.Sprintf("%s.%s=%s", attrTypeToString(a.Type), a.Key, a.Val)
}
func attrTypeToString(at eosclient.AttrType) string {
switch at {
case eosclient.SystemAttr:
return "sys"
case eosclient.UserAttr:
return "user"
default:
return "invalid"
}
}
func isValidAttribute(a *eosclient.Attribute) bool {
// validate that an attribute is correct.
if (a.Type != eosclient.SystemAttr && a.Type != eosclient.UserAttr) || a.Key == "" {
return false
}
return true
}
// Create and connect a grpc eos Client.
func newgrpc(ctx context.Context, log *zerolog.Logger, opt *Options) (erpc.EosClient, error) {
log.Debug().Msgf("Setting up GRPC towards '%s'", opt.GrpcURI)
conn, err := grpc.NewClient(opt.GrpcURI, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Warn().Err(err).Msgf("Error connecting to '%s'", opt.GrpcURI)
}
log.Debug().Msgf("Going to ping '%s'", opt.GrpcURI)
ecl := erpc.NewEosClient(conn)
// If we can't ping... just print warnings. In the case EOS is down, grpc will take care of
// connecting later
prq := new(erpc.PingRequest)
prq.Authkey = opt.Authkey
prq.Message = []byte("hi this is a ping from reva")
prep, err := ecl.Ping(ctx, prq)
if err != nil {
log.Warn().Err(err).Msgf("Could not ping to '%s'", opt.GrpcURI)
}
if prep == nil {
log.Warn().Msgf("Could not ping to '%s': nil response", opt.GrpcURI)
}
log.Debug().Msgf("Ping to '%s' succeeded", opt.GrpcURI)
return ecl, nil
}
// New creates a new client with the given options.
func New(ctx context.Context, opt *Options, httpOpts *HTTPOptions) (*Client, error) {
log := appctx.GetLogger(ctx)
log.Debug().Interface("options", opt).Msgf("Creating new eosgrpc client")
opt.init()
httpcl, err := NewEOSHTTPClient(httpOpts)
if err != nil {
return nil, err
}
cl, err := newgrpc(ctx, log, opt)
if err != nil {
return nil, err
}
return &Client{
opt: opt,
httpcl: httpcl,
cl: cl,
}, nil
}
// If the error is not nil, take that
// If there is an error coming from EOS, return a descriptive error.
func (c *Client) getRespError(rsp *erpc.NSResponse, err error) error {
if err != nil {
return err
}
if rsp == nil || rsp.Error == nil || rsp.Error.Code == 0 {
return nil
}
switch rsp.Error.Code {
case 16: // EBUSY
return eosclient.FileIsLockedError
case 17: // EEXIST
return eosclient.AttrAlreadyExistsError
default:
return errtypes.InternalError(fmt.Sprintf("%s (code: %d)", rsp.Error.Msg, rsp.Error.Code))
}
}
// Common code to create and initialize a NSRequest.
func (c *Client) initNSRequest(ctx context.Context, auth eosclient.Authorization, app string) (*erpc.NSRequest, error) {
log := appctx.GetLogger(ctx)
log.Debug().Str("(uid,gid)", "("+auth.Role.UID+","+auth.Role.GID+")").Str("app", app).Msg("New grpcNS req")
rq := new(erpc.NSRequest)
rq.Role = new(erpc.RoleId)
// Let's put in the authentication info
if auth.Token != "" {
// Map to owner using EOSAUTHZ token
// We do not become cbox
rq.Authkey = auth.Token
} else {
// We take the secret key from the config, which maps on EOS to cbox
// cbox is a sudo'er, so we become the user specified in UID/GID, if it is set
rq.Authkey = c.opt.Authkey
uid, gid, err := utils.ExtractUidGid(auth)
if err == nil {
rq.Role.Uid = uid
rq.Role.Gid = gid
}
}
// For NS operations, specifically for locking, we also need to provide the app
if app != "" {
rq.Role.App = app
}
return rq, nil
}
// Common code to create and initialize a MDRequest.
func (c *Client) initMDRequest(ctx context.Context, auth eosclient.Authorization) (*erpc.MDRequest, error) {
// Stuff filename, uid, gid into the MDRequest type
log := appctx.GetLogger(ctx)
log.Debug().Str("(uid,gid)", "("+auth.Role.UID+","+auth.Role.GID+")").Msg("New grpcMD req")
rq := new(erpc.MDRequest)
rq.Role = new(erpc.RoleId)
if auth.Token != "" {
// Map to owner using EOSAUTHZ token
// We do not become cbox
rq.Authkey = auth.Token
} else {
// We take the secret key from the config, which maps on EOS to cbox
// cbox is a sudo'er, so we become the user specified in UID/GID, if it is set
rq.Authkey = c.opt.Authkey
uid, gid, err := utils.ExtractUidGid(auth)
if err == nil {
rq.Role.Uid = uid
rq.Role.Gid = gid
}
}
return rq, nil
}
// AddACL adds an new acl to EOS with the given aclType.
func (c *Client) AddACL(ctx context.Context, auth, rootAuth eosclient.Authorization, path string, pos uint, a *acl.Entry) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "AddACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
// First, we need to figure out if the path is a directory
// to know whether our request should be recursive
fileInfo, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return err
}
// Init a new NSRequest
rq, err := c.initNSRequest(ctx, rootAuth, "")
if err != nil {
return err
}
// workaround to be root
// TODO: removed once fixed in eos grpc
rq.Role.Gid = 1
msg := new(erpc.NSRequest_AclRequest)
msg.Cmd = erpc.NSRequest_AclRequest_ACL_COMMAND(erpc.NSRequest_AclRequest_ACL_COMMAND_value["MODIFY"])
msg.Type = erpc.NSRequest_AclRequest_ACL_TYPE(erpc.NSRequest_AclRequest_ACL_TYPE_value["SYS_ACL"])
msg.Recursive = fileInfo.IsDir
msg.Rule = a.CitrineSerialize()
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
rq.Command = &erpc.NSRequest_Acl{Acl: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
log.Error().Str("func", "AddACL").Str("path", path).Str("err", e.Error()).Msg("")
return e
}
if resp == nil {
return errtypes.NotFound(fmt.Sprintf("Path: %s", path))
}
log.Debug().Str("func", "AddACL").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
return err
}
// RemoveACL removes the acl from EOS.
func (c *Client) RemoveACL(ctx context.Context, auth, rootAuth eosclient.Authorization, path string, a *acl.Entry) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "RemoveACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Str("ACL", a.CitrineSerialize()).Msg("")
// We set permissions to "", so the ACL will serialize to `u:123456=`, which will make EOS delete the entry
a.Permissions = ""
return c.AddACL(ctx, auth, rootAuth, path, eosclient.StartPosition, a)
}
// UpdateACL updates the EOS acl.
func (c *Client) UpdateACL(ctx context.Context, auth, rootAuth eosclient.Authorization, path string, position uint, a *acl.Entry) error {
return c.AddACL(ctx, auth, rootAuth, path, position, a)
}
// GetACL for a file.
func (c *Client) GetACL(ctx context.Context, auth eosclient.Authorization, path, aclType, target string) (*acl.Entry, error) {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "GetACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
acls, err := c.ListACLs(ctx, auth, path)
if err != nil {
return nil, err
}
for _, a := range acls {
if a.Type == aclType && a.Qualifier == target {
return a, nil
}
}
return nil, errtypes.NotFound(fmt.Sprintf("%s:%s", aclType, target))
}
// ListACLs returns the list of ACLs present under the given path.
// EOS returns uids/gid for Citrine version and usernames for older versions.
// For Citire we need to convert back the uid back to username.
func (c *Client) ListACLs(ctx context.Context, auth eosclient.Authorization, path string) ([]*acl.Entry, error) {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "ListACLs").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
parsedACLs, err := c.getACLForPath(ctx, auth, path)
if err != nil {
return nil, err
}
// EOS Citrine ACLs are stored with uid. The UID will be resolved to the
// user opaque ID at the eosfs level.
return parsedACLs.Entries, nil
}
func (c *Client) getACLForPath(ctx context.Context, auth eosclient.Authorization, path string) (*acl.ACLs, error) {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "GetACLForPath").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
fileInfo, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return nil, err
}
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, auth, "")
if err != nil {
return nil, err
}
msg := new(erpc.NSRequest_AclRequest)
msg.Cmd = erpc.NSRequest_AclRequest_ACL_COMMAND(erpc.NSRequest_AclRequest_ACL_COMMAND_value["LIST"])
msg.Type = erpc.NSRequest_AclRequest_ACL_TYPE(erpc.NSRequest_AclRequest_ACL_TYPE_value["SYS_ACL"])
msg.Recursive = fileInfo.IsDir
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
rq.Command = &erpc.NSRequest_Acl{Acl: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
log.Error().Str("func", "GetACLForPath").Str("path", path).Str("err", e.Error()).Msg("")
return nil, e
}
if resp == nil {
return nil, errtypes.InternalError(fmt.Sprintf("nil response for uid: '%s' path: '%s'", auth.Role.UID, path))
}
log.Debug().Str("func", "GetACLForPath").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
if resp.Acl == nil {
return nil, errtypes.InternalError(fmt.Sprintf("nil acl for uid: '%s' path: '%s'", auth.Role.UID, path))
}
if resp.GetError() != nil {
log.Error().Str("func", "GetACLForPath").Str("uid", auth.Role.UID).Str("path", path).Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative resp")
}
aclret, err := acl.Parse(resp.Acl.Rule, acl.ShortTextForm)
// Now loop and build the correct return value
return aclret, err
}
// GetFileInfoByInode returns the FileInfo by the given inode.
func (c *Client) GetFileInfoByInode(ctx context.Context, auth eosclient.Authorization, inode uint64) (*eosclient.FileInfo, error) {
log := appctx.GetLogger(ctx)
log.Debug().Str("func", "GetFileInfoByInode").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Uint64("inode", inode).Msg("entering")
// Initialize the common fields of the MDReq
mdrq, err := c.initMDRequest(ctx, auth)
if err != nil {
return nil, err
}
// Stuff filename, uid, gid into the MDRequest type
mdrq.Type = erpc.TYPE_STAT
mdrq.Id = new(erpc.MDId)
mdrq.Id.Ino = inode
// Now send the req and see what happens
resp, err := c.cl.MD(appctx.ContextGetClean(ctx), mdrq)
if err != nil {
log.Error().Err(err).Uint64("inode", inode).Str("err", err.Error()).Send()
return nil, err
}
rsp, err := resp.Recv()
if err != nil {
log.Error().Err(err).Uint64("inode", inode).Str("err", err.Error()).Send()
return nil, err
}
if rsp == nil {
return nil, errtypes.InternalError(fmt.Sprintf("nil response for inode: '%d'", inode))
}
log.Debug().Uint64("inode", inode).Str("rsp:", fmt.Sprintf("%#v", rsp)).Msg("grpc response")
info, err := c.grpcMDResponseToFileInfo(ctx, rsp)
if err != nil {
return nil, err
}
if c.opt.VersionInvariant && isVersionFolder(info.File) {
info, err = c.getFileInfoFromVersion(ctx, auth, info.File)
if err != nil {
return nil, err
}
info.Inode = inode
}
log.Info().Str("func", "GetFileInfoByInode").Uint64("inode", inode).Uint64("info.Inode", info.Inode).Str("file", info.File).Uint64("size", info.Size).Str("etag", info.ETag).Msg("result")
return c.fixupACLs(ctx, auth, info), nil
}
func (c *Client) fixupACLs(ctx context.Context, auth eosclient.Authorization, info *eosclient.FileInfo) *eosclient.FileInfo {
// Append the ACLs that are described by the xattr sys.acl entry
a, err := acl.Parse(info.Attrs["sys.acl"], acl.ShortTextForm)
if err == nil {
if info.SysACL != nil {
info.SysACL.Entries = append(info.SysACL.Entries, a.Entries...)
} else {
info.SysACL = a
}
}
// We need to inherit the ACLs for the parent directory as these are not available for files
if !info.IsDir {
parentInfo, err := c.GetFileInfoByPath(ctx, auth, path.Dir(info.File))
// Even if this call fails, at least return the current file object
if err == nil {
info.SysACL.Entries = append(info.SysACL.Entries, parentInfo.SysACL.Entries...)
}
}
return info
}
// SetAttr sets an extended attributes on a path.
func (c *Client) SetAttr(ctx context.Context, auth eosclient.Authorization, attr *eosclient.Attribute, errorIfExists, recursive bool, path, app string) error {
if !isValidAttribute(attr) {
return errors.New("eos: attr is invalid: " + serializeAttribute(attr))
}
// Favorites need to be stored per user so handle these separately
if attr.Type == eosclient.UserAttr && attr.Key == favoritesKey {
info, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return err
}
return c.handleFavAttr(ctx, auth, attr, recursive, path, info, true)
}
return c.setEOSAttr(ctx, auth, attr, errorIfExists, recursive, path, app)
}
func (c *Client) setEOSAttr(ctx context.Context, auth eosclient.Authorization, attr *eosclient.Attribute, errorIfExists, recursive bool, path, app string) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "SetAttr").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, auth, app)
if err != nil {
return err
}
msg := new(erpc.NSRequest_SetXAttrRequest)
var m = map[string][]byte{attr.GetKey(): []byte(attr.Val)}
msg.Xattrs = m
msg.Recursive = recursive
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
if errorIfExists {
msg.Create = true
}
rq.Command = &erpc.NSRequest_Xattr{Xattr: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if resp != nil && resp.Error != nil && resp.Error.Code == 17 {
return eosclient.AttrAlreadyExistsError
}
if e != nil {
log.Error().Str("func", "SetAttr").Str("path", path).Str("err", e.Error()).Msg("")
return e
}
if resp == nil {
return errtypes.InternalError(fmt.Sprintf("nil response for uid: '%s' gid: '%s' path: '%s'", auth.Role.UID, auth.Role.GID, path))
}
if resp.GetError() != nil {
log.Error().Str("func", "setAttr").Str("path", path).Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative result")
}
return err
}
func (c *Client) handleFavAttr(ctx context.Context, auth eosclient.Authorization, attr *eosclient.Attribute, recursive bool, path string, info *eosclient.FileInfo, set bool) error {
var err error
u := appctx.ContextMustGetUser(ctx)
if info == nil {
info, err = c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return err
}
}
favStr := info.Attrs[favoritesKey]
favs, err := acl.Parse(favStr, acl.ShortTextForm)
if err != nil {
return err
}
if set {
err = favs.SetEntry(acl.TypeUser, u.Id.OpaqueId, "1")
if err != nil {
return err
}
} else {
favs.DeleteEntry(acl.TypeUser, u.Id.OpaqueId)
}
attr.Val = favs.Serialize()
if attr.Val == "" {
return c.unsetEOSAttr(ctx, auth, attr, recursive, path, "", true)
} else {
return c.setEOSAttr(ctx, auth, attr, false, recursive, path, "")
}
}
// UnsetAttr unsets an extended attribute on a path.
func (c *Client) UnsetAttr(ctx context.Context, auth eosclient.Authorization, attr *eosclient.Attribute, recursive bool, path, app string) error {
// In the case of handleFavs, we call unsetEOSAttr with deleteFavs = true, which is why this simply calls a subroutine
return c.unsetEOSAttr(ctx, auth, attr, recursive, path, app, false)
}
func (c *Client) unsetEOSAttr(ctx context.Context, auth eosclient.Authorization, attr *eosclient.Attribute, recursive bool, path, app string, deleteFavs bool) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "unsetEOSAttr").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
// Favorites need to be stored per user so handle these separately
if !deleteFavs && attr.Type == eosclient.UserAttr && attr.Key == favoritesKey {
info, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return err
}
return c.handleFavAttr(ctx, auth, attr, recursive, path, info, false)
}
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, auth, app)
if err != nil {
return err
}
msg := new(erpc.NSRequest_SetXAttrRequest)
var ktd = []string{attr.GetKey()}
msg.Keystodelete = ktd
msg.Recursive = recursive
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
rq.Command = &erpc.NSRequest_Xattr{Xattr: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
if resp != nil && resp.Error != nil && resp.Error.Code == 61 {
return eosclient.AttrNotExistsError
}
e := c.getRespError(resp, err)
if e != nil {
log.Error().Str("func", "UnsetAttr").Str("path", path).Str("err", e.Error()).Msg("")
return e
}
if resp == nil {
return errtypes.InternalError(fmt.Sprintf("nil response for uid: '%s' gid: '%s' path: '%s'", auth.Role.UID, auth.Role.GID, path))
}
if resp.GetError() != nil {
log.Error().Str("func", "UnsetAttr").Str("path", path).Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative resp")
}
return err
}
// GetAttr returns the attribute specified by key.
func (c *Client) GetAttr(ctx context.Context, auth eosclient.Authorization, key, path string) (*eosclient.Attribute, error) {
info, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return nil, err
}
for k, v := range info.Attrs {
if k == key {
attr, err := getAttribute(k, v)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("eosgrpc: cannot parse attribute key=%s value=%s", k, v))
}
return attr, nil
}
}
return nil, errtypes.NotFound(fmt.Sprintf("key %s not found", key))
}
// GetAttrs returns all the attributes of a resource.
func (c *Client) GetAttrs(ctx context.Context, auth eosclient.Authorization, path string) ([]*eosclient.Attribute, error) {
info, err := c.GetFileInfoByPath(ctx, auth, path)
if err != nil {
return nil, err
}
attrs := make([]*eosclient.Attribute, 0, len(info.Attrs))
for k, v := range info.Attrs {
attr, err := getAttribute(k, v)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("eosgrpc: cannot parse attribute key=%s value=%s", k, v))
}
attrs = append(attrs, attr)
}
return attrs, nil
}
func getAttribute(key, val string) (*eosclient.Attribute, error) {
// key is in the form sys.forced.checksum
type2key := strings.SplitN(key, ".", 2) // type2key = ["sys", "forced.checksum"]
if len(type2key) != 2 {
return nil, errtypes.InternalError("wrong attr format to deserialize")
}
t, err := eosclient.AttrStringToType(type2key[0])
if err != nil {
return nil, err
}
attr := &eosclient.Attribute{
Type: t,
Key: type2key[1],
Val: val,
}
return attr, nil
}
// GetFileInfoByPath returns the FilInfo at the given path.
func (c *Client) GetFileInfoByPath(ctx context.Context, userAuth eosclient.Authorization, path string) (*eosclient.FileInfo, error) {
log := appctx.GetLogger(ctx)
log.Debug().Str("func", "GetFileInfoByPath").Str("uid,gid", userAuth.Role.UID+","+userAuth.Role.GID).Str("path", path).Msg("entering")
// UserAuth may not be sufficient, because the user may not have access to the file
// e.g. in the case of a guest account. So we check if a uid/gid is set, and if not,
// revert to the daemon account
auth := utils.GetUserOrDaemonAuth(userAuth)
// Initialize the common fields of the MDReq
mdrq, err := c.initMDRequest(ctx, auth)
if err != nil {
return nil, err
}
mdrq.Type = erpc.TYPE_STAT
mdrq.Id = new(erpc.MDId)
mdrq.Id.Path = []byte(path)
// Now send the req and see what happens
resp, err := c.cl.MD(appctx.ContextGetClean(ctx), mdrq)
if err != nil {
log.Error().Str("func", "GetFileInfoByPath").Err(err).Str("path", path).Str("err", err.Error()).Msg("")
return nil, err
}
rsp, err := resp.Recv()
if err != nil {
log.Error().Str("func", "GetFileInfoByPath").Err(err).Str("path", path).Str("err", err.Error()).Msg("")
// FIXME: this is very bad and poisonous for the project!!!!!!!
// Apparently here we have to assume that an error in Recv() means "file not found"
// - "File not found is not an error", it's a legitimate result of a legitimate check
// - Assuming that any error means file not found is doubly poisonous
return nil, errtypes.NotFound(err.Error())
// return nil, nil
}
if rsp == nil {
return nil, errtypes.NotFound(fmt.Sprintf("%s:%s", "acltype", path))
}
log.Debug().Str("func", "GetFileInfoByPath").Str("path", path).Str("rsp:", fmt.Sprintf("%#v", rsp)).Msg("grpc response")
info, err := c.grpcMDResponseToFileInfo(ctx, rsp)
if err != nil {
return nil, err
}
if c.opt.VersionInvariant && !isVersionFolder(path) && !info.IsDir {
// Here we have to create a missing version folder, irrespective from the user (that could be a sharee, or a lw account, or...)
// Therefore, we impersonate the owner of the file
ownerAuth := eosclient.Authorization{
Role: eosclient.Role{
UID: strconv.FormatUint(info.UID, 10),
GID: strconv.FormatUint(info.GID, 10),
},
}
inode, err := c.getOrCreateVersionFolderInode(ctx, ownerAuth, path)
if err != nil {
return nil, err
}
info.Inode = inode
}
log.Info().Str("func", "GetFileInfoByPath").Str("path", path).Uint64("info.Inode", info.Inode).Uint64("size", info.Size).Str("etag", info.ETag).Msg("result")
return c.fixupACLs(ctx, auth, info), nil
}
// GetFileInfoByFXID returns the FileInfo by the given file id in hexadecimal.
func (c *Client) GetFileInfoByFXID(ctx context.Context, auth eosclient.Authorization, fxid string) (*eosclient.FileInfo, error) {
return nil, errtypes.NotSupported("eosgrpc: GetFileInfoByFXID not implemented")
}
// GetQuota gets the quota of a user on the quota node defined by path.
func (c *Client) GetQuota(ctx context.Context, username string, rootAuth eosclient.Authorization, path string) (*eosclient.QuotaInfo, error) {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "GetQuota").Str("rootuid,rootgid", rootAuth.Role.UID+","+rootAuth.Role.GID).Str("username", username).Str("path", path).Msg("")
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, rootAuth, "")
if err != nil {
return nil, err
}
msg := new(erpc.NSRequest_QuotaRequest)
msg.Path = []byte(path)
msg.Id = new(erpc.RoleId)
msg.Op = erpc.QUOTAOP_GET
// Eos filters the returned quotas by username. This means that EOS must know it, someone
// must have created an user with that name
msg.Id.Username = username
rq.Command = &erpc.NSRequest_Quota{Quota: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
return nil, e
}
if resp == nil {
return nil, errtypes.InternalError(fmt.Sprintf("nil response for username: '%s' path: '%s'", username, path))
}
if resp.GetError() != nil {
log.Error().Str("func", "GetQuota").Str("username", username).Str("info:", fmt.Sprintf("%#v", resp)).Int64("eoserrcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative resp")
} else {
log.Debug().Str("func", "GetQuota").Str("username", username).Str("info:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
}
if resp.Quota == nil {
return nil, errtypes.InternalError(fmt.Sprintf("nil quota response? path: '%s'", path))
}
if resp.Quota.Code != 0 {
return nil, errtypes.InternalError(fmt.Sprintf("Quota error from eos. info: '%#v'", resp.Quota))
}
// Let's loop on all the quotas that match this uid (apparently there can be many)
// If there are many for this node, we sum them up
qi := new(eosclient.QuotaInfo)
for i := 0; i < len(resp.Quota.Quotanode); i++ {
log.Debug().Str("func", "GetQuota").Str("quotanode:", fmt.Sprintf("%d: %#v", i, resp.Quota.Quotanode[i])).Msg("")
qi.TotalBytes += max(uint64(resp.Quota.Quotanode[i].Maxlogicalbytes), 0)
qi.UsedBytes += resp.Quota.Quotanode[i].Usedbytes
qi.TotalInodes += max(uint64(resp.Quota.Quotanode[i].Maxfiles), 0)
qi.UsedInodes += resp.Quota.Quotanode[i].Usedfiles
}
return qi, err
}
// SetQuota sets the quota of a user on the quota node defined by path.
func (c *Client) SetQuota(ctx context.Context, rootAuth eosclient.Authorization, info *eosclient.SetQuotaInfo) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "SetQuota").Str("info:", fmt.Sprintf("%#v", info)).Msg("")
// EOS does not have yet this command... work in progress, this is a draft piece of code
// return errtypes.NotSupported("eosgrpc: SetQuota not implemented")
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, rootAuth, "")
if err != nil {
return err
}
msg := new(erpc.NSRequest_QuotaRequest)
msg.Path = []byte(info.QuotaNode)
msg.Id = new(erpc.RoleId)
uidInt, err := strconv.ParseUint(info.UID, 10, 64)
if err != nil {
return err
}
// We set a quota for an user, not a group!
msg.Id.Uid = uidInt
msg.Id.Gid = 0
msg.Id.Username = info.Username
msg.Op = erpc.QUOTAOP_SET
msg.Maxbytes = info.MaxBytes
msg.Maxfiles = info.MaxFiles
rq.Command = &erpc.NSRequest_Quota{Quota: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
return e
}
if resp == nil {
return errtypes.InternalError(fmt.Sprintf("nil response for info: '%#v'", info))
}
if resp.GetError() != nil {
log.Error().Str("func", "SetQuota").Str("info:", fmt.Sprintf("%#v", resp)).Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative resp")
} else {
log.Debug().Str("func", "SetQuota").Str("info:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
}
if resp.Quota == nil {
return errtypes.InternalError(fmt.Sprintf("nil quota response? info: '%#v'", info))
}
if resp.Quota.Code != 0 {
return errtypes.InternalError(fmt.Sprintf("Quota error from eos. quota: '%#v'", resp.Quota))
}
log.Debug().Str("func", "GetQuota").Str("quotanodes", fmt.Sprintf("%d", len(resp.Quota.Quotanode))).Msg("grpc response")
return err
}
// Touch creates a 0-size,0-replica file in the EOS namespace.
func (c *Client) Touch(ctx context.Context, auth eosclient.Authorization, path string) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "Touch").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("")
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, auth, "")
if err != nil {
return err
}
msg := new(erpc.NSRequest_TouchRequest)
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
rq.Command = &erpc.NSRequest_Touch{Touch: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
log.Error().Str("func", "Touch").Str("path", path).Str("err", e.Error()).Msg("")
return e
}
if resp == nil {
return errtypes.InternalError(fmt.Sprintf("nil response for uid: '%s' path: '%s'", auth.Role.UID, path))
}
log.Debug().Str("func", "Touch").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
return err
}
// Chown given path.
func (c *Client) Chown(ctx context.Context, auth, chownAuth eosclient.Authorization, path string) error {
log := appctx.GetLogger(ctx)
log.Info().Str("func", "Chown").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("chownuid,chowngid", chownAuth.Role.UID+","+chownAuth.Role.GID).Str("path", path).Msg("")
// Initialize the common fields of the NSReq
rq, err := c.initNSRequest(ctx, auth, "")
if err != nil {
return err
}
msg := new(erpc.NSRequest_ChownRequest)
msg.Owner = new(erpc.RoleId)
uid, gid, err := utils.ExtractUidGid(chownAuth)
if err == nil {
msg.Owner.Uid = uid
msg.Owner.Gid = gid
}
msg.Id = new(erpc.MDId)
msg.Id.Path = []byte(path)
rq.Command = &erpc.NSRequest_Chown{Chown: msg}
// Now send the req and see what happens
resp, err := c.cl.Exec(appctx.ContextGetClean(ctx), rq)
e := c.getRespError(resp, err)
if e != nil {
log.Error().Str("func", "Chown").Str("path", path).Str("err", e.Error()).Msg("")
return e
}
if resp == nil {
return errtypes.InternalError(fmt.Sprintf("nil response for uid: '%s' chownuid: '%s' path: '%s'", auth.Role.UID, chownAuth.Role.UID, path))
}
log.Debug().Str("func", "Chown").Str("path", path).Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("chownuid,chowngid", chownAuth.Role.UID+","+chownAuth.Role.GID).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response")
return err