1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/cmd"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
26 type resourceList interface {
28 GetItems() []interface{}
31 // UserList implements resourceList interface
32 type UserList struct {
36 // Len returns the amount of items this list holds
37 func (l UserList) Len() int {
41 // GetItems returns the list of items
42 func (l UserList) GetItems() (out []interface{}) {
43 for _, item := range l.Items {
44 out = append(out, item)
50 cfg, err := GetConfig()
55 if err := doMain(&cfg); err != nil {
60 type ConfigParams struct {
61 Client *arvados.Client
63 CurrentUser arvados.User
64 DeactivateUnlisted bool
71 func ParseFlags(cfg *ConfigParams) error {
72 flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
73 flags.Usage = func() {
74 usageStr := `Synchronize remote users into Arvados from a CSV format file with 5 columns:
78 * 4th: Active status (0 or 1)
79 * 5th: Admin status (0 or 1)`
80 fmt.Fprintf(flags.Output(), "%s\n\n", usageStr)
81 fmt.Fprintf(flags.Output(), "Usage:\n%s [OPTIONS] <input-file.csv>\n\n", os.Args[0])
82 fmt.Fprintf(flags.Output(), "Options:\n")
86 deactivateUnlisted := flags.Bool(
87 "deactivate-unlisted",
89 "Deactivate users that are not in the input file.")
90 verbose := flags.Bool(
93 "Log informational messages. Off by default.")
94 getVersion := flags.Bool(
97 "Print version information and exit.")
99 if ok, code := cmd.ParseFlags(flags, os.Args[0], os.Args[1:], "input-file.csv", os.Stderr); !ok {
101 } else if *getVersion {
102 fmt.Printf("%s %s\n", os.Args[0], version)
106 // Input file as a required positional argument
107 if flags.NArg() == 0 {
108 return fmt.Errorf("please provide a path to an input file")
110 srcPath := &os.Args[flags.NFlag()+1]
114 return fmt.Errorf("input file path invalid")
117 cfg.DeactivateUnlisted = *deactivateUnlisted
119 cfg.Verbose = *verbose
124 // GetConfig sets up a ConfigParams struct
125 func GetConfig() (cfg ConfigParams, err error) {
126 err = ParseFlags(&cfg)
131 cfg.Client = arvados.NewClientFromEnv()
133 // Check current user permissions
134 u, err := cfg.Client.CurrentUser()
136 return cfg, fmt.Errorf("error getting the current user: %s", err)
139 return cfg, fmt.Errorf("current user %q is not an admin user", u.UUID)
142 log.Printf("Running as admin user %q (%s)", u.Email, u.UUID)
152 err = cfg.Client.RequestAndDecode(&ac, "GET", "arvados/v1/config", nil, nil)
154 return cfg, fmt.Errorf("error getting the exported config: %s", err)
156 if ac.Login.LoginCluster != "" && ac.Login.LoginCluster != ac.ClusterID {
157 return cfg, fmt.Errorf("cannot run on a cluster other than the login cluster")
159 cfg.SysUserUUID = ac.ClusterID + "-tpzed-000000000000000"
160 cfg.AnonUserUUID = ac.ClusterID + "-tpzed-anonymouspublic"
161 cfg.ClusterID = ac.ClusterID
166 func doMain(cfg *ConfigParams) error {
167 // Try opening the input file early, just in case there's a problem.
168 f, err := os.Open(cfg.Path)
170 return fmt.Errorf("error opening input file: %s", err)
174 allUsers := make(map[string]arvados.User)
175 processedUsers := make(map[string]bool)
176 results, err := GetAll(cfg.Client, "users", arvados.ResourceListParams{}, &UserList{})
178 return fmt.Errorf("error getting all users: %s", err)
180 log.Printf("Found %d users in cluster %q", len(results), cfg.ClusterID)
181 for _, item := range results {
182 u := item.(arvados.User)
183 allUsers[strings.ToLower(u.Email)] = u
184 processedUsers[strings.ToLower(u.Email)] = false
187 loadedRecords, err := LoadInputFile(f)
189 return fmt.Errorf("reading input file %q: %s", cfg.Path, err)
191 log.Printf("Loaded %d records from input file", len(loadedRecords))
193 updatesSucceeded := map[string]bool{}
194 updatesFailed := map[string]bool{}
195 updatesSkipped := map[string]bool{}
197 for _, record := range loadedRecords {
198 processedUsers[record.Email] = true
199 if record.Email == cfg.CurrentUser.Email {
200 updatesSkipped[record.Email] = true
201 log.Printf("Skipping current user %q from processing", record.Email)
204 if updated, err := ProcessRecord(cfg, record, allUsers); err != nil {
205 log.Printf("error processing record %q: %s", record.Email, err)
206 updatesFailed[record.Email] = true
208 updatesSucceeded[record.Email] = true
212 if cfg.DeactivateUnlisted {
213 for email, user := range allUsers {
214 if shouldSkip(cfg, user) {
215 updatesSkipped[email] = true
218 if !processedUsers[email] && allUsers[email].IsActive {
220 log.Printf("Deactivating unlisted user %q (%s)", user.Email, user.UUID)
222 var updatedUser arvados.User
223 if err := UnsetupUser(cfg.Client, user.UUID, &updatedUser); err != nil {
224 log.Printf("error deactivating unlisted user %q: %s", user.UUID, err)
225 updatesFailed[email] = true
227 allUsers[email] = updatedUser
228 updatesSucceeded[email] = true
234 log.Printf("User update successes: %d, skips: %d, failures: %d", len(updatesSucceeded), len(updatesSkipped), len(updatesFailed))
239 func shouldSkip(cfg *ConfigParams, user arvados.User) bool {
241 case cfg.SysUserUUID, cfg.AnonUserUUID:
243 case cfg.CurrentUser.UUID:
249 type userRecord struct {
257 // ProcessRecord creates or updates a user based on the given record
258 func ProcessRecord(cfg *ConfigParams, record userRecord, allUsers map[string]arvados.User) (bool, error) {
260 log.Printf("Processing record for user %q", record.Email)
263 wantedActiveStatus := strconv.FormatBool(record.Active)
264 wantedAdminStatus := strconv.FormatBool(record.Admin)
265 createRequired := false
266 updateRequired := false
267 // Check if user exists, set its active & admin status.
268 var user arvados.User
269 user, ok := allUsers[record.Email]
272 log.Printf("User %q does not exist, creating", record.Email)
274 createRequired = true
275 err := CreateUser(cfg.Client, &user, map[string]string{
276 "email": record.Email,
277 "first_name": record.FirstName,
278 "last_name": record.LastName,
279 "is_active": wantedActiveStatus,
280 "is_admin": wantedAdminStatus,
283 return false, fmt.Errorf("error creating user %q: %s", record.Email, err)
286 if record.Active != user.IsActive {
287 updateRequired = true
290 log.Printf("User %q is inactive, activating", record.Email)
292 // Here we assume the 'setup' is done elsewhere if needed.
293 err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
294 "is_active": wantedActiveStatus,
295 "is_admin": wantedAdminStatus, // Just in case it needs to be changed.
298 return false, fmt.Errorf("error updating user %q: %s", record.Email, err)
302 log.Printf("User %q is active, deactivating", record.Email)
304 err := UnsetupUser(cfg.Client, user.UUID, &user)
306 return false, fmt.Errorf("error deactivating user %q: %s", record.Email, err)
310 // Inactive users cannot be admins.
311 if user.IsActive && record.Admin != user.IsAdmin {
313 log.Printf("User %q is active, changing admin status to %v", record.Email, record.Admin)
315 updateRequired = true
316 err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
317 "is_admin": wantedAdminStatus,
320 return false, fmt.Errorf("error updating user %q: %s", record.Email, err)
323 allUsers[record.Email] = user
325 log.Printf("Created user %q", record.Email)
328 log.Printf("Updated user %q", record.Email)
331 return createRequired || updateRequired, nil
334 // LoadInputFile reads the input file and returns a list of user records
335 func LoadInputFile(f *os.File) (loadedRecords []userRecord, err error) {
337 csvReader := csv.NewReader(f)
338 loadedRecords = make([]userRecord, 0)
341 record, e := csvReader.Read()
347 err = fmt.Errorf("parsing error at line %d: %s", lineNo, e)
350 if len(record) != 5 {
351 err = fmt.Errorf("parsing error at line %d: expected 5 fields, found %d", lineNo, len(record))
354 email := strings.ToLower(strings.TrimSpace(record[0]))
355 firstName := strings.TrimSpace(record[1])
356 lastName := strings.TrimSpace(record[2])
357 active := strings.TrimSpace(record[3])
358 admin := strings.TrimSpace(record[4])
359 if email == "" || firstName == "" || lastName == "" || active == "" || admin == "" {
360 err = fmt.Errorf("parsing error at line %d: fields cannot be empty", lineNo)
363 activeBool, err := strconv.ParseBool(active)
365 return nil, fmt.Errorf("parsing error at line %d: active status not recognized", lineNo)
367 adminBool, err := strconv.ParseBool(admin)
369 return nil, fmt.Errorf("parsing error at line %d: admin status not recognized", lineNo)
371 loadedRecords = append(loadedRecords, userRecord{
373 FirstName: firstName,
379 return loadedRecords, nil
382 // GetAll adds all objects of type 'resource' to the 'allItems' list
383 func GetAll(c *arvados.Client, res string, params arvados.ResourceListParams, page resourceList) (allItems []interface{}, err error) {
384 // Use the maximum page size the server allows
386 params.Limit = &limit
388 params.Order = "uuid"
390 if err = GetResourceList(c, &page, res, params); err != nil {
393 // Have we finished paging?
397 allItems = append(allItems, page.GetItems()...)
398 params.Offset += page.Len()
403 func jsonReader(rscName string, ob interface{}) io.Reader {
404 j, err := json.Marshal(ob)
409 v[rscName] = []string{string(j)}
410 return bytes.NewBufferString(v.Encode())
413 // GetResourceList fetches res list using params
414 func GetResourceList(c *arvados.Client, dst *resourceList, res string, params interface{}) error {
415 return c.RequestAndDecode(dst, "GET", "/arvados/v1/"+res, nil, params)
418 // CreateUser creates a user with userData parameters, assigns it to dst
419 func CreateUser(c *arvados.Client, dst *arvados.User, userData map[string]string) error {
420 return c.RequestAndDecode(dst, "POST", "/arvados/v1/users", jsonReader("user", userData), nil)
423 // UpdateUser updates a user with userData parameters
424 func UpdateUser(c *arvados.Client, userUUID string, dst *arvados.User, userData map[string]string) error {
425 return c.RequestAndDecode(&dst, "PUT", "/arvados/v1/users/"+userUUID, jsonReader("user", userData), nil)
428 // UnsetupUser deactivates a user
429 func UnsetupUser(c *arvados.Client, userUUID string, dst *arvados.User) error {
430 return c.RequestAndDecode(&dst, "POST", "/arvados/v1/users/"+userUUID+"/unsetup", nil, nil)