1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/sdk/go/arvados"
24 type resourceList interface {
26 GetItems() []interface{}
29 // GroupPermissions maps permission levels on groups (can_read, can_write, can_manage)
30 type GroupPermissions map[string]bool
32 // GroupInfo tracks previous and current member's permissions on a particular Group
33 type GroupInfo struct {
35 PreviousMembers map[string]GroupPermissions
36 CurrentMembers map[string]GroupPermissions
39 // GetUserID returns the correct user id value depending on the selector
40 func GetUserID(u arvados.User, idSelector string) (string, error) {
45 return u.Username, nil
47 return "", fmt.Errorf("cannot identify user by %q selector", idSelector)
51 // UserList implements resourceList interface
52 type UserList struct {
56 // Len returns the amount of items this list holds
57 func (l UserList) Len() int {
61 // GetItems returns the list of items
62 func (l UserList) GetItems() (out []interface{}) {
63 for _, item := range l.Items {
64 out = append(out, item)
69 // GroupList implements resourceList interface
70 type GroupList struct {
74 // Len returns the amount of items this list holds
75 func (l GroupList) Len() int {
79 // GetItems returns the list of items
80 func (l GroupList) GetItems() (out []interface{}) {
81 for _, item := range l.Items {
82 out = append(out, item)
87 // LinkList implements resourceList interface
88 type LinkList struct {
92 // Len returns the amount of items this list holds
93 func (l LinkList) Len() int {
97 // GetItems returns the list of items
98 func (l LinkList) GetItems() (out []interface{}) {
99 for _, item := range l.Items {
100 out = append(out, item)
106 // Parse & validate arguments, set up arvados client.
107 cfg, err := GetConfig()
109 log.Fatalf("%v", err)
112 if err := doMain(&cfg); err != nil {
113 log.Fatalf("%v", err)
117 // ConfigParams holds configuration data for this tool
118 type ConfigParams struct {
122 ParentGroupUUID string
123 ParentGroupName string
125 Client *arvados.Client
128 // ParseFlags parses and validates command line arguments
129 func ParseFlags(config *ConfigParams) error {
130 // Acceptable attributes to identify a user on the CSV file
131 userIDOpts := map[string]bool{
132 "email": true, // default
136 flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
138 // Set up usage message
139 flags.Usage = func() {
140 usageStr := `Synchronize remote groups into Arvados from a CSV format file with 3 columns:
142 * 2nd: User identifier
143 * 3rd (Optional): User permission on the group: can_read, can_write or can_manage. (Default: can_write)`
144 fmt.Fprintf(os.Stderr, "%s\n\n", usageStr)
145 fmt.Fprintf(os.Stderr, "Usage:\n%s [OPTIONS] <input-file.csv>\n\n", os.Args[0])
146 fmt.Fprintf(os.Stderr, "Options:\n")
147 flags.PrintDefaults()
150 // Set up option flags
151 userID := flags.String(
154 "Attribute by which every user is identified. Valid values are: email and username.")
155 verbose := flags.Bool(
158 "Log informational messages. Off by default.")
159 getVersion := flags.Bool(
162 "Print version information and exit.")
163 parentGroupUUID := flags.String(
166 "Use given group UUID as a parent for the remote groups. Should be owned by the system user. If not specified, a group named '"+config.ParentGroupName+"' will be used (and created if nonexistant).")
168 // Parse args; omit the first arg which is the command name
169 flags.Parse(os.Args[1:])
171 // Print version information if requested
173 fmt.Printf("%s %s\n", os.Args[0], version)
177 // Input file as a required positional argument
178 if flags.NArg() == 0 {
179 return fmt.Errorf("please provide a path to an input file")
181 srcPath := &os.Args[flags.NFlag()+1]
185 return fmt.Errorf("input file path invalid")
187 if !userIDOpts[*userID] {
189 for opt := range userIDOpts {
190 options = append(options, opt)
192 return fmt.Errorf("user ID must be one of: %s", strings.Join(options, ", "))
195 config.Path = *srcPath
196 config.ParentGroupUUID = *parentGroupUUID
197 config.UserID = *userID
198 config.Verbose = *verbose
203 // SetParentGroup finds/create parent group of all remote groups
204 func SetParentGroup(cfg *ConfigParams) error {
205 var parentGroup arvados.Group
206 if cfg.ParentGroupUUID == "" {
207 // UUID not provided, search for preexisting parent group
209 params := arvados.ResourceListParams{
210 Filters: []arvados.Filter{{
213 Operand: cfg.ParentGroupName,
217 Operand: cfg.SysUserUUID,
220 if err := cfg.Client.RequestAndDecode(&gl, "GET", "/arvados/v1/groups", nil, params); err != nil {
221 return fmt.Errorf("error searching for parent group: %s", err)
223 if len(gl.Items) == 0 {
224 // Default parent group does not exist, create it.
226 log.Println("Default parent group not found, creating...")
228 groupData := map[string]string{
229 "name": cfg.ParentGroupName,
230 "owner_uuid": cfg.SysUserUUID,
231 "group_class": "role",
233 if err := CreateGroup(cfg, &parentGroup, groupData); err != nil {
234 return fmt.Errorf("error creating system user owned group named %q: %s", groupData["name"], err)
236 } else if len(gl.Items) == 1 {
237 // Default parent group found.
238 parentGroup = gl.Items[0]
240 // This should never happen, as there's an unique index for
241 // (owner_uuid, name) on groups.
242 return fmt.Errorf("bug: found %d groups owned by system user and named %q", len(gl.Items), cfg.ParentGroupName)
244 cfg.ParentGroupUUID = parentGroup.UUID
246 // UUID provided. Check if exists and if it's owned by system user
247 if err := GetGroup(cfg, &parentGroup, cfg.ParentGroupUUID); err != nil {
248 return fmt.Errorf("error searching for parent group with UUID %q: %s", cfg.ParentGroupUUID, err)
250 if parentGroup.OwnerUUID != cfg.SysUserUUID {
251 return fmt.Errorf("parent group %q (%s) must be owned by system user", parentGroup.Name, cfg.ParentGroupUUID)
257 // GetConfig sets up a ConfigParams struct
258 func GetConfig() (config ConfigParams, err error) {
259 config.ParentGroupName = "Externally synchronized groups"
262 err = ParseFlags(&config)
267 // Arvados Client setup
268 config.Client = arvados.NewClientFromEnv()
270 // Check current user permissions & get System user's UUID
271 u, err := config.Client.CurrentUser()
273 return config, fmt.Errorf("error getting the current user: %s", err)
275 if !u.IsActive || !u.IsAdmin {
276 return config, fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
279 var ac struct{ ClusterID string }
280 err = config.Client.RequestAndDecode(&ac, "GET", "arvados/v1/config", nil, nil)
282 return config, fmt.Errorf("error getting the exported config: %s", err)
284 config.SysUserUUID = ac.ClusterID + "-tpzed-000000000000000"
286 // Set up remote groups' parent
287 if err = SetParentGroup(&config); err != nil {
294 func doMain(cfg *ConfigParams) error {
295 // Try opening the input file early, just in case there's a problem.
296 f, err := os.Open(cfg.Path)
298 return fmt.Errorf("%s", err)
302 log.Printf("%s %s started. Using %q as users id and parent group UUID %q", os.Args[0], version, cfg.UserID, cfg.ParentGroupUUID)
304 // Get the complete user list to minimize API Server requests
305 allUsers := make(map[string]arvados.User)
306 userIDToUUID := make(map[string]string) // Index by email or username
307 results, err := GetAll(cfg.Client, "users", arvados.ResourceListParams{}, &UserList{})
309 return fmt.Errorf("error getting user list: %s", err)
311 log.Printf("Found %d users", len(results))
312 for _, item := range results {
313 u := item.(arvados.User)
315 uID, err := GetUserID(u, cfg.UserID)
319 userIDToUUID[uID] = u.UUID
321 log.Printf("Seen user %q (%s)", u.Username, u.UUID)
325 // Get remote groups and their members
326 remoteGroups, groupNameToUUID, err := GetRemoteGroups(cfg, allUsers)
330 log.Printf("Found %d remote groups", len(remoteGroups))
332 for groupUUID := range remoteGroups {
333 log.Printf("- Group %q: %d users", remoteGroups[groupUUID].Group.Name, len(remoteGroups[groupUUID].PreviousMembers))
337 membershipsRemoved := 0
340 groupsCreated, membershipsAdded, membershipsSkipped, err := ProcessFile(cfg, f, userIDToUUID, groupNameToUUID, remoteGroups, allUsers)
345 // Remove previous members not listed on this run
346 for groupUUID := range remoteGroups {
347 gi := remoteGroups[groupUUID]
348 evictedMemberPerms := subtract(gi.PreviousMembers, gi.CurrentMembers)
349 groupName := gi.Group.Name
350 if len(evictedMemberPerms) > 0 {
351 log.Printf("Removing permissions from %d users on group %q", len(evictedMemberPerms), groupName)
353 for member := range evictedMemberPerms {
355 completeMembershipRemoval := false
356 if _, ok := gi.CurrentMembers[member]; !ok {
357 completeMembershipRemoval = true
360 // Collect which user->group permission links should be removed
361 for p := range evictedMemberPerms[member] {
362 if evictedMemberPerms[member][p] {
363 perms = append(perms, p)
366 membershipsRemoved += len(perms)
368 if err := RemoveMemberLinksFromGroup(cfg, allUsers[userIDToUUID[member]],
369 perms, completeMembershipRemoval, gi.Group); err != nil {
374 log.Printf("Groups created: %d. Memberships added: %d, removed: %d, skipped: %d", groupsCreated, membershipsAdded, membershipsRemoved, membershipsSkipped)
379 // ProcessFile reads the CSV file and process every record
383 userIDToUUID map[string]string,
384 groupNameToUUID map[string]string,
385 remoteGroups map[string]*GroupInfo,
386 allUsers map[string]arvados.User,
387 ) (groupsCreated, membersAdded, membersSkipped int, err error) {
389 csvReader := csv.NewReader(f)
390 // Allow variable number of fields.
391 csvReader.FieldsPerRecord = -1
393 record, e := csvReader.Read()
399 err = fmt.Errorf("error parsing %q, line %d", cfg.Path, lineNo)
402 // Only allow 2 or 3 fields per record for backwards compatibility.
403 if len(record) < 2 || len(record) > 3 {
404 err = fmt.Errorf("error parsing %q, line %d: found %d fields but only 2 or 3 are allowed", cfg.Path, lineNo, len(record))
407 groupName := strings.TrimSpace(record[0])
408 groupMember := strings.TrimSpace(record[1]) // User ID (username or email)
409 groupPermission := "can_write"
410 if len(record) == 3 {
411 groupPermission = strings.ToLower(record[2])
413 if groupName == "" || groupMember == "" || groupPermission == "" {
414 log.Printf("Warning: CSV record has at least one empty field (%s, %s, %s). Skipping", groupName, groupMember, groupPermission)
418 if !(groupPermission == "can_read" || groupPermission == "can_write" || groupPermission == "can_manage") {
419 log.Printf("Warning: 3rd field should be 'can_read', 'can_write' or 'can_manage'. Found: %q at line %d, skipping.", groupPermission, lineNo)
423 if _, found := userIDToUUID[groupMember]; !found {
424 // User not present on the system, skip.
425 log.Printf("Warning: there's no user with %s %q on the system, skipping.", cfg.UserID, groupMember)
429 if _, found := groupNameToUUID[groupName]; !found {
430 // Group doesn't exist, create it before continuing
432 log.Printf("Remote group %q not found, creating...", groupName)
434 var newGroup arvados.Group
435 groupData := map[string]string{
437 "owner_uuid": cfg.ParentGroupUUID,
438 "group_class": "role",
440 if e := CreateGroup(cfg, &newGroup, groupData); e != nil {
441 err = fmt.Errorf("error creating group named %q: %s", groupName, e)
444 // Update cached group data
445 groupNameToUUID[groupName] = newGroup.UUID
446 remoteGroups[newGroup.UUID] = &GroupInfo{
448 PreviousMembers: make(map[string]GroupPermissions),
449 CurrentMembers: make(map[string]GroupPermissions),
453 // Both group & user exist, check if user is a member
454 groupUUID := groupNameToUUID[groupName]
455 gi := remoteGroups[groupUUID]
456 if !gi.PreviousMembers[groupMember][groupPermission] && !gi.CurrentMembers[groupMember][groupPermission] {
458 log.Printf("Adding %q to group %q", groupMember, groupName)
460 // User permissionwasn't there, but should be. Avoid duplicating the
461 // group->user link when necessary.
462 createG2ULink := true
463 if _, ok := gi.PreviousMembers[groupMember]; ok {
464 createG2ULink = false // User is already member of the group
466 if e := AddMemberToGroup(cfg, allUsers[userIDToUUID[groupMember]], gi.Group, groupPermission, createG2ULink); e != nil {
472 if _, ok := gi.CurrentMembers[groupMember]; ok {
473 gi.CurrentMembers[groupMember][groupPermission] = true
475 gi.CurrentMembers[groupMember] = GroupPermissions{groupPermission: true}
482 // GetAll : Adds all objects of type 'resource' to the 'allItems' list
483 func GetAll(c *arvados.Client, res string, params arvados.ResourceListParams, page resourceList) (allItems []interface{}, err error) {
484 // Use the maximum page size the server allows
486 params.Limit = &limit
488 params.Order = "uuid"
490 if err = GetResourceList(c, &page, res, params); err != nil {
493 // Have we finished paging?
497 for _, i := range page.GetItems() {
498 allItems = append(allItems, i)
500 params.Offset += page.Len()
505 func subtract(setA map[string]GroupPermissions, setB map[string]GroupPermissions) map[string]GroupPermissions {
506 result := make(map[string]GroupPermissions)
507 for element := range setA {
508 if _, ok := setB[element]; !ok {
509 result[element] = setA[element]
511 for perm := range setA[element] {
512 if _, ok := setB[element][perm]; !ok {
513 result[element] = GroupPermissions{perm: true}
521 func jsonReader(rscName string, ob interface{}) io.Reader {
522 j, err := json.Marshal(ob)
527 v[rscName] = []string{string(j)}
528 return bytes.NewBufferString(v.Encode())
531 // GetRemoteGroups fetches all remote groups with their members
532 func GetRemoteGroups(cfg *ConfigParams, allUsers map[string]arvados.User) (remoteGroups map[string]*GroupInfo, groupNameToUUID map[string]string, err error) {
533 remoteGroups = make(map[string]*GroupInfo)
534 groupNameToUUID = make(map[string]string) // Index by group name
536 params := arvados.ResourceListParams{
537 Filters: []arvados.Filter{{
540 Operand: cfg.ParentGroupUUID,
543 results, err := GetAll(cfg.Client, "links", params, &LinkList{})
545 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting remote groups: %s", err)
547 for _, item := range results {
548 var group arvados.Group
549 err = GetGroup(cfg, &group, item.(arvados.Link).HeadUUID)
551 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting remote group: %s", err)
553 // Group -> User filter
554 g2uFilter := arvados.ResourceListParams{
555 Filters: []arvados.Filter{{
558 Operand: cfg.SysUserUUID,
562 Operand: "permission",
574 Operand: "arvados#user",
577 // User -> Group filter
578 u2gFilter := arvados.ResourceListParams{
579 Filters: []arvados.Filter{{
582 Operand: cfg.SysUserUUID,
586 Operand: "permission",
590 Operand: []string{"can_read", "can_write", "can_manage"},
598 Operand: "arvados#user",
601 g2uLinks, err := GetAll(cfg.Client, "links", g2uFilter, &LinkList{})
603 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting group->user 'can_read' links for group %q: %s", group.Name, err)
605 u2gLinks, err := GetAll(cfg.Client, "links", u2gFilter, &LinkList{})
607 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting user->group links for group %q: %s", group.Name, err)
609 // Build a list of user ids (email or username) belonging to this group.
610 membersSet := make(map[string]GroupPermissions)
611 u2gLinkSet := make(map[string]GroupPermissions)
612 for _, l := range u2gLinks {
613 link := l.(arvados.Link)
614 // Also save the member's group access level.
615 if _, ok := u2gLinkSet[link.TailUUID]; ok {
616 u2gLinkSet[link.TailUUID][link.Name] = true
618 u2gLinkSet[link.TailUUID] = GroupPermissions{link.Name: true}
621 for _, item := range g2uLinks {
622 link := item.(arvados.Link)
623 // We may have received an old link pointing to a removed account.
624 if _, found := allUsers[link.HeadUUID]; !found {
627 // The matching User -> Group link may not exist if the link
628 // creation failed on a previous run. If that's the case, don't
629 // include this account on the "previous members" list.
630 if _, found := u2gLinkSet[link.HeadUUID]; !found {
633 memberID, err := GetUserID(allUsers[link.HeadUUID], cfg.UserID)
635 return remoteGroups, groupNameToUUID, err
637 membersSet[memberID] = u2gLinkSet[link.HeadUUID]
639 remoteGroups[group.UUID] = &GroupInfo{
641 PreviousMembers: membersSet,
642 CurrentMembers: make(map[string]GroupPermissions),
644 groupNameToUUID[group.Name] = group.UUID
646 return remoteGroups, groupNameToUUID, nil
649 // RemoveMemberLinksFromGroup remove all links related to the membership
650 func RemoveMemberLinksFromGroup(cfg *ConfigParams, user arvados.User, linkNames []string, completeRemoval bool, group arvados.Group) error {
652 log.Printf("Getting group membership links for user %q (%s) on group %q (%s)", user.Username, user.UUID, group.Name, group.UUID)
654 var links []interface{}
655 var filters [][]arvados.Filter
657 // Search for all group<->user links (both ways)
658 filters = [][]arvados.Filter{
663 Operand: "permission",
677 Operand: "permission",
689 // Search only for the requested Group <- User permission links
690 filters = [][]arvados.Filter{
694 Operand: "permission",
711 for _, filterset := range filters {
712 l, err := GetAll(cfg.Client, "links", arvados.ResourceListParams{Filters: filterset}, &LinkList{})
714 userID, _ := GetUserID(user, cfg.UserID)
715 return fmt.Errorf("error getting links needed to remove user %q from group %q: %s", userID, group.Name, err)
717 for _, link := range l {
718 links = append(links, link)
721 for _, item := range links {
722 link := item.(arvados.Link)
723 userID, _ := GetUserID(user, cfg.UserID)
725 log.Printf("Removing %q permission link for %q on group %q", link.Name, userID, group.Name)
727 if err := DeleteLink(cfg, link.UUID); err != nil {
728 return fmt.Errorf("error removing user %q from group %q: %s", userID, group.Name, err)
734 // AddMemberToGroup create membership links
735 func AddMemberToGroup(cfg *ConfigParams, user arvados.User, group arvados.Group, perm string, createG2ULink bool) error {
736 var newLink arvados.Link
737 var linkData map[string]string
739 linkData = map[string]string{
740 "owner_uuid": cfg.SysUserUUID,
741 "link_class": "permission",
743 "tail_uuid": group.UUID,
744 "head_uuid": user.UUID,
746 if err := CreateLink(cfg, &newLink, linkData); err != nil {
747 userID, _ := GetUserID(user, cfg.UserID)
748 return fmt.Errorf("error adding group %q -> user %q read permission: %s", group.Name, userID, err)
751 linkData = map[string]string{
752 "owner_uuid": cfg.SysUserUUID,
753 "link_class": "permission",
755 "tail_uuid": user.UUID,
756 "head_uuid": group.UUID,
758 if err := CreateLink(cfg, &newLink, linkData); err != nil {
759 userID, _ := GetUserID(user, cfg.UserID)
760 return fmt.Errorf("error adding user %q -> group %q %s permission: %s", userID, group.Name, perm, err)
765 // CreateGroup creates a group with groupData parameters, assigns it to dst
766 func CreateGroup(cfg *ConfigParams, dst *arvados.Group, groupData map[string]string) error {
767 return cfg.Client.RequestAndDecode(dst, "POST", "/arvados/v1/groups", jsonReader("group", groupData), nil)
770 // GetGroup fetches a group by its UUID
771 func GetGroup(cfg *ConfigParams, dst *arvados.Group, groupUUID string) error {
772 return cfg.Client.RequestAndDecode(&dst, "GET", "/arvados/v1/groups/"+groupUUID, nil, nil)
775 // CreateLink creates a link with linkData parameters, assigns it to dst
776 func CreateLink(cfg *ConfigParams, dst *arvados.Link, linkData map[string]string) error {
777 return cfg.Client.RequestAndDecode(dst, "POST", "/arvados/v1/links", jsonReader("link", linkData), nil)
780 // DeleteLink deletes a link by its UUID
781 func DeleteLink(cfg *ConfigParams, linkUUID string) error {
783 return fmt.Errorf("cannot delete link with invalid UUID: %q", linkUUID)
785 return cfg.Client.RequestAndDecode(&arvados.Link{}, "DELETE", "/arvados/v1/links/"+linkUUID, nil, nil)
788 // GetResourceList fetches res list using params
789 func GetResourceList(c *arvados.Client, dst *resourceList, res string, params interface{}) error {
790 return c.RequestAndDecode(dst, "GET", "/arvados/v1/"+res, nil, params)