Skip to content

Commit ca16314

Browse files
svonworlmr-c
andauthored
Append "cwltool" to HTTP User-Agent string (#1977)
Also appends the program name, if not "cwltool" Should work for calrissian, reana-cwl-runner, and arvados-cwl-runner, but not toil-cwl-runner which doesn't call the cwltool.main.main() function. Probably works for streamflow, but I haven't tested that. --------- Co-authored-by: Michael R. Crusoe <[email protected]>
1 parent 814d6d1 commit ca16314

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

cwltool/main.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
import argcomplete
3535
import coloredlogs
36+
import requests
3637
import ruamel.yaml
3738
from ruamel.yaml.comments import CommentedMap, CommentedSeq
3839
from ruamel.yaml.main import YAML
@@ -173,6 +174,14 @@ def _signal_handler(signum: int, _: Any) -> None:
173174
sys.exit(signum)
174175

175176

177+
def append_word_to_default_user_agent(word: str) -> None:
178+
"""Append the specified word to the requests http user agent string if it's not already there."""
179+
original_function = requests.utils.default_user_agent
180+
suffix = f" {word}"
181+
if not original_function().endswith(suffix):
182+
requests.utils.default_user_agent = lambda *args: original_function(*args) + suffix
183+
184+
176185
def generate_example_input(
177186
inptype: Optional[CWLOutputType],
178187
default: Optional[CWLOutputType],
@@ -979,6 +988,12 @@ def main(
979988
workflowobj = None
980989
prov_log_handler: Optional[logging.StreamHandler[ProvOut]] = None
981990
global docker_exe
991+
992+
user_agent = "cwltool"
993+
if user_agent not in (progname := os.path.basename(sys.argv[0])):
994+
user_agent += f" {progname}" # append the real program name as well
995+
append_word_to_default_user_agent(user_agent)
996+
982997
try:
983998
if args is None:
984999
if argsl is None:

tests/test_user_agent.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import requests
2+
3+
from cwltool.main import append_word_to_default_user_agent, main
4+
5+
6+
def get_user_agent() -> str:
7+
return requests.utils.default_headers()["User-Agent"]
8+
9+
10+
def test_cwltool_in_user_agent() -> None:
11+
"""python-requests HTTP User-Agent should include the string 'cwltool'."""
12+
try:
13+
assert main(["--version"]) == 0
14+
except SystemExit as err:
15+
assert err.code == 0
16+
assert "cwltool" in get_user_agent()
17+
18+
19+
def test_append_word_to_default_user_agent() -> None:
20+
"""Confirm that append_word_to_default_user_agent works."""
21+
word_to_append = "foobar123"
22+
assert word_to_append not in get_user_agent()
23+
append_word_to_default_user_agent(word_to_append)
24+
assert word_to_append in get_user_agent()

0 commit comments

Comments
 (0)