Files
POCloud-Driver-Setup/pocloud_driver_setup.py
2017-11-03 12:34:40 -05:00

132 lines
4.2 KiB
Python

"""Command Line utility for use with POCloud driver files."""
import json
import click
import boto3
import csv
import urllib2
CONFIG_FILE_NAME = "driverConfig.json"
CONFIG_OUTPUT_FILENAME = "config.txt"
DRIVER_BUCKET = 'pocloud-drivers'
s3 = boto3.resource('s3')
try:
with open(CONFIG_FILE_NAME, 'r') as config_file:
driver_config = json.load(config_file)
except IOError:
print("Missing {} file.".format(CONFIG_FILE_NAME))
exit()
except ValueError as e:
print("There seems to be an error in the JSON syntax of the {} file:".format(CONFIG_FILE_NAME))
print(e)
exit()
def get_driver_files():
"""Find all the files that should be included with the driver."""
files = [driver_config['driverFilename']]
for x in driver_config['additionalDriverFiles']:
files.append(x)
return files
def get_driver_ids():
"""Retrieve the master list of driver IDs from the S3 bucket."""
ids = []
url = 'https://s3.amazonaws.com/{}/deviceIds.csv'.format(DRIVER_BUCKET)
response = urllib2.urlopen(url)
csvreader = csv.DictReader(response)
for row in csvreader:
ids.append(row)
return ids
def check_driver_id(driver_name):
"""Check if a driver ID exists and if not, create an ID for it."""
id_list = get_driver_ids()
for id in id_list:
if id['driver'] == driver_name:
return id['id']
# if you get here, you didn't find the driver in the list
last_id = int(id_list[-1]['id'])
new_id = ("0000" + str(last_id + 10))[-4:]
new_csv_contents = "driver,id\n"
for id in id_list:
new_csv_contents += "{},{}\n".format(id['driver'], id['id'])
new_csv_contents += "{},{}\n".format(driver_name, new_id)
file_key = "deviceIds.csv"
s3.Bucket(DRIVER_BUCKET).put_object(Key=file_key, Body=new_csv_contents)
s3.ObjectAcl(DRIVER_BUCKET, file_key).put(ACL='public-read')
return new_id
@click.group()
def cli():
pass
@click.command()
def upload():
"""Upload the file to AWS S3 bucket."""
all_files = get_driver_files()
all_files.append("config.txt")
for single_file in all_files:
try:
open_file = open(single_file, 'rb')
file_key = "{}/{}".format(driver_config['s3BucketName'], single_file)
s3.Bucket(DRIVER_BUCKET).put_object(Key=file_key, Body=open_file)
s3.ObjectAcl(DRIVER_BUCKET, file_key).put(ACL='public-read')
click.echo("Uploaded {} to S3 Bucket {}".format(single_file, driver_config['s3BucketName']))
except IOError:
click.echo("ERROR: The file {} does not exist.".format(single_file))
@click.command()
@click.option('--dry-run', default=False, help='Perform a dry run of the script without making changes')
@click.option('--version', default="", help='Sets the version number of the driver code')
def prepare(dry_run, version):
"""Perform the configuration of the driver."""
files = get_driver_files()
file_object = {}
for i in range(0, len(files)):
file_object["file{}".format(i+1)] = files[i]
if version == "+1":
version = int(driver_config['version']) + 1
driver_config['version'] += 1
click.echo("Version set to {}".format(version))
elif version != "":
version = int(version)
click.echo("Version set to {}".format(version))
driver_config['version'] = version
else:
version = driver_config['version']
driver_id = check_driver_id(driver_config['name'])
config_object = {
"driverFileName": driver_config['driverFilename'],
"deviceName": driver_config['name'],
"driverId": driver_id,
"releaseVersion": "{}".format(version),
"files": file_object
}
if dry_run:
click.echo("==== DRY RUN: {} ====".format(CONFIG_OUTPUT_FILENAME))
click.echo(json.dumps(config_object, indent=4))
else:
with open(CONFIG_OUTPUT_FILENAME, 'w') as config_out:
json.dump(config_object, config_out, indent=4)
with open(CONFIG_FILE_NAME, 'w') as input_config_out:
json.dump(driver_config, input_config_out, indent=4)
cli.add_command(upload)
cli.add_command(prepare)
if __name__ == '__main__':
cli()