Skip to contentSkip to conversation

Use aiohttp in pkg-stats

PATCH Superseded Thomas Petazzoni 2 participants 8 messages Aug 4, 2020 – Aug 5, 2020

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover Use aiohttp in pkg-stats

Hello,

I started investigating why pkg-stats was sometimes stuck on the server running it on a daily basis to populate autobuild.buildroot.org/stats/ and send the autobuilder e-mails. The subprocesses started by "multiprocessing" to retrieve the latest upstream version from release-monitoring.org were stuck holding a lock. Without providing a definitive conclusion, some preliminary research showed that multiprocessing can be tricky and cause some issues with locks.

Discussing this with Titouan, he suggested to use aiohttp instead of multiprocessing. And indeed, it makes a lot of sense to use this popular asynchronous HTTP library.

This patch series switches the latest version retrieval and the upstream URL checking to aiohttp, and as a bonus adds some logging to show the progress of the retrieval, as it can be quite long.

Changes since v1:

- Pass trust_env=True when creating the aiohttp.ClientSession() so that HTTP proxy environment variables are taken into account. Suggested by Matt Weber.

- Fix bogus indentation that was breaking the logic of the latest version retrieval.

Thanks,

Thomas

Thomas Petazzoni (3):
support/scripts/pkg-stats: use aiohttp for latest version retrieval support/scripts/pkg-stats: use aiohttp for upstream URL checking support/scripts/pkg-stats: show progress of upstream URL and latest
version

 support/scripts/pkg-stats | 206 ++++++++++++++++++++++----------------
 1 file changed, 122 insertions(+), 84 deletions(-)
Signature · 1 line
2.26.2
#1 lore raw

PATCH v2 1/3 support/scripts/pkg-stats: use aiohttp for latest version retrieval

This commit reworks the code that retrieves the latest upstream version of each package from release-monitoring.org using the aiohttp module. This makes the implementation much more elegant, and avoids the problematic multiprocessing Pool which is causing issues in some situations.

---
 support/scripts/pkg-stats | 142 +++++++++++++++++++++-----------------
 1 file changed, 78 insertions(+), 64 deletions(-)
support/scripts/pkg-stats +78 -64
index ec4d538758..31ff101781 100755
@@ -16,7 +16,9 @@
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
+import aiohttp
 import argparse
+import asyncio
 import datetime
 import fnmatch
 import os
@@ -26,13 +28,10 @@ import subprocess
 import requests  # URL checking
 import json
 import ijson
-import certifi
 import distutils.version
 import time
 import gzip
 import sys
-from urllib3 import HTTPSConnectionPool
-from urllib3.exceptions import HTTPError
 from multiprocessing import Pool
 
 sys.path.append('utils/')
@@ -54,10 +53,6 @@ CVE_AFFECTS = 1
 CVE_DOESNT_AFFECT = 2
 CVE_UNKNOWN = 3
 
-# Used to make multiple requests to the same host. It is global
-# because it's used by sub-processes.
-http_pool = None
-
 
 class Defconfig:
     def __init__(self, name, path):
@@ -526,54 +521,88 @@ def check_package_urls(packages):
     pool.terminate()
 
 
-def release_monitoring_get_latest_version_by_distro(pool, name):
-    try:
-        req = pool.request('GET', "/api/project/Buildroot/%s" % name)
-    except HTTPError:
-        return (RM_API_STATUS_ERROR, None, None)
-
-    if req.status != 200:
-        return (RM_API_STATUS_NOT_FOUND, None, None)
+def check_package_latest_version_set_status(pkg, status, version, identifier):
+    pkg.latest_version = {
+        "status": status,
+        "version": version,
+        "id": identifier,
+    }
 
-    data = json.loads(req.data)
+    if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
+        pkg.status['version'] = ('warning', "Release Monitoring API error")
+    elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
+        pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
 
-    if 'version' in data:
-        return (RM_API_STATUS_FOUND_BY_DISTRO, data['version'], data['id'])
+    if pkg.latest_version['version'] is None:
+        pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
+    elif pkg.latest_version['version'] != pkg.current_version:
+        pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
     else:
-        return (RM_API_STATUS_FOUND_BY_DISTRO, None, data['id'])
+        pkg.status['version'] = ('ok', 'up-to-date')
 
 
-def release_monitoring_get_latest_version_by_guess(pool, name):
+async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
+    url = "https://release-monitoring.org//api/project/Buildroot/%s" % pkg.name
     try:
-        req = pool.request('GET', "/api/projects/?pattern=%s" % name)
-    except HTTPError:
-        return (RM_API_STATUS_ERROR, None, None)
+        async with session.get(url) as resp:
+            if resp.status != 200:
+                return False
 
-    if req.status != 200:
-        return (RM_API_STATUS_NOT_FOUND, None, None)
+            data = await resp.json()
+            version = data['version'] if 'version' in data else None
+            check_package_latest_version_set_status(pkg,
+                                                    RM_API_STATUS_FOUND_BY_DISTRO,
+                                                    version,
+                                                    data['id'])
+            return True
+
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
+        if retry:
+            return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
+        else:
+            return False
 
-    data = json.loads(req.data)
 
-    projects = data['projects']
-    projects.sort(key=lambda x: x['id'])
+async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
+    url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
+    try:
+        async with session.get(url) as resp:
+            if resp.status != 200:
+                return False
+
+            data = await resp.json()
+            # filter projects that have the right name and a version defined
+            projects = [p for p in data['projects'] if p['name'] == pkg.name and 'version' in p]
+            projects.sort(key=lambda x: x['id'])
+
+            if len(projects) > 0:
+                check_package_latest_version_set_status(pkg,
+                                                        RM_API_STATUS_FOUND_BY_DISTRO,
+                                                        projects[0]['version'],
+                                                        projects[0]['id'])
+                return True
+
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
+        if retry:
+            return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
+        else:
+            return False
+
 
-    for p in projects:
-        if p['name'] == name and 'version' in p:
-            return (RM_API_STATUS_FOUND_BY_PATTERN, p['version'], p['id'])
+async def check_package_latest_version_get(session, pkg):
 
-    return (RM_API_STATUS_NOT_FOUND, None, None)
+    if await check_package_get_latest_version_by_distro(session, pkg):
+        return
 
+    if await check_package_get_latest_version_by_guess(session, pkg):
+        return
 
-def check_package_latest_version_worker(name):
-    """Wrapper to try both by name then by guess"""
-    print(name)
-    res = release_monitoring_get_latest_version_by_distro(http_pool, name)
-    if res[0] == RM_API_STATUS_NOT_FOUND:
-        res = release_monitoring_get_latest_version_by_guess(http_pool, name)
-    return res
+    check_package_latest_version_set_status(pkg,
+                                            RM_API_STATUS_NOT_FOUND,
+                                            None, None)
 
 
-def check_package_latest_version(packages):
+async def check_package_latest_version(packages):
     """
     Fills in the .latest_version field of all Package objects
 
@@ -587,33 +616,18 @@ def check_package_latest_version(packages):
     - id: string containing the id of the project corresponding to this
       package, as known by release-monitoring.org
     """
-    global http_pool
-    http_pool = HTTPSConnectionPool('release-monitoring.org', port=443,
-                                    cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(),
-                                    timeout=30)
-    worker_pool = Pool(processes=64)
-    results = worker_pool.map(check_package_latest_version_worker, (pkg.name for pkg in packages))
-    for pkg, r in zip(packages, results):
-        pkg.latest_version = dict(zip(['status', 'version', 'id'], r))
 
+    for pkg in packages:
         if not pkg.has_valid_infra:
             pkg.status['version'] = ("na", "no valid package infra")
-            continue
-
-        if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
-            pkg.status['version'] = ('warning', "Release Monitoring API error")
-        elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
-            pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
-
-        if pkg.latest_version['version'] is None:
-            pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
-        elif pkg.latest_version['version'] != pkg.current_version:
-            pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
-        else:
-            pkg.status['version'] = ('ok', 'up-to-date')
 
-    worker_pool.terminate()
-    del http_pool
+    tasks = []
+    connector = aiohttp.TCPConnector(limit_per_host=5)
+    async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
+        packages = [p for p in packages if p.has_valid_infra]
+        for pkg in packages:
+            tasks.append(check_package_latest_version_get(sess, pkg))
+        await asyncio.wait(tasks)
 
 
 def check_package_cves(nvd_path, packages):
@@ -1057,7 +1071,7 @@ def __main__():
     print("Checking URL status")
     check_package_urls(packages)
     print("Getting latest versions ...")
-    check_package_latest_version(packages)
+    asyncio.run(check_package_latest_version(packages))
     if args.nvd_path:
         print("Checking packages CVEs")
         check_package_cves(args.nvd_path, {p.name: p for p in packages})
Signature · 1 line
2.26.2
#2 lore raw

PATCH v2 1/3 support/scripts/pkg-stats: use aiohttp for latest version retrieval

Hello Thomas,

Quoted 17 lines · Thomas Petazzoni

This commit reworks the code that retrieves the latest upstream version of each package from release-monitoring.org using the aiohttp module. This makes the implementation much more elegant, and avoids the problematic multiprocessing Pool which is causing issues in some situations.

---
  support/scripts/pkg-stats | 142 +++++++++++++++++++++-----------------
  1 file changed, 78 insertions(+), 64 deletions(-)
support/scripts/pkg-stats +0 -0
index ec4d538758..31ff101781 100755

support/scripts/pkg-stats line 17

Quoted 2 lines
support/scripts/pkg-stats +0 -0
@@ -16,7 +16,9 @@
  # along with this program; if not, write to the Free Software
  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

Now that pkg-state uses Python3 only, you should change the shebang line to #!/usr/bin/env python3 as well.

Quoted 1 line

[--SNIP--]

Quoted 12 lines
support/scripts/pkg-stats +5 -5
-def release_monitoring_get_latest_version_by_guess(pool, name):
+async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
+    url = "https://release-monitoring.org//api/project/Buildroot/%s" % pkg.name
      try:
-        req = pool.request('GET', "/api/projects/?pattern=%s" % name)
-    except HTTPError:
-        return (RM_API_STATUS_ERROR, None, None)
+        async with session.get(url) as resp:
+            if resp.status != 200:
+                return False
 
-    if req.status != 200:

support/scripts/pkg-stats def check_package_urls(packages): · line 559

Quoted 10 lines
support/scripts/pkg-stats +9 -1
-        return (RM_API_STATUS_NOT_FOUND, None, None)
+            data = await resp.json()
+            version = data['version'] if 'version' in data else None
+            check_package_latest_version_set_status(pkg,
+                                                    RM_API_STATUS_FOUND_BY_DISTRO,
+                                                    version,
+                                                    data['id'])
+            return True
+
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):

Use asyncio.TimeoutError here. The module asyncio.exceptions was introduced in Python3.8, which is quite recent [1]. Also the public API is asyncio.TimeoutError [2].

Quoted 19 lines
support/scripts/pkg-stats +14 -3
+        if retry:
+            return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
+        else:
+            return False
 
-    data = json.loads(req.data)
 
-    projects = data['projects']
-    projects.sort(key=lambda x: x['id'])
+async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
+    url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
+    try:
+        async with session.get(url) as resp:
+            if resp.status != 200:
+                return False
+
+            data = await resp.json()
+            # filter projects that have the right name and a version defined
+            projects = [p for p in data['projects'] if p['name'] == pkg.name and 'version' in p]

support/scripts/pkg-stats def check_package_urls(packages): · line 585

Quoted 10 lines
support/scripts/pkg-stats +10 -0
+            projects.sort(key=lambda x: x['id'])
+
+            if len(projects) > 0:
+                check_package_latest_version_set_status(pkg,
+                                                        RM_API_STATUS_FOUND_BY_DISTRO,
+                                                        projects[0]['version'],
+                                                        projects[0]['id'])
+                return True
+
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):

Use asyncio.TimeoutError here.

[--SNIP--]

Quoted 24 lines
support/scripts/pkg-stats +1 -16
@@ -587,33 +616,18 @@ def check_package_latest_version(packages):
      - id: string containing the id of the project corresponding to this
        package, as known by release-monitoring.org
      """
-    global http_pool
-    http_pool = HTTPSConnectionPool('release-monitoring.org', port=443,
-                                    cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(),
-                                    timeout=30)
-    worker_pool = Pool(processes=64)
-    results = worker_pool.map(check_package_latest_version_worker, (pkg.name for pkg in packages))
-    for pkg, r in zip(packages, results):
-        pkg.latest_version = dict(zip(['status', 'version', 'id'], r))
 
+    for pkg in packages:
          if not pkg.has_valid_infra:
              pkg.status['version'] = ("na", "no valid package infra")
-            continue
-
-        if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
-            pkg.status['version'] = ('warning', "Release Monitoring API error")
-        elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
-            pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
-
-        if pkg.latest_version['version'] is None:

support/scripts/pkg-stats def check_package_latest_version(packages): · line 625

Quoted 10 lines
support/scripts/pkg-stats +2 -7
-            pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
-        elif pkg.latest_version['version'] != pkg.current_version:
-            pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
-        else:
-            pkg.status['version'] = ('ok', 'up-to-date')
 
-    worker_pool.terminate()
-    del http_pool
+    tasks = []
+    connector = aiohttp.TCPConnector(limit_per_host=5) > +    async with aiohttp.ClientSession(connector=connector, 

trust_env=True) as sess:

support/scripts/pkg-stats def check_package_latest_version(packages): · line 630

Quoted 4 lines
support/scripts/pkg-stats +4 -0
+        packages = [p for p in packages if p.has_valid_infra]
+        for pkg in packages:
+            tasks.append(check_package_latest_version_get(sess, pkg))
+        await asyncio.wait(tasks)

We don't really need 3 consecutive for loops here. I would rewrite the function as:

async def check_package_latest_version(packages):
global check_latest_count

tasks = []
connector = aiohttp.TCPConnector(limit_per_host=5) async with aiohttp.ClientSession(connector=connector) as sess:
for pkg in packages:
if pkg.has_valid_infra:
tasks.append(
check_package_latest_version_get(sess, pkg,
len(packages))

                 )
             else:
                 check_latest_count += 1
                 pkg.status['version'] = ("na", "no valid package infra")
         await asyncio.wait(tasks)

support/scripts/pkg-stats def __main__(): · line 1074

Quoted 9 lines
support/scripts/pkg-stats +1 -1
  def check_package_cves(nvd_path, packages):
@@ -1057,7 +1071,7 @@ def __main__():
      print("Checking URL status")
      check_package_urls(packages)
      print("Getting latest versions ...")
-    check_package_latest_version(packages)
+    asyncio.run(check_package_latest_version(packages))

asyncio.run was introduced in Python3.7 [3], which is quite "recent". You could maybe use an "older" form (that would run down to py3.5):

loop = asyncio.get_event_loop() loop.run_until_complete(check_package_latest_version(packages))

support/scripts/pkg-stats def __main__(): · line 1077

Quoted 4 lines
support/scripts/pkg-stats +0 -0
      if args.nvd_path:
          print("Checking packages CVEs")
          check_package_cves(args.nvd_path, {p.name: p for p in packages})

[1] https://bugs.python.org/issue34622
[2]
https://docs.python.org/3.8/library/asyncio-exceptions.html#asyncio.TimeoutError
[3] https://docs.python.org/3/library/asyncio-task.html#asyncio.run

Kind regards,
Titouan

#3 lore raw

PATCH v2 1/3 support/scripts/pkg-stats: use aiohttp for latest version retrieval

Quoted 24 lines · On Wed, 5 Aug 2020 22:29:38 +0200 Titouan Christophe…

support/scripts/pkg-stats def check_package_latest_version(packages):

Quoted 4 lines
support/scripts/pkg-stats +2 -2
-    worker_pool.terminate()
-    del http_pool
+    tasks = []
+    connector = aiohttp.TCPConnector(limit_per_host=5) > +    async with aiohttp.ClientSession(connector=connector,   

trust_env=True) as sess:

support/scripts/pkg-stats def check_package_latest_version(packages): · line 630

Quoted 4 lines
support/scripts/pkg-stats +4 -0
+        packages = [p for p in packages if p.has_valid_infra]
+        for pkg in packages:
+            tasks.append(check_package_latest_version_get(sess, pkg))
+        await asyncio.wait(tasks)  

We don't really need 3 consecutive for loops here. I would rewrite the function as:

async def check_package_latest_version(packages):
global check_latest_count

tasks = []
connector = aiohttp.TCPConnector(limit_per_host=5) async with aiohttp.ClientSession(connector=connector) as sess:
for pkg in packages:
if pkg.has_valid_infra:
tasks.append(
check_package_latest_version_get(sess, pkg,
len(packages))

Quoted 3 lines
                 )
             else:
                 check_latest_count += 1

There will be "gaps" in the count being displayed, since you're incrementing this counter without displaying the package name and total count of packages.

That is why I was doing differently: handle the packages that don't have any valid infra first, and then handle the remainder of the packages.

Quoted 17 lines

pkg.status['version'] = ("na", "no valid package infra")
await asyncio.wait(tasks)

support/scripts/pkg-stats def __main__(): · line 1074

Quoted 9 lines

def check_package_cves(nvd_path, packages):

support/scripts/pkg-stats +1 -1
@@ -1057,7 +1071,7 @@ def __main__():
      print("Checking URL status")
      check_package_urls(packages)
      print("Getting latest versions ...")
-    check_package_latest_version(packages)
+    asyncio.run(check_package_latest_version(packages))  

asyncio.run was introduced in Python3.7 [3], which is quite "recent". You could maybe use an "older" form (that would run down to py3.5):

Quoted 2 lines

loop = asyncio.get_event_loop() loop.run_until_complete(check_package_latest_version(packages))

ACK, will change this.

Thomas

Signature · 3 lines
Thomas Petazzoni, CTO, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#4 lore raw

PATCH v2 2/3 support/scripts/pkg-stats: use aiohttp for upstream URL checking

In reply to Thomas Petazzoni

This commit reworks the code that checks if the upstream URL of each package (specified by its Config.in file) using the aiohttp module. This makes the implementation much more elegant, and avoids the problematic multiprocessing Pool which is causing issues in some situations.

---
 support/scripts/pkg-stats | 45 +++++++++++++++++++++------------------
 1 file changed, 24 insertions(+), 21 deletions(-)
support/scripts/pkg-stats +24 -21
index 31ff101781..30aca89336 100755
@@ -25,14 +25,13 @@ import os
 from collections import defaultdict
 import re
 import subprocess
-import requests  # URL checking
+import requests  # NVD database download
 import json
 import ijson
 import distutils.version
 import time
 import gzip
 import sys
-from multiprocessing import Pool
 
 sys.path.append('utils/')
 from getdeveloperlib import parse_developers  # noqa: E402
@@ -499,26 +498,30 @@ def package_init_make_info():
             Package.all_ignored_cves[pkgvar] = value.split()
 
 
-def check_url_status_worker(url, url_status):
-    if url_status[0] == 'ok':
-        try:
-            url_status_code = requests.head(url, timeout=30).status_code
-            if url_status_code >= 400:
-                return ("error", "invalid {}".format(url_status_code))
-        except requests.exceptions.RequestException:
-            return ("error", "invalid (err)")
-        return ("ok", "valid")
-    return url_status
+async def check_url_status(session, pkg, retry=True):
+    try:
+        async with session.get(pkg.url) as resp:
+            if resp.status >= 400:
+                pkg.status['url'] = ("error", "invalid {}".format(resp.status))
+                return
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
+        if retry:
+            return await check_url_status(session, pkg, retry=False)
+        else:
+            pkg.status['url'] = ("error", "invalid (err)")
+            return
 
+    pkg.status['url'] = ("ok", "valid")
 
-def check_package_urls(packages):
-    pool = Pool(processes=64)
-    for pkg in packages:
-        pkg.url_worker = pool.apply_async(check_url_status_worker, (pkg.url, pkg.status['url']))
-    for pkg in packages:
-        pkg.status['url'] = pkg.url_worker.get(timeout=3600)
-        del pkg.url_worker
-    pool.terminate()
+
+async def check_package_urls(packages):
+    tasks = []
+    connector = aiohttp.TCPConnector(limit_per_host=5)
+    async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
+        packages = [p for p in packages if p.status['url'][0] == 'ok']
+        for pkg in packages:
+            tasks.append(check_url_status(sess, pkg))
+        await asyncio.wait(tasks)
 
 
 def check_package_latest_version_set_status(pkg, status, version, identifier):
@@ -1069,7 +1072,7 @@ def __main__():
         pkg.set_url()
         pkg.set_developers(developers)
     print("Checking URL status")
-    check_package_urls(packages)
+    asyncio.run(check_package_urls(packages))
     print("Getting latest versions ...")
     asyncio.run(check_package_latest_version(packages))
     if args.nvd_path:
Signature · 1 line
2.26.2
#5 lore raw

PATCH v2 2/3 support/scripts/pkg-stats: use aiohttp for upstream URL checking

Hello Thomas,

Quoted 17 lines · Thomas Petazzoni

This commit reworks the code that checks if the upstream URL of each package (specified by its Config.in file) using the aiohttp module. This makes the implementation much more elegant, and avoids the problematic multiprocessing Pool which is causing issues in some situations.

---
  support/scripts/pkg-stats | 45 +++++++++++++++++++++------------------
  1 file changed, 24 insertions(+), 21 deletions(-)
support/scripts/pkg-stats +0 -0
index 31ff101781..30aca89336 100755

support/scripts/pkg-stats import os · line 28

Quoted 5 lines
support/scripts/pkg-stats +1 -1
@@ -25,14 +25,13 @@ import os
  from collections import defaultdict
  import re
  import subprocess
-import requests  # URL checking
+import requests  # NVD database download

Shouldn't we migrate the NVD downloads to aiohttp as well ? So we do not need 2 different HTTP client libs.

Quoted 21 lines
support/scripts/pkg-stats +0 -8
  import json
  import ijson
  import distutils.version
  import time
  import gzip
  import sys
-from multiprocessing import Pool
 
  sys.path.append('utils/')
  from getdeveloperlib import parse_developers  # noqa: E402
@@ -499,26 +498,30 @@ def package_init_make_info():
              Package.all_ignored_cves[pkgvar] = value.split()
 
 
-def check_url_status_worker(url, url_status):
-    if url_status[0] == 'ok':
-        try:
-            url_status_code = requests.head(url, timeout=30).status_code
-            if url_status_code >= 400:
-                return ("error", "invalid {}".format(url_status_code))
-        except requests.exceptions.RequestException:

support/scripts/pkg-stats def package_init_make_info(): · line 507

Quoted 10 lines
support/scripts/pkg-stats +7 -3
-            return ("error", "invalid (err)")
-        return ("ok", "valid")
-    return url_status
+async def check_url_status(session, pkg, retry=True):
+    try:
+        async with session.get(pkg.url) as resp:
+            if resp.status >= 400:
+                pkg.status['url'] = ("error", "invalid {}".format(resp.status))
+                return
+    except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):

Same as in previous patch: use asyncio.TimeoutError

Quoted 29 lines
support/scripts/pkg-stats +15 -8
+        if retry:
+            return await check_url_status(session, pkg, retry=False)
+        else:
+            pkg.status['url'] = ("error", "invalid (err)")
+            return
 
+    pkg.status['url'] = ("ok", "valid")
 
-def check_package_urls(packages):
-    pool = Pool(processes=64)
-    for pkg in packages:
-        pkg.url_worker = pool.apply_async(check_url_status_worker, (pkg.url, pkg.status['url']))
-    for pkg in packages:
-        pkg.status['url'] = pkg.url_worker.get(timeout=3600)
-        del pkg.url_worker
-    pool.terminate()
+
+async def check_package_urls(packages):
+    tasks = []
+    connector = aiohttp.TCPConnector(limit_per_host=5)
+    async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
+        packages = [p for p in packages if p.status['url'][0] == 'ok']
+        for pkg in packages:
+            tasks.append(check_url_status(sess, pkg))
+        await asyncio.wait(tasks)
 
 
  def check_package_latest_version_set_status(pkg, status, version, identifier):

support/scripts/pkg-stats def __main__(): · line 1075

Quoted 5 lines
support/scripts/pkg-stats +1 -1
@@ -1069,7 +1072,7 @@ def __main__():
          pkg.set_url()
          pkg.set_developers(developers)
      print("Checking URL status")
-    check_package_urls(packages)
+    asyncio.run(check_package_urls(packages))

Same as in previous patch to support down to py3.5:

loop.run_until_complete(check_package_urls(packages))

support/scripts/pkg-stats def __main__(): · line 1078

Quoted 4 lines
support/scripts/pkg-stats +0 -0
      print("Getting latest versions ...")
      asyncio.run(check_package_latest_version(packages))
      if args.nvd_path:

Best regards,

Titouan

#6 lore raw

PATCH v2 2/3 support/scripts/pkg-stats: use aiohttp for upstream URL checking

Quoted 5 lines · On Wed, 5 Aug 2020 22:37:35 +0200 Titouan Christophe…

support/scripts/pkg-stats import os · line 28

Quoted 2 lines
support/scripts/pkg-stats +1 -1
-import requests  # URL checking
+import requests  # NVD database download  

Shouldn't we migrate the NVD downloads to aiohttp as well ? So we do not need 2 different HTTP client libs.

Yes, we could, but I consider that a separate enhancement. We're not using multiprocessing for the NVD database download, so it's less urgent to convert the NVD database download.

(Of course: ACK for all your other comments.)

Thomas

Signature · 3 lines
Thomas Petazzoni, CTO, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#7 lore raw

PATCH v2 3/3 support/scripts/pkg-stats: show progress of upstream URL and latest version

In reply to Thomas Petazzoni

This commit slightly improves the output of pkg-stats by showing the progress of the upstream URL checks and latest version retrieval, on a package basis:

Checking URL status
[0001/0062] curlpp
[0002/0062] cmocka
[0003/0062] snappy
[0004/0062] nload
[...]
[0060/0062] librtas
[0061/0062] libsilk
[0062/0062] jhead
Getting latest versions ...
[0001/0064] libglob
[0002/0064] perl-http-daemon
[0003/0064] shadowsocks-libev
[...]
[0061/0064] lua-flu
[0062/0064] python-aiohttp-security
[0063/0064] ljlinenoise
[0064/0064] matchbox-lib

Note that the above sample was run on 64 packages. Only 62 packages appear for the URL status check, because packages that do not have any URL in their Config.in file, or don't have any Config.in file at all, are not checked and therefore not accounted.

---
 support/scripts/pkg-stats | 31 ++++++++++++++++++++++++++-----
 1 file changed, 26 insertions(+), 5 deletions(-)
support/scripts/pkg-stats +26 -5
index 30aca89336..570bbe833f 100755
@@ -498,20 +498,31 @@ def package_init_make_info():
             Package.all_ignored_cves[pkgvar] = value.split()
 
 
-async def check_url_status(session, pkg, retry=True):
+check_url_count = 0
+
+
+async def check_url_status(session, pkg, npkgs, retry=True):
+    global check_url_count
+
     try:
         async with session.get(pkg.url) as resp:
             if resp.status >= 400:
                 pkg.status['url'] = ("error", "invalid {}".format(resp.status))
+                check_url_count += 1
+                print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
                 return
     except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
         if retry:
-            return await check_url_status(session, pkg, retry=False)
+            return await check_url_status(session, pkg, npkgs, retry=False)
         else:
             pkg.status['url'] = ("error", "invalid (err)")
+            check_url_count += 1
+            print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
             return
 
     pkg.status['url'] = ("ok", "valid")
+    check_url_count += 1
+    print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
 
 
 async def check_package_urls(packages):
@@ -520,7 +531,7 @@ async def check_package_urls(packages):
     async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
         packages = [p for p in packages if p.status['url'][0] == 'ok']
         for pkg in packages:
-            tasks.append(check_url_status(sess, pkg))
+            tasks.append(check_url_status(sess, pkg, len(packages)))
         await asyncio.wait(tasks)
 
 
@@ -592,17 +603,27 @@ async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
             return False
 
 
-async def check_package_latest_version_get(session, pkg):
+check_latest_count = 0
+
+
+async def check_package_latest_version_get(session, pkg, npkgs):
+    global check_latest_count
 
     if await check_package_get_latest_version_by_distro(session, pkg):
+        check_latest_count += 1
+        print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
         return
 
     if await check_package_get_latest_version_by_guess(session, pkg):
+        check_latest_count += 1
+        print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
         return
 
     check_package_latest_version_set_status(pkg,
                                             RM_API_STATUS_NOT_FOUND,
                                             None, None)
+    check_latest_count += 1
+    print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
 
 
 async def check_package_latest_version(packages):
@@ -629,7 +650,7 @@ async def check_package_latest_version(packages):
     async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
         packages = [p for p in packages if p.has_valid_infra]
         for pkg in packages:
-            tasks.append(check_package_latest_version_get(sess, pkg))
+            tasks.append(check_package_latest_version_get(sess, pkg, len(packages)))
         await asyncio.wait(tasks)
 
 
Signature · 1 line
2.26.2