18903: fix uninitialized user object in the user activity script.
[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
14 def parse_arguments(arguments):
15     arg_parser = argparse.ArgumentParser()
16     arg_parser.add_argument('--days', type=int, required=True)
17     args = arg_parser.parse_args(arguments)
18     return args
19
20 def getowner(arv, uuid, owners):
21     if uuid is None:
22         return None
23     if uuid[6:11] == "tpzed":
24         return uuid
25
26     if uuid not in owners:
27         try:
28             gp = arv.groups().get(uuid=uuid).execute()
29             owners[uuid] = gp["owner_uuid"]
30         except:
31             owners[uuid] = None
32
33     return getowner(arv, owners[uuid], owners)
34
35 def getuserinfo(arv, uuid):
36     u = arv.users().get(uuid=uuid).execute()
37     prof = "\n".join("  %s: \"%s\"" % (k, v) for k, v in u["prefs"].get("profile", {}).items() if v)
38     if prof:
39         prof = "\n"+prof+"\n"
40     return "%s %s <%s> (%susers/%s)%s" % (u["first_name"], u["last_name"], u["email"],
41                                                        arv.config()["Services"]["Workbench1"]["ExternalURL"],
42                                                        uuid, prof)
43
44 collectionNameCache = {}
45 def getCollectionName(arv, uuid):
46     if uuid not in collectionNameCache:
47         u = arv.collections().get(uuid=uuid).execute()
48         collectionNameCache[uuid] = u["name"]
49     return collectionNameCache[uuid]
50
51 def getname(u):
52     return "\"%s\" (%s)" % (u["name"], u["uuid"])
53
54 def main(arguments=None):
55     if arguments is None:
56         arguments = sys.argv[1:]
57
58     args = parse_arguments(arguments)
59
60     arv = arvados.api()
61
62     since = datetime.datetime.utcnow() - datetime.timedelta(days=args.days)
63
64     print("User activity on %s between %s and %s\n" % (arv.config()["ClusterID"],
65                                                        (datetime.datetime.now() - datetime.timedelta(days=args.days)).isoformat(sep=" ", timespec="minutes"),
66                                                        datetime.datetime.now().isoformat(sep=" ", timespec="minutes")))
67
68     events = arvados.util.keyset_list_all(arv.logs().list, filters=[["created_at", ">=", since.isoformat()]])
69
70     users = {}
71     owners = {}
72
73     for e in events:
74         owner = getowner(arv, e["object_owner_uuid"], owners)
75         users.setdefault(owner, [])
76         event_at = ciso8601.parse_datetime(e["event_at"]).astimezone().isoformat(sep=" ", timespec="minutes")
77         # loguuid = e["uuid"]
78         loguuid = ""
79
80         if e["event_type"] == "create" and e["object_uuid"][6:11] == "tpzed":
81             users.setdefault(e["object_uuid"], [])
82             users[e["object_uuid"]].append("%s User account created" % event_at)
83
84         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "tpzed":
85             pass
86
87         elif e["event_type"] == "create" and e["object_uuid"][6:11] == "xvhdp":
88             if e["properties"]["new_attributes"]["requesting_container_uuid"] is None:
89                 users[owner].append("%s Ran container %s %s" % (event_at, getname(e["properties"]["new_attributes"]), loguuid))
90
91         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "xvhdp":
92             pass
93
94         elif e["event_type"] == "create" and e["object_uuid"][6:11] == "j7d0g":
95             users[owner].append("%s Created project %s" %  (event_at, getname(e["properties"]["new_attributes"])))
96
97         elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "j7d0g":
98             users[owner].append("%s Deleted project %s" % (event_at, getname(e["properties"]["old_attributes"])))
99
100         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "j7d0g":
101             users[owner].append("%s Updated project %s" % (event_at, getname(e["properties"]["new_attributes"])))
102
103         elif e["event_type"] in ("create", "update") and e["object_uuid"][6:11] == "gj3su":
104             since_last = None
105             if len(users[owner]) > 0 and users[owner][-1].endswith("activity"):
106                 sp = users[owner][-1].split(" ")
107                 start = sp[0]+" "+sp[1]
108                 since_last = ciso8601.parse_datetime(event_at) - ciso8601.parse_datetime(sp[3]+" "+sp[4])
109                 span = ciso8601.parse_datetime(event_at) - ciso8601.parse_datetime(start)
110
111             if since_last is not None and since_last < datetime.timedelta(minutes=61):
112                 users[owner][-1] = "%s to %s (%02d:%02d) Account activity" % (start, event_at, span.days*24 + int(span.seconds/3600), int((span.seconds % 3600)/60))
113             else:
114                 users[owner].append("%s to %s (0:00) Account activity" % (event_at, event_at))
115
116         elif e["event_type"] == "create" and e["object_uuid"][6:11] == "o0j2j":
117             if e["properties"]["new_attributes"]["link_class"] == "tag":
118                 users[owner].append("%s Tagged %s" % (event_at, e["properties"]["new_attributes"]["head_uuid"]))
119             elif e["properties"]["new_attributes"]["link_class"] == "permission":
120                 users[owner].append("%s Shared %s with %s" % (event_at, e["properties"]["new_attributes"]["tail_uuid"], e["properties"]["new_attributes"]["head_uuid"]))
121             else:
122                 users[owner].append("%s %s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"], loguuid))
123
124         elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "o0j2j":
125             if e["properties"]["old_attributes"]["link_class"] == "tag":
126                 users[owner].append("%s Untagged %s" % (event_at, e["properties"]["old_attributes"]["head_uuid"]))
127             elif e["properties"]["old_attributes"]["link_class"] == "permission":
128                 users[owner].append("%s Unshared %s with %s" % (event_at, e["properties"]["old_attributes"]["tail_uuid"], e["properties"]["old_attributes"]["head_uuid"]))
129             else:
130                 users[owner].append("%s %s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"], loguuid))
131
132         elif e["event_type"] == "create" and e["object_uuid"][6:11] == "4zz18":
133             if e["properties"]["new_attributes"]["properties"].get("type") in ("log", "output", "intermediate"):
134                 pass
135             else:
136                 users[owner].append("%s Created collection %s %s" % (event_at, getname(e["properties"]["new_attributes"]), loguuid))
137
138         elif e["event_type"] == "update" and e["object_uuid"][6:11] == "4zz18":
139             users[owner].append("%s Updated collection %s %s" % (event_at, getname(e["properties"]["new_attributes"]), loguuid))
140
141         elif e["event_type"] == "delete" and e["object_uuid"][6:11] == "4zz18":
142             if e["properties"]["old_attributes"]["properties"].get("type") in ("log", "output", "intermediate"):
143                 pass
144             else:
145                 users[owner].append("%s Deleted collection %s %s" % (event_at, getname(e["properties"]["old_attributes"]), loguuid))
146
147         elif e["event_type"] == "file_download":
148                 users.setdefault(e["object_uuid"], [])
149                 users[e["object_uuid"]].append("%s Downloaded file \"%s\" from \"%s\" (%s) (%s)" % (event_at,
150                                                                                        e["properties"].get("collection_file_path") or e["properties"].get("reqPath"),
151                                                                                        getCollectionName(arv, e["properties"].get("collection_uuid")),
152                                                                                        e["properties"].get("collection_uuid"),
153                                                                                        e["properties"].get("portable_data_hash")))
154
155         elif e["event_type"] == "file_upload":
156                 users.setdefault(e["object_uuid"], [])
157                 users[e["object_uuid"]].append("%s Uploaded file \"%s\" to \"%s\" (%s)" % (event_at,
158                                                                                     e["properties"].get("collection_file_path") or e["properties"].get("reqPath"),
159                                                                                     getCollectionName(arv, e["properties"].get("collection_uuid")),
160                                                                                     e["properties"].get("collection_uuid")))
161
162         else:
163             users[owner].append("%s %s %s %s" % (e["event_type"], e["object_kind"], e["object_uuid"], loguuid))
164
165     for k,v in users.items():
166         if k is None or k.endswith("-tpzed-000000000000000"):
167             continue
168         print(getuserinfo(arv, k))
169         for ev in v:
170             print("  %s" % ev)
171         print("")
172
173 if __name__ == "__main__":
174     main()