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,
232 if err := CreateGroup(cfg, &parentGroup, groupData); err != nil {
233 return fmt.Errorf("error creating system user owned group named %q: %s", groupData["name"], err)
235 } else if len(gl.Items) == 1 {
236 // Default parent group found.
237 parentGroup = gl.Items[0]
239 // This should never happen, as there's an unique index for
240 // (owner_uuid, name) on groups.
241 return fmt.Errorf("bug: found %d groups owned by system user and named %q", len(gl.Items), cfg.ParentGroupName)
243 cfg.ParentGroupUUID = parentGroup.UUID
245 // UUID provided. Check if exists and if it's owned by system user
246 if err := GetGroup(cfg, &parentGroup, cfg.ParentGroupUUID); err != nil {
247 return fmt.Errorf("error searching for parent group with UUID %q: %s", cfg.ParentGroupUUID, err)
249 if parentGroup.OwnerUUID != cfg.SysUserUUID {
250 return fmt.Errorf("parent group %q (%s) must be owned by system user", parentGroup.Name, cfg.ParentGroupUUID)
256 // GetConfig sets up a ConfigParams struct
257 func GetConfig() (config ConfigParams, err error) {
258 config.ParentGroupName = "Externally synchronized groups"
261 err = ParseFlags(&config)
266 // Arvados Client setup
267 config.Client = arvados.NewClientFromEnv()
269 // Check current user permissions & get System user's UUID
270 u, err := config.Client.CurrentUser()
272 return config, fmt.Errorf("error getting the current user: %s", err)
274 if !u.IsActive || !u.IsAdmin {
275 return config, fmt.Errorf("current user (%s) is not an active admin user", u.UUID)
277 config.SysUserUUID = u.UUID[:12] + "000000000000000"
279 // Set up remote groups' parent
280 if err = SetParentGroup(&config); err != nil {
287 func doMain(cfg *ConfigParams) error {
288 // Try opening the input file early, just in case there's a problem.
289 f, err := os.Open(cfg.Path)
291 return fmt.Errorf("%s", err)
295 log.Printf("%s %s started. Using %q as users id and parent group UUID %q", os.Args[0], version, cfg.UserID, cfg.ParentGroupUUID)
297 // Get the complete user list to minimize API Server requests
298 allUsers := make(map[string]arvados.User)
299 userIDToUUID := make(map[string]string) // Index by email or username
300 results, err := GetAll(cfg.Client, "users", arvados.ResourceListParams{}, &UserList{})
302 return fmt.Errorf("error getting user list: %s", err)
304 log.Printf("Found %d users", len(results))
305 for _, item := range results {
306 u := item.(arvados.User)
308 uID, err := GetUserID(u, cfg.UserID)
312 userIDToUUID[uID] = u.UUID
314 log.Printf("Seen user %q (%s)", u.Username, u.UUID)
318 // Get remote groups and their members
319 remoteGroups, groupNameToUUID, err := GetRemoteGroups(cfg, allUsers)
323 log.Printf("Found %d remote groups", len(remoteGroups))
325 for groupUUID := range remoteGroups {
326 log.Printf("- Group %q: %d users", remoteGroups[groupUUID].Group.Name, len(remoteGroups[groupUUID].PreviousMembers))
330 membershipsRemoved := 0
333 groupsCreated, membershipsAdded, membershipsSkipped, err := ProcessFile(cfg, f, userIDToUUID, groupNameToUUID, remoteGroups, allUsers)
338 // Remove previous members not listed on this run
339 for groupUUID := range remoteGroups {
340 gi := remoteGroups[groupUUID]
341 evictedMemberPerms := subtract(gi.PreviousMembers, gi.CurrentMembers)
342 groupName := gi.Group.Name
343 if len(evictedMemberPerms) > 0 {
344 log.Printf("Removing permissions from %d users on group %q", len(evictedMemberPerms), groupName)
346 for member := range evictedMemberPerms {
348 completeMembershipRemoval := false
349 if _, ok := gi.CurrentMembers[member]; !ok {
350 completeMembershipRemoval = true
353 // Collect which user->group permission links should be removed
354 for p := range evictedMemberPerms[member] {
355 if evictedMemberPerms[member][p] {
356 perms = append(perms, p)
359 membershipsRemoved += len(perms)
361 if err := RemoveMemberLinksFromGroup(cfg, allUsers[userIDToUUID[member]],
362 perms, completeMembershipRemoval, gi.Group); err != nil {
367 log.Printf("Groups created: %d. Memberships added: %d, removed: %d, skipped: %d", groupsCreated, membershipsAdded, membershipsRemoved, membershipsSkipped)
372 // ProcessFile reads the CSV file and process every record
376 userIDToUUID map[string]string,
377 groupNameToUUID map[string]string,
378 remoteGroups map[string]*GroupInfo,
379 allUsers map[string]arvados.User,
380 ) (groupsCreated, membersAdded, membersSkipped int, err error) {
382 csvReader := csv.NewReader(f)
383 // Allow variable number of fields.
384 csvReader.FieldsPerRecord = -1
386 record, e := csvReader.Read()
392 err = fmt.Errorf("error parsing %q, line %d", cfg.Path, lineNo)
395 // Only allow 2 or 3 fields per record for backwards compatibility.
396 if len(record) < 2 || len(record) > 3 {
397 err = fmt.Errorf("error parsing %q, line %d: found %d fields but only 2 or 3 are allowed", cfg.Path, lineNo, len(record))
400 groupName := strings.TrimSpace(record[0])
401 groupMember := strings.TrimSpace(record[1]) // User ID (username or email)
402 groupPermission := "can_write"
403 if len(record) == 3 {
404 groupPermission = strings.ToLower(record[2])
406 if groupName == "" || groupMember == "" || groupPermission == "" {
407 log.Printf("Warning: CSV record has at least one empty field (%s, %s, %s). Skipping", groupName, groupMember, groupPermission)
411 if !(groupPermission == "can_read" || groupPermission == "can_write" || groupPermission == "can_manage") {
412 log.Printf("Warning: 3rd field should be 'can_read', 'can_write' or 'can_manage'. Found: %q at line %d, skipping.", groupPermission, lineNo)
416 if _, found := userIDToUUID[groupMember]; !found {
417 // User not present on the system, skip.
418 log.Printf("Warning: there's no user with %s %q on the system, skipping.", cfg.UserID, groupMember)
422 if _, found := groupNameToUUID[groupName]; !found {
423 // Group doesn't exist, create it before continuing
425 log.Printf("Remote group %q not found, creating...", groupName)
427 var newGroup arvados.Group
428 groupData := map[string]string{
430 "owner_uuid": cfg.ParentGroupUUID,
431 "group_class": "role",
433 if e := CreateGroup(cfg, &newGroup, groupData); e != nil {
434 err = fmt.Errorf("error creating group named %q: %s", groupName, err)
437 // Update cached group data
438 groupNameToUUID[groupName] = newGroup.UUID
439 remoteGroups[newGroup.UUID] = &GroupInfo{
441 PreviousMembers: make(map[string]GroupPermissions),
442 CurrentMembers: make(map[string]GroupPermissions),
446 // Both group & user exist, check if user is a member
447 groupUUID := groupNameToUUID[groupName]
448 gi := remoteGroups[groupUUID]
449 if !gi.PreviousMembers[groupMember][groupPermission] && !gi.CurrentMembers[groupMember][groupPermission] {
451 log.Printf("Adding %q to group %q", groupMember, groupName)
453 // User permissionwasn't there, but should be. Avoid duplicating the
454 // group->user link when necessary.
455 createG2ULink := true
456 if _, ok := gi.PreviousMembers[groupMember]; ok {
457 createG2ULink = false // User is already member of the group
459 if e := AddMemberToGroup(cfg, allUsers[userIDToUUID[groupMember]], gi.Group, groupPermission, createG2ULink); e != nil {
465 if _, ok := gi.CurrentMembers[groupMember]; ok {
466 gi.CurrentMembers[groupMember][groupPermission] = true
468 gi.CurrentMembers[groupMember] = GroupPermissions{groupPermission: true}
475 // GetAll : Adds all objects of type 'resource' to the 'allItems' list
476 func GetAll(c *arvados.Client, res string, params arvados.ResourceListParams, page resourceList) (allItems []interface{}, err error) {
477 // Use the maximum page size the server allows
479 params.Limit = &limit
481 params.Order = "uuid"
483 if err = GetResourceList(c, &page, res, params); err != nil {
486 // Have we finished paging?
490 for _, i := range page.GetItems() {
491 allItems = append(allItems, i)
493 params.Offset += page.Len()
498 func subtract(setA map[string]GroupPermissions, setB map[string]GroupPermissions) map[string]GroupPermissions {
499 result := make(map[string]GroupPermissions)
500 for element := range setA {
501 if _, ok := setB[element]; !ok {
502 result[element] = setA[element]
504 for perm := range setA[element] {
505 if _, ok := setB[element][perm]; !ok {
506 result[element] = GroupPermissions{perm: true}
514 func jsonReader(rscName string, ob interface{}) io.Reader {
515 j, err := json.Marshal(ob)
520 v[rscName] = []string{string(j)}
521 return bytes.NewBufferString(v.Encode())
524 // GetRemoteGroups fetches all remote groups with their members
525 func GetRemoteGroups(cfg *ConfigParams, allUsers map[string]arvados.User) (remoteGroups map[string]*GroupInfo, groupNameToUUID map[string]string, err error) {
526 remoteGroups = make(map[string]*GroupInfo)
527 groupNameToUUID = make(map[string]string) // Index by group name
529 params := arvados.ResourceListParams{
530 Filters: []arvados.Filter{{
533 Operand: cfg.ParentGroupUUID,
536 results, err := GetAll(cfg.Client, "groups", params, &GroupList{})
538 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting remote groups: %s", err)
540 for _, item := range results {
541 group := item.(arvados.Group)
542 // Group -> User filter
543 g2uFilter := arvados.ResourceListParams{
544 Filters: []arvados.Filter{{
547 Operand: cfg.SysUserUUID,
551 Operand: "permission",
563 Operand: "arvados#user",
566 // User -> Group filter
567 u2gFilter := arvados.ResourceListParams{
568 Filters: []arvados.Filter{{
571 Operand: cfg.SysUserUUID,
575 Operand: "permission",
579 Operand: []string{"can_read", "can_write", "can_manage"},
587 Operand: "arvados#user",
590 g2uLinks, err := GetAll(cfg.Client, "links", g2uFilter, &LinkList{})
592 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting group->user 'can_read' links for group %q: %s", group.Name, err)
594 u2gLinks, err := GetAll(cfg.Client, "links", u2gFilter, &LinkList{})
596 return remoteGroups, groupNameToUUID, fmt.Errorf("error getting user->group links for group %q: %s", group.Name, err)
598 // Build a list of user ids (email or username) belonging to this group.
599 membersSet := make(map[string]GroupPermissions)
600 u2gLinkSet := make(map[string]GroupPermissions)
601 for _, l := range u2gLinks {
602 link := l.(arvados.Link)
603 // Also save the member's group access level.
604 if _, ok := u2gLinkSet[link.TailUUID]; ok {
605 u2gLinkSet[link.TailUUID][link.Name] = true
607 u2gLinkSet[link.TailUUID] = GroupPermissions{link.Name: true}
610 for _, item := range g2uLinks {
611 link := item.(arvados.Link)
612 // We may have received an old link pointing to a removed account.
613 if _, found := allUsers[link.HeadUUID]; !found {
616 // The matching User -> Group link may not exist if the link
617 // creation failed on a previous run. If that's the case, don't
618 // include this account on the "previous members" list.
619 if _, found := u2gLinkSet[link.HeadUUID]; !found {
622 memberID, err := GetUserID(allUsers[link.HeadUUID], cfg.UserID)
624 return remoteGroups, groupNameToUUID, err
626 membersSet[memberID] = u2gLinkSet[link.HeadUUID]
628 remoteGroups[group.UUID] = &GroupInfo{
630 PreviousMembers: membersSet,
631 CurrentMembers: make(map[string]GroupPermissions),
633 groupNameToUUID[group.Name] = group.UUID
635 return remoteGroups, groupNameToUUID, nil
638 // RemoveMemberLinksFromGroup remove all links related to the membership
639 func RemoveMemberLinksFromGroup(cfg *ConfigParams, user arvados.User, linkNames []string, completeRemoval bool, group arvados.Group) error {
641 log.Printf("Getting group membership links for user %q (%s) on group %q (%s)", user.Username, user.UUID, group.Name, group.UUID)
643 var links []interface{}
644 var filters [][]arvados.Filter
646 // Search for all group<->user links (both ways)
647 filters = [][]arvados.Filter{
652 Operand: "permission",
666 Operand: "permission",
678 // Search only for the requested Group <- User permission links
679 filters = [][]arvados.Filter{
683 Operand: "permission",
700 for _, filterset := range filters {
701 l, err := GetAll(cfg.Client, "links", arvados.ResourceListParams{Filters: filterset}, &LinkList{})
703 userID, _ := GetUserID(user, cfg.UserID)
704 return fmt.Errorf("error getting links needed to remove user %q from group %q: %s", userID, group.Name, err)
706 for _, link := range l {
707 links = append(links, link)
710 for _, item := range links {
711 link := item.(arvados.Link)
712 userID, _ := GetUserID(user, cfg.UserID)
714 log.Printf("Removing %q permission link for %q on group %q", link.Name, userID, group.Name)
716 if err := DeleteLink(cfg, link.UUID); err != nil {
717 return fmt.Errorf("error removing user %q from group %q: %s", userID, group.Name, err)
723 // AddMemberToGroup create membership links
724 func AddMemberToGroup(cfg *ConfigParams, user arvados.User, group arvados.Group, perm string, createG2ULink bool) error {
725 var newLink arvados.Link
726 var linkData map[string]string
728 linkData = map[string]string{
729 "owner_uuid": cfg.SysUserUUID,
730 "link_class": "permission",
732 "tail_uuid": group.UUID,
733 "head_uuid": user.UUID,
735 if err := CreateLink(cfg, &newLink, linkData); err != nil {
736 userID, _ := GetUserID(user, cfg.UserID)
737 return fmt.Errorf("error adding group %q -> user %q read permission: %s", group.Name, userID, err)
740 linkData = map[string]string{
741 "owner_uuid": cfg.SysUserUUID,
742 "link_class": "permission",
744 "tail_uuid": user.UUID,
745 "head_uuid": group.UUID,
747 if err := CreateLink(cfg, &newLink, linkData); err != nil {
748 userID, _ := GetUserID(user, cfg.UserID)
749 return fmt.Errorf("error adding user %q -> group %q %s permission: %s", userID, group.Name, perm, err)
754 // CreateGroup creates a group with groupData parameters, assigns it to dst
755 func CreateGroup(cfg *ConfigParams, dst *arvados.Group, groupData map[string]string) error {
756 return cfg.Client.RequestAndDecode(dst, "POST", "/arvados/v1/groups", jsonReader("group", groupData), nil)
759 // GetGroup fetches a group by its UUID
760 func GetGroup(cfg *ConfigParams, dst *arvados.Group, groupUUID string) error {
761 return cfg.Client.RequestAndDecode(&dst, "GET", "/arvados/v1/groups/"+groupUUID, nil, nil)
764 // CreateLink creates a link with linkData parameters, assigns it to dst
765 func CreateLink(cfg *ConfigParams, dst *arvados.Link, linkData map[string]string) error {
766 return cfg.Client.RequestAndDecode(dst, "POST", "/arvados/v1/links", jsonReader("link", linkData), nil)
769 // DeleteLink deletes a link by its UUID
770 func DeleteLink(cfg *ConfigParams, linkUUID string) error {
772 return fmt.Errorf("cannot delete link with invalid UUID: %q", linkUUID)
774 return cfg.Client.RequestAndDecode(&arvados.Link{}, "DELETE", "/arvados/v1/links/"+linkUUID, nil, nil)
777 // GetResourceList fetches res list using params
778 func GetResourceList(c *arvados.Client, dst *resourceList, res string, params interface{}) error {
779 return c.RequestAndDecode(dst, "GET", "/arvados/v1/"+res, nil, params)