Skip to content

CHC SFTP Downloads #352

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

Merged
merged 10 commits into from
Oct 28, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions changehc/delphi_changehc/constants.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Registry for signal names and geo types"""
SMOOTHED = "smoothed_chc"
SMOOTHED_ADJ = "smoothed_adj_chc"
SMOOTHED = "smoothed_cli"
SMOOTHED_ADJ = "smoothed_adj_cli"
SIGNALS = [SMOOTHED, SMOOTHED_ADJ]
NA = "NA"
HRR = "hrr"
Expand Down
74 changes: 74 additions & 0 deletions changehc/delphi_changehc/download_ftp_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""
Downloads files modified in the last 24 hours from the specified ftp server."""

# standard
import datetime
import functools
import sys
from os import path

# third party
import paramiko


def print_callback(filename, bytes_so_far, bytes_total):
"""Log file transfer progress"""
rough_percent_transferred = int(100 * (bytes_so_far / bytes_total))
if (rough_percent_transferred % 25) == 0:
print(f'{filename} transfer: {rough_percent_transferred}%')


def get_files_from_dir(sftp, out_path):
"""Download files from sftp server that have been uploaded in last day
Args:
sftp: SFTP Session from Paramiko client
out_path: Path to local directory into which to download the files
"""

current_time = datetime.datetime.now()

# go through files in recieving dir
filepaths_to_download = {}
for fileattr in sftp.listdir_attr():
file_time = datetime.datetime.fromtimestamp(fileattr.st_mtime)
filename = fileattr.filename
if current_time - file_time < datetime.timedelta(days=1) and \
not path.exists(path.join(out_path, filename)):
filepaths_to_download[filename] = path.join(out_path, filename)

# make sure we don't download more than 2 files per day
assert len(filepaths_to_download) <= 2, "more files dropped than expected"

# download!
for infile, outfile in filepaths_to_download.items():
callback_for_filename = functools.partial(print_callback, infile)
sftp.get(infile, outfile, callback=callback_for_filename)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

callback is cool, didn't know of this feature in paramiko



def download(out_path, ftp_conn):
"""Downloads files necessary to create CHC signal from ftp server.
Args:
out_path: Path to local directory into which to download the files
ftp_conn: Dict containing login credentials to ftp server
"""

# open client
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(ftp_conn["host"], username=ftp_conn["user"],
password=ftp_conn["pass"][1:] + ftp_conn["pass"][0],
port=ftp_conn["port"],
allow_agent=False, look_for_keys=False)
sftp = client.open_sftp()

sftp.chdir('/dailycounts/All_Outpatients_By_County')
get_files_from_dir(sftp, out_path)

sftp.chdir('/dailycounts/Covid_Outpatients_By_County')
get_files_from_dir(sftp, out_path)

finally:
if client:
client.close()
5 changes: 5 additions & 0 deletions changehc/delphi_changehc/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from delphi_utils import read_params

# first party
from .download_ftp_files import download
from .update_sensor import CHCSensorUpdator


Expand All @@ -25,6 +26,10 @@ def run_module():

logging.basicConfig(level=logging.DEBUG)

## download recent files from FTP server
logging.info("downloading recent files through SFTP")
download(params["cache_dir"], params["ftp_conn"])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be mocked out for testing?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1


## get end date from input file
# the filenames are expected to be in the format:
# Denominator: "YYYYMMDD_All_Outpatients_By_County.dat.gz"
Expand Down
10 changes: 8 additions & 2 deletions changehc/params.json.template
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,11 @@
"aws_access_key_id": "",
"aws_secret_access_key": ""
},
"bucket_name": ""
}
"bucket_name": "",
"ftp_conn": {
"host": "",
"user": "",
"pass": "",
"port": 0
}
}
3 changes: 2 additions & 1 deletion changehc/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"delphi-utils",
"covidcast",
"boto3",
"moto"
"moto",
"paramiko"
]

setup(
Expand Down
3 changes: 1 addition & 2 deletions changehc/tests/test_update_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,6 @@ def test_handle_wip_signal(self):
assert signal_names[0].startswith("wip_")
assert all(not s.startswith("wip_") for s in signal_names[1:])
# Test wip_signal = False (only unpublished signals should receive prefix)
# No CHC signal is published now, so both should get prefix
signal_names = add_prefix(["xyzzy", SIGNALS[0]], False)
assert signal_names[0].startswith("wip_")
assert all(s.startswith("wip_") for s in signal_names[1:])
assert all(not s.startswith("wip_") for s in signal_names[1:])