20640: Add iter_computed_permissions tests.
[arvados.git] / tools / user-activity / arvados_user_activity / main.py
1 #!/usr/bin/env python3
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 import argparse
7 import sys
8
9 import arvados
10 import arvados.util
11 import datetime
12 import ciso8601
13 import csv
14
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)
22
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")
26         exit(1)
27
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")
31         exit(1)
32
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")
36         exit(1)
37
38     if args.days:
39         to = datetime.datetime.utcnow()
40         since = to - datetime.timedelta(days=args.days)
41
42     if args.start:
43         try:
44             since = datetime.datetime.strptime(args.start,"%Y-%m-%d")
45         except:
46             arg_parser.print_help()
47             print("\nError: start date must be in YYYY-MM-DD format")
48             exit(1)
49
50     if args.end:
51         try:
52             to = datetime.datetime.strptime(args.end,"%Y-%m-%d")
53         except:
54             arg_parser.print_help()
55             print("\nError: end date must be in YYYY-MM-DD format")
56             exit(1)
57
58     return args, since, to
59
60 def getowner(arv, uuid, owners):
61     if uuid is None:
62         return None
63     if uuid[6:11] == "tpzed":
64         return uuid
65
66     if uuid not in owners:
67         try:
68             gp = arv.groups().get(uuid=uuid).execute()
69             owners[uuid] = gp["owner_uuid"]
70         except:
71             owners[uuid] = None
72
73     return getowner(arv, owners[uuid], owners)
74
75 def getuserinfo(arv, uuid):
76     try:
77         u = arv.users().get(uuid=uuid).execute()
78     except:
79         return "deleted user (%susers/%s)" % (arv.config()["Services"]["Workbench1"]["ExternalURL"],
80                                                        uuid)
81     prof = "\n".join("  %s: \"%s\"" % (k, v) for k, v in u["prefs"].get("profile", {}).items() if v)
82     if prof:
83         prof = "\n"+prof+"\n"
84     return "%s %s <%s> (%susers/%s)%s" % (u["first_name"], u["last_name"], u["email"],
85                                                        arv.config()["Services"]["Workbench1"]["ExternalURL"],
86                                                        uuid, prof)
87 def getuserinfocsv(arv, uuid):
88     try:
89         u = arv.users().get(uuid=uuid).execute()
90     except:
91         return [uuid,"deleted","user",""]
92     return [uuid, u["first_name"], u["last_name"], u["email"]]
93
94
95 collectionNameCache = {}
96 def getCollectionName(arv, uuid, pdh):
97     lookupField = uuid
98     filters = [["uuid", "=", uuid]]
99     order = None
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.
107         lookupField = pdh
108         filters = [["portable_data_hash", "=", pdh]]
109         order = "created_at"
110         cached = pdh in collectionNameCache
111
112     if not cached:
113         u = arv.collections().list(filters=filters, order=order, limit=1, count="none").execute().get("items")
114         if len(u) < 1:
115             return "(deleted)"
116         collectionNameCache[lookupField] = u[0]["name"]
117     return collectionNameCache[lookupField]
118
119 def getname(u):
120     return "\"%s\" (%s)" % (u["name"], u["uuid"])
121
122 def main(arguments=None):
123     if arguments is None:
124         arguments = sys.argv[1:]
125
126     args, since, to = parse_arguments(arguments)
127
128     arv = arvados.api()
129
130     prefix = ''
131     suffix = "\n"
132     if args.csv:
133         prefix = '# '
134         suffix = ''
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))
138
139     events = arvados.util.keyset_list_all(arv.logs().list, filters=[["created_at", ">=", since.isoformat()],["created_at", "<", to.isoformat()]])
140
141     users = {}
142     owners = {}
143
144     for e in events:
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")
148         loguuid = e["uuid"]
149
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"])
153
154         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "tpzed":
155             pass
156
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"]))])
160
161         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "xvhdp":
162             pass
163
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"]))])
166
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"]))])
169
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"]))])
172
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)
175             pass
176
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.
180
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"])])
186             else:
187                 users[owner].append([loguuid, event_at,"%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
188
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"])])
194             else:
195                 users[owner].append([loguuid, event_at,"%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
196
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"):
199                 pass
200             else:
201                 users[owner].append([loguuid, event_at,"Created collection %s" % (getname(e["properties"]["new_attributes"]))])
202
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"]))])
205
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"):
208                 pass
209             else:
210                 users[owner].append([loguuid, event_at, "Deleted collection %s" % (getname(e["properties"]["old_attributes"]))])
211
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"))])
219
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"))])
226
227         else:
228             users[owner].append([loguuid, event_at, "%s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"])])
229
230     if args.csv:
231         csvwriter = csv.writer(sys.stdout, dialect='unix')
232
233     for k,v in users.items():
234         # Skip system user
235         if k is None or k.endswith("-tpzed-000000000000000"):
236             continue
237
238         # Skip users with no activity to report
239         if not v:
240             continue
241
242         if not args.csv:
243           print(getuserinfo(arv, k))
244           for ev in v:
245               # Remove the log entry uuid, this report is intended for human consumption
246               ev.pop(0)
247               print("  %s" % ' '.join(ev))
248           print("")
249         else:
250           user = getuserinfocsv(arv, k)
251           for ev in v:
252             ev = user + ev
253             csvwriter.writerow(ev)
254
255 if __name__ == "__main__":
256     main()