-
-
Notifications
You must be signed in to change notification settings - Fork 1
Add EUVD mirror pipeline #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Samk1710
wants to merge
6
commits into
aboutcode-org:main
Choose a base branch
from
Samk1710:add_EUVD_mirror_pipeline
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8e69c78
Add EUVD mirror pipeline
Samk1710 f75cf19
Update DEFAULT_START_YEAR to Unix Epoch
Samk1710 91cbede
Refactor EUVD sync as per suggestions
Samk1710 ecee45c
Add logging to unexpected results from API
Samk1710 217d3ae
Address review feedback for EUVD catalog mirror pipeline
Samk1710 c5ac22f
Improve code readability and optimize initial fetches
Samk1710 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| name: Daily sync of EUVD catalog | ||
|
|
||
| on: | ||
| workflow_dispatch: | ||
| schedule: | ||
| - cron: '0 0 * * *' | ||
|
|
||
| permissions: | ||
| contents: write | ||
|
|
||
| jobs: | ||
| scheduled: | ||
| runs-on: ubuntu-latest | ||
|
|
||
| steps: | ||
| - name: Checkout repository | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Set up Python | ||
| uses: actions/setup-python@v5 | ||
| with: | ||
| python-version: '3.10' | ||
|
|
||
| - name: Install required packages | ||
| run: pip install requests==2.32.5 aboutcode.pipeline==0.2.1 | ||
|
|
||
| - name: Run sync (daily) | ||
| run: python sync_catalog.py daily | ||
|
|
||
| - name: Commit and push if it changed | ||
| run: |- | ||
| git config user.name "AboutCode Automation" | ||
| git config user.email "[email protected]" | ||
| git add -A | ||
| timestamp=$(date -u) | ||
| git commit -m "$(echo -e "Sync EUVD catalog: $timestamp\n\nSigned-off-by: AboutCode Automation <[email protected]>")" || exit 0 | ||
| git push | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # Various junk and temp files | ||
| .DS_Store | ||
| *~ | ||
| .*.sw[po] | ||
| .build | ||
| .ve | ||
| *.bak | ||
| var | ||
| share | ||
| selenium | ||
| local | ||
| /dist/ | ||
| /.*cache/ | ||
| /.venv/ | ||
| /.python-version | ||
| /.pytest_cache/ | ||
| /scancodeio.egg-info/ | ||
| *.rdb | ||
| *.aof | ||
| .vscode | ||
| .ipynb_checkpoints |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| requests==2.32.5 | ||
| aboutcode.pipeline==0.2.1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,216 @@ | ||
| # | ||
| # Copyright (c) nexB Inc. and others. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. | ||
| # See https://aboutcode.org for more information about nexB OSS projects. | ||
| # | ||
|
|
||
| import json | ||
| import sys | ||
| from datetime import date, datetime, timedelta, timezone | ||
| from pathlib import Path | ||
| from typing import Any, Dict | ||
|
|
||
| import requests | ||
|
|
||
| from aboutcode.pipeline import BasePipeline, LoopProgress | ||
|
|
||
| ROOT_PATH = Path(__file__).parent | ||
| CATALOG_PATH = ROOT_PATH / "catalog" | ||
| PAGE_DIRECTORY = CATALOG_PATH / "pages" | ||
|
|
||
| API_URL = "https://euvdservices.enisa.europa.eu/api/search" | ||
|
|
||
| HEADERS = { | ||
| "User-Agent": "Vulnerablecode", | ||
| "Accept": "application/json", | ||
| } | ||
|
|
||
| PAGE_SIZE = 100 | ||
| DEFAULT_START_YEAR = 1970 | ||
| REQUEST_TIMEOUT = 10 | ||
|
|
||
|
|
||
| class EuvdCatalogMirror(BasePipeline): | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self.session = requests.Session() | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| @classmethod | ||
| def steps(cls): | ||
| return (cls.collect_catalog,) | ||
|
|
||
| def collect_catalog(self) -> None: | ||
| mode = getattr(self, "mode", "backfill") | ||
| if mode == "daily": | ||
| self.sync_yesterday() | ||
| else: | ||
| self.backfill_from_year(DEFAULT_START_YEAR) | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def backfill_from_year(self, start_year: int) -> None: | ||
Samk1710 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| today = date.today() | ||
| backfill_start = date(start_year, 1, 1) | ||
| backfill_end = today | ||
|
|
||
| months: list[tuple[int, int]] = [] | ||
| current = backfill_start | ||
|
|
||
| while current <= backfill_end: | ||
| months.append((current.year, current.month)) | ||
| if current.month == 12: | ||
| current = date(current.year + 1, 1, 1) | ||
| else: | ||
| current = date(current.year, current.month + 1, 1) | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| progress = LoopProgress(total_iterations=len(months), logger=self.log) | ||
|
|
||
| for year, month in progress.iter(months): | ||
| if year == backfill_end.year and month == backfill_end.month: | ||
| month_start = date(year, month, 1) | ||
| day_token = month_start.isoformat() | ||
| self.log(f"backfill {year}-{month:02d}: {month_start} to {backfill_end}") | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self._collect_paginated( | ||
| start=month_start, | ||
| end=backfill_end, | ||
| year=year, | ||
| month=month, | ||
| day_token=day_token, | ||
| ) | ||
| else: | ||
| self.collect_month(year, month) | ||
|
|
||
| def sync_yesterday(self) -> None: | ||
| target_date = date.today() - timedelta(days=1) | ||
| self.collect_single_day(target_date) | ||
|
|
||
| def collect_month(self, year: int, month: int) -> None: | ||
| month_start = date(year, month, 1) | ||
| if month == 12: | ||
| next_month = date(year + 1, 1, 1) | ||
| else: | ||
| next_month = date(year, month + 1, 1) | ||
| month_end = next_month - timedelta(days=1) | ||
|
|
||
| self.log(f"month {year}-{month:02d}: {month_start} to {month_end}") | ||
| day_token = month_start.isoformat() | ||
|
|
||
| self._collect_paginated( | ||
| start=month_start, | ||
| end=month_end, | ||
| year=year, | ||
| month=month, | ||
| day_token=day_token, | ||
| ) | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def collect_single_day(self, target_date: date) -> None: | ||
| self.log(f"day {target_date}: updated_on={target_date}") | ||
| day_token = target_date.isoformat() | ||
|
|
||
| self._collect_paginated( | ||
| start=target_date, | ||
| end=target_date, | ||
| year=target_date.year, | ||
| month=target_date.month, | ||
| day_token=day_token, | ||
| ) | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def _collect_paginated( | ||
Samk1710 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self, | ||
| start: date, | ||
| end: date, | ||
| year: int, | ||
| month: int, | ||
| day_token: str, | ||
| ) -> None: | ||
| page = 0 | ||
|
|
||
| while True: | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| params = { | ||
| "fromUpdatedDate": start.isoformat(), | ||
| "toUpdatedDate": end.isoformat(), | ||
| "size": PAGE_SIZE, | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| "page": page, | ||
| } | ||
|
|
||
| data = self.fetch_page(params) | ||
| items = data.get("items") or [] | ||
| count = len(items) | ||
|
|
||
| if count == 0: | ||
| self.log(f"no results for {start}–{end} on page {page}, stopping") | ||
| break | ||
|
|
||
| page_number = page + 1 | ||
| self.write_page_file( | ||
| year=year, | ||
| month=month, | ||
| day_token=day_token, | ||
| page_number=page_number, | ||
| payload=data, | ||
| ) | ||
|
|
||
| if count < PAGE_SIZE: | ||
| self.log(f"finished {start}–{end} at page {page} ({count} items)") | ||
| break | ||
|
|
||
| page += 1 | ||
|
|
||
| def write_page_file( | ||
| self, | ||
| year: int, | ||
| month: int, | ||
| day_token: str, | ||
| page_number: int, | ||
| payload: Dict[str, Any], | ||
| ) -> None: | ||
| year_str = f"{year:04d}" | ||
| month_str = f"{month:02d}" | ||
| page_str = f"{page_number:04d}" | ||
|
|
||
| dir_path = PAGE_DIRECTORY / year_str / month_str | ||
| dir_path.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| filename = f"page{day_token}-{page_str}.json" | ||
| path = dir_path / filename | ||
|
|
||
| if path.exists(): | ||
| self.log(f"skip existing file: {path}") | ||
| return | ||
Samk1710 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| with path.open("w", encoding="utf-8") as output: | ||
| json.dump(payload, output, indent=2) | ||
|
|
||
| self.log(f"saved {path}") | ||
|
|
||
| def fetch_page(self, params: Dict[str, Any]) -> Dict[str, Any]: | ||
| self.log(f"GET {API_URL} {params}") | ||
| response = self.session.get( | ||
| API_URL, | ||
| params=params, | ||
| headers=HEADERS, | ||
| timeout=REQUEST_TIMEOUT, | ||
| ) | ||
| response.raise_for_status() | ||
| data: Any = response.json() | ||
| if not isinstance(data, dict): | ||
| return {} | ||
Samk1710 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return data | ||
|
|
||
| def log(self, message: str) -> None: | ||
| now = datetime.now(timezone.utc).astimezone() | ||
| stamp = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] | ||
| print(f"{stamp} {message}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| mode = "backfill" | ||
| if len(sys.argv) >= 2: | ||
| mode = sys.argv[1] | ||
Samk1710 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| mirror = EuvdCatalogMirror() | ||
| mirror.mode = mode | ||
|
|
||
| status_code, error_message = mirror.execute() | ||
| if error_message: | ||
| print(error_message) | ||
| sys.exit(status_code) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.