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, updatesFailed := 0, 0
194 for _, record := range loadedRecords {
195 if record.Email == cfg.CurrentUser.Email {
196 log.Printf("Skipping current user %q from processing", record.Email)
199 if updated, err := ProcessRecord(cfg, record, allUsers); err != nil {
200 log.Printf("error processing record %q: %s", record.Email, err)
203 processedUsers[strings.ToLower(record.Email)] = true
208 if cfg.DeactivateUnlisted {
209 for email, user := range allUsers {
211 case cfg.SysUserUUID, cfg.AnonUserUUID:
213 log.Printf("Skipping system user deactivation: %s", user.UUID)
216 case cfg.CurrentUser.UUID:
218 log.Printf("Skipping current user deactivation: %s (%s)", user.Email, user.UUID)
222 if !processedUsers[email] && allUsers[email].IsActive {
224 log.Printf("Deactivating unlisted user %q (%s)", user.Email, user.UUID)
226 var updatedUser arvados.User
227 if err := UnsetupUser(cfg.Client, user.UUID, &updatedUser); err != nil {
228 log.Printf("error deactivating unlisted user %q: %s", user.UUID, err)
231 allUsers[email] = updatedUser
238 log.Printf("Updated %d user(s), failed to update %d user(s)", updatesSucceeded, updatesFailed)
243 type userRecord struct {
251 // ProcessRecord creates or updates a user based on the given record
252 func ProcessRecord(cfg *ConfigParams, record userRecord, allUsers map[string]arvados.User) (bool, error) {
254 log.Printf("Processing record for user %q", record.Email)
257 wantedActiveStatus := strconv.FormatBool(record.Active)
258 wantedAdminStatus := strconv.FormatBool(record.Admin)
259 createRequired := false
260 updateRequired := false
261 // Check if user exists, set its active & admin status.
262 var user arvados.User
263 user, ok := allUsers[record.Email]
266 log.Printf("User %q does not exist, creating", record.Email)
268 createRequired = true
269 err := CreateUser(cfg.Client, &user, map[string]string{
270 "email": record.Email,
271 "first_name": record.FirstName,
272 "last_name": record.LastName,
273 "is_active": wantedActiveStatus,
274 "is_admin": wantedAdminStatus,
277 return false, fmt.Errorf("error creating user %q: %s", record.Email, err)
280 if record.Active != user.IsActive {
281 updateRequired = true
284 log.Printf("User %q is inactive, activating", record.Email)
286 // Here we assume the 'setup' is done elsewhere if needed.
287 err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
288 "is_active": wantedActiveStatus,
289 "is_admin": wantedAdminStatus, // Just in case it needs to be changed.
292 return false, fmt.Errorf("error updating user %q: %s", record.Email, err)
296 log.Printf("User %q is active, deactivating", record.Email)
298 err := UnsetupUser(cfg.Client, user.UUID, &user)
300 return false, fmt.Errorf("error deactivating user %q: %s", record.Email, err)
304 // Inactive users cannot be admins.
305 if user.IsActive && record.Admin != user.IsAdmin {
307 log.Printf("User %q is active, changing admin status to %v", record.Email, record.Admin)
309 updateRequired = true
310 err := UpdateUser(cfg.Client, user.UUID, &user, map[string]string{
311 "is_admin": wantedAdminStatus,
314 return false, fmt.Errorf("error updating user %q: %s", record.Email, err)
317 allUsers[record.Email] = user
319 log.Printf("Created user %q", record.Email)
322 log.Printf("Updated user %q", record.Email)
325 return createRequired || updateRequired, nil
328 // LoadInputFile reads the input file and returns a list of user records
329 func LoadInputFile(f *os.File) (loadedRecords []userRecord, err error) {
331 csvReader := csv.NewReader(f)
332 loadedRecords = make([]userRecord, 0)
335 record, e := csvReader.Read()
341 err = fmt.Errorf("parsing error at line %d: %s", lineNo, e)
344 if len(record) != 5 {
345 err = fmt.Errorf("parsing error at line %d: expected 5 fields, found %d", lineNo, len(record))
348 email := strings.ToLower(strings.TrimSpace(record[0]))
349 firstName := strings.TrimSpace(record[1])
350 lastName := strings.TrimSpace(record[2])
351 active := strings.TrimSpace(record[3])
352 admin := strings.TrimSpace(record[4])
353 if email == "" || firstName == "" || lastName == "" || active == "" || admin == "" {
354 err = fmt.Errorf("parsing error at line %d: fields cannot be empty", lineNo)
357 activeBool, err := strconv.ParseBool(active)
359 return nil, fmt.Errorf("parsing error at line %d: active status not recognized", lineNo)
361 adminBool, err := strconv.ParseBool(admin)
363 return nil, fmt.Errorf("parsing error at line %d: admin status not recognized", lineNo)
365 loadedRecords = append(loadedRecords, userRecord{
367 FirstName: firstName,
373 return loadedRecords, nil
376 // GetAll adds all objects of type 'resource' to the 'allItems' list
377 func GetAll(c *arvados.Client, res string, params arvados.ResourceListParams, page resourceList) (allItems []interface{}, err error) {
378 // Use the maximum page size the server allows
380 params.Limit = &limit
382 params.Order = "uuid"
384 if err = GetResourceList(c, &page, res, params); err != nil {
387 // Have we finished paging?
391 allItems = append(allItems, page.GetItems()...)
392 params.Offset += page.Len()
397 func jsonReader(rscName string, ob interface{}) io.Reader {
398 j, err := json.Marshal(ob)
403 v[rscName] = []string{string(j)}
404 return bytes.NewBufferString(v.Encode())
407 // GetResourceList fetches res list using params
408 func GetResourceList(c *arvados.Client, dst *resourceList, res string, params interface{}) error {
409 return c.RequestAndDecode(dst, "GET", "/arvados/v1/"+res, nil, params)
412 // CreateUser creates a user with userData parameters, assigns it to dst
413 func CreateUser(c *arvados.Client, dst *arvados.User, userData map[string]string) error {
414 return c.RequestAndDecode(dst, "POST", "/arvados/v1/users", jsonReader("user", userData), nil)
417 // UpdateUser updates a user with userData parameters
418 func UpdateUser(c *arvados.Client, userUUID string, dst *arvados.User, userData map[string]string) error {
419 return c.RequestAndDecode(&dst, "PUT", "/arvados/v1/users/"+userUUID, jsonReader("user", userData), nil)
422 // UnsetupUser deactivates a user
423 func UnsetupUser(c *arvados.Client, userUUID string, dst *arvados.User) error {
424 return c.RequestAndDecode(&dst, "POST", "/arvados/v1/users/"+userUUID+"/unsetup", nil, nil)