forked from dotnet/performance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperfcontrib.py
125 lines (96 loc) · 3.84 KB
/
perfcontrib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
from json import loads, dumps
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError
import time
import sys
import os
tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47"
appId = "c2fe4cd0-be4a-468b-aa4f-078c67dcab6e"
uploadService = "https://perfcontrib.azurewebsites.net"
uploadEndpoint = f"{uploadService}/api/UploadPerfData"
authEndpoint = f"{uploadService}/.auth/login/aad"
authDetailsEndpoint = f"{uploadService}/.auth/me"
aadUrl = f"https://login.microsoftonline.com/{tenantId}"
def get_token() -> str:
path = os.path.expanduser("~/.perfcontrib")
token: str | None = None
try:
if not os.path.exists(path):
os.makedirs(path)
with open(os.path.expanduser("~/.perfcontrib/token")) as tokenfile:
token = tokenfile.readline()
except FileNotFoundError:
pass
if token:
try:
with urlopen(Request(authDetailsEndpoint,
headers = { "X-ZUMO-AUTH": token })) as response:
print("Using cached credentials.")
except HTTPError as error:
token = None
if not token:
token = authenticate()
if token:
with open(os.path.expanduser("~/.perfcontrib/token"), "w") as tokenfile:
tokenfile.write(token)
return token
def authenticate() -> str:
authBody = {
"tenant": tenantId,
"client_id": appId,
"scope": "User.Read openid profile",
}
authBodyEncoded = urlencode(authBody).encode()
with urlopen(Request(f"{aadUrl}/oauth2/v2.0/devicecode", data = authBodyEncoded)) as response:
devicecodeResponse = loads(response.read().decode('utf-8'))
print(devicecodeResponse["message"])
authBody2 = {
"tenant": tenantId,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"client_id": appId,
"device_code": devicecodeResponse["device_code"]
}
authBody2Encoded = urlencode(authBody2).encode()
authStatus = "waiting"
print("waiting", end="", flush=True)
while (authStatus == "waiting"):
# Try to get the access token. if we encounter an error check the reason.
# If the reason is we are waiting then sleep for some time.
# If the reason is the user has declined or we timed out then quit.
try:
with urlopen(Request(f"{aadUrl}/oauth2/v2.0/token", data = authBody2Encoded)) as response:
tokenResponse = loads(response.read().decode('utf-8'))
authStatus = "done"
except Exception as ex:
reason = loads(ex.read().decode('utf-8'))["error"]
if reason == "authorization_pending":
print(".", end="", flush=True)
time.sleep(5)
elif reason == "authorization_declined":
authStatus = "failed"
elif reason == "expired_token":
authStatus = "failed"
print()
if authStatus == "failed": raise "Authentication failed"
idToken = tokenResponse["id_token"]
print("Thanks.")
authBody3 = {
"access_token": idToken
}
authBody3Json = dumps(authBody3).encode()
with urlopen(Request(authEndpoint,
data = authBody3Json,
headers = {"Content-Type": "application/json"})) as response:
aadLoginResponse = loads(response.read().decode('utf-8'))
token = aadLoginResponse["authenticationToken"]
return token
def upload(filename: str) -> None:
token = get_token()
print("Uploading.")
with urlopen(Request(uploadEndpoint,
headers = { "X-ZUMO-AUTH": token, "Content-Type": "application/octet-stream", "X-Filename": filename },
data = open(filename,"rb"))) as response:
print(response.read().decode('utf-8'))
if __name__ == "__main__":
upload(sys.argv[1])