2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
15 def parse_arguments(arguments):
16 arg_parser = argparse.ArgumentParser()
17 arg_parser.add_argument('--start', help='Start date for the report in YYYY-MM-DD format (UTC)')
18 arg_parser.add_argument('--end', help='End date for the report in YYYY-MM-DD format (UTC)')
19 arg_parser.add_argument('--days', type=int, help='Number of days before now() to start the report')
20 arg_parser.add_argument('--csv', action='store_true', help='Output in csv format (default: false)')
21 args = arg_parser.parse_args(arguments)
23 if args.days and (args.start or args.end):
24 arg_parser.print_help()
25 print("Error: either specify --days or both --start and --end")
28 if not args.days and (not args.start or not args.end):
29 arg_parser.print_help()
30 print("\nError: either specify --days or both --start and --end")
33 if (args.start and not args.end) or (args.end and not args.start):
34 arg_parser.print_help()
35 print("\nError: no start or end date found, either specify --days or both --start and --end")
39 to = datetime.datetime.utcnow()
40 since = to - datetime.timedelta(days=args.days)
44 since = datetime.datetime.strptime(args.start,"%Y-%m-%d")
46 arg_parser.print_help()
47 print("\nError: start date must be in YYYY-MM-DD format")
52 to = datetime.datetime.strptime(args.end,"%Y-%m-%d")
54 arg_parser.print_help()
55 print("\nError: end date must be in YYYY-MM-DD format")
58 return args, since, to
60 def getowner(arv, uuid, owners):
63 if uuid[6:11] == "tpzed":
66 if uuid not in owners:
68 gp = arv.groups().get(uuid=uuid).execute()
69 owners[uuid] = gp["owner_uuid"]
73 return getowner(arv, owners[uuid], owners)
75 def getuserinfo(arv, uuid):
77 u = arv.users().get(uuid=uuid).execute()
79 return "deleted user (%susers/%s)" % (arv.config()["Services"]["Workbench1"]["ExternalURL"],
81 prof = "\n".join(" %s: \"%s\"" % (k, v) for k, v in u["prefs"].get("profile", {}).items() if v)
84 return "%s %s <%s> (%susers/%s)%s" % (u["first_name"], u["last_name"], u["email"],
85 arv.config()["Services"]["Workbench1"]["ExternalURL"],
87 def getuserinfocsv(arv, uuid):
89 u = arv.users().get(uuid=uuid).execute()
91 return [uuid,"deleted","user",""]
92 return [uuid, u["first_name"], u["last_name"], u["email"]]
95 collectionNameCache = {}
96 def getCollectionName(arv, uuid, pdh):
98 filters = [["uuid", "=", uuid]]
100 cached = uuid in collectionNameCache
101 # look up by uuid if it is available, fall back to look up by pdh
102 if uuid is None or len(uuid) != 27:
103 # Look up by pdh. Note that this can be misleading; the download could
104 # have happened from a collection with the same pdh but different name.
105 # We arbitrarily pick the oldest collection with the pdh to lookup the
106 # name, if the uuid for the request is not known.
108 filters = [["portable_data_hash", "=", pdh]]
110 cached = pdh in collectionNameCache
113 u = arv.collections().list(filters=filters, order=order, limit=1, count="none").execute().get("items")
116 collectionNameCache[lookupField] = u[0]["name"]
117 return collectionNameCache[lookupField]
120 return "\"%s\" (%s)" % (u["name"], u["uuid"])
122 def main(arguments=None):
123 if arguments is None:
124 arguments = sys.argv[1:]
126 args, since, to = parse_arguments(arguments)
135 print("%sUser activity on %s between %s and %s%s" % (prefix, arv.config()["ClusterID"],
136 since.isoformat(sep=" ", timespec="minutes"),
137 to.isoformat(sep=" ", timespec="minutes"), suffix))
139 events = arvados.util.keyset_list_all(arv.logs().list, filters=[["created_at", ">=", since.isoformat()],["created_at", "<", to.isoformat()]])
145 owner = getowner(arv, e["object_owner_uuid"], owners)
146 users.setdefault(owner, [])
147 event_at = ciso8601.parse_datetime(e["event_at"]).astimezone().isoformat(sep=" ", timespec="minutes")
150 if e["event_type"] == "create" and e["object_uuid"][6:11] == "tpzed":
151 users.setdefault(e["object_uuid"], [])
152 users[e["object_uuid"]].append([loguuid, event_at, "User account created"])
154 elif e["event_type"] == "update" and e["object_uuid"][6:11] == "tpzed":
157 elif e["event_type"] == "create" and e["object_uuid"][6:11] == "xvhdp":
158 if e["properties"]["new_attributes"]["requesting_container_uuid"] is None:
159 users[owner].append([loguuid, event_at, "Ran container %s" % (getname(e["properties"]["new_attributes"]))])
161 elif e["event_type"] == "update" and e["object_uuid"][6:11] == "xvhdp":
164 elif e["event_type"] == "create" and e["object_uuid"][6:11] == "j7d0g":
165 users[owner].append([loguuid, event_at,"Created project %s" % (getname(e["properties"]["new_attributes"]))])
167 elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "j7d0g":
168 users[owner].append([loguuid, event_at,"Deleted project %s" % (getname(e["properties"]["old_attributes"]))])
170 elif e["event_type"] == "update" and e["object_uuid"][6:11] == "j7d0g":
171 users[owner].append([loguuid, event_at,"Updated project %s" % (getname(e["properties"]["new_attributes"]))])
173 elif e["event_type"] in ("create", "update") and e["object_uuid"][6:11] == "gj3su":
174 # Don't log token activity, it is too noisy (bug #19179)
177 # We want to report when a user goes through the login
178 # process, but controller doesn't do that yet, so revisit
179 # this when #19388 is done.
181 elif e["event_type"] == "create" and e["object_uuid"][6:11] == "o0j2j":
182 if e["properties"]["new_attributes"]["link_class"] == "tag":
183 users[owner].append([event_at,"Tagged %s" % (e["properties"]["new_attributes"]["head_uuid"])])
184 elif e["properties"]["new_attributes"]["link_class"] == "permission":
185 users[owner].append([loguuid, event_at,"Shared %s with %s" % (e["properties"]["new_attributes"]["tail_uuid"], e["properties"]["new_attributes"]["head_uuid"])])
187 users[owner].append([loguuid, event_at,"%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
189 elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "o0j2j":
190 if e["properties"]["old_attributes"]["link_class"] == "tag":
191 users[owner].append([loguuid, event_at,"Untagged %s" % (e["properties"]["old_attributes"]["head_uuid"])])
192 elif e["properties"]["old_attributes"]["link_class"] == "permission":
193 users[owner].append([loguuid, event_at,"Unshared %s with %s" % (e["properties"]["old_attributes"]["tail_uuid"], e["properties"]["old_attributes"]["head_uuid"])])
195 users[owner].append([loguuid, event_at,"%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
197 elif e["event_type"] == "create" and e["object_uuid"][6:11] == "4zz18":
198 if e["properties"]["new_attributes"]["properties"].get("type") in ("log", "output", "intermediate"):
201 users[owner].append([loguuid, event_at,"Created collection %s" % (getname(e["properties"]["new_attributes"]))])
203 elif e["event_type"] == "update" and e["object_uuid"][6:11] == "4zz18":
204 users[owner].append([loguuid, event_at,"Updated collection %s" % (getname(e["properties"]["new_attributes"]))])
206 elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "4zz18":
207 if e["properties"]["old_attributes"]["properties"].get("type") in ("log", "output", "intermediate"):
210 users[owner].append([loguuid, event_at, "Deleted collection %s" % (getname(e["properties"]["old_attributes"]))])
212 elif e["event_type"] == "file_download":
213 users.setdefault(e["object_uuid"], [])
214 users[e["object_uuid"]].append([loguuid, event_at, "Downloaded file \"%s\" from \"%s\" (%s) (%s)" % (
215 e["properties"].get("collection_file_path") or e["properties"].get("reqPath"),
216 getCollectionName(arv, e["properties"].get("collection_uuid"), e["properties"].get("portable_data_hash")),
217 e["properties"].get("collection_uuid"),
218 e["properties"].get("portable_data_hash"))])
220 elif e["event_type"] == "file_upload":
221 users.setdefault(e["object_uuid"], [])
222 users[e["object_uuid"]].append([loguuid, event_at, "Uploaded file \"%s\" to \"%s\" (%s)" % (
223 e["properties"].get("collection_file_path") or e["properties"].get("reqPath"),
224 getCollectionName(arv, e["properties"].get("collection_uuid"), e["properties"].get("portable_data_hash")),
225 e["properties"].get("collection_uuid"))])
228 users[owner].append([loguuid, event_at, "%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
231 csvwriter = csv.writer(sys.stdout, dialect='unix')
233 for k,v in users.items():
235 if k is None or k.endswith("-tpzed-000000000000000"):
238 # Skip users with no activity to report
243 print(getuserinfo(arv, k))
245 # Remove the log entry uuid, this report is intended for human consumption
247 print(" %s" % ' '.join(ev))
250 user = getuserinfocsv(arv, k)
253 csvwriter.writerow(ev)
255 if __name__ == "__main__":