|
| 1 | +import boto3 |
| 2 | +from django.conf import settings |
| 3 | +import djclick as click |
| 4 | +import psycopg2 |
| 5 | +from psycopg2 import extensions, sql |
| 6 | + |
| 7 | + |
| 8 | +@click.command() |
| 9 | +def setupmlflow(): |
| 10 | + db_name = settings.MLFLOW_PG_DB if settings.MLFLOW_PG_DB else 'mlflow' |
| 11 | + bucket_name = settings.MLFLOW_BUCKET if settings.MLFLOW_BUCKET else 'mlflow' |
| 12 | + |
| 13 | + click.echo(f'Creating database {db_name} for mlflow') |
| 14 | + default_db = settings.DATABASES['default'] |
| 15 | + host = default_db['HOST'] |
| 16 | + user = default_db['USER'] |
| 17 | + password = default_db['PASSWORD'] |
| 18 | + conn = psycopg2.connect(f"dbname='postgres' user='{user}' password='{password}' host='{host}'") |
| 19 | + # We cannot use CREATE DATABASE in a transaction |
| 20 | + conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT) |
| 21 | + with conn.cursor() as cursor: |
| 22 | + cursor.execute(sql.SQL('SELECT 1 FROM pg_database WHERE datname = %s'), (db_name,)) |
| 23 | + if not cursor.fetchone(): |
| 24 | + cursor.execute(f'CREATE DATABASE {sql.Identifier(db_name).as_string(cursor)}') |
| 25 | + click.echo(f'Created database {db_name} for mlflow') |
| 26 | + else: |
| 27 | + click.echo(f'Database {db_name} already exists') |
| 28 | + conn.close() |
| 29 | + |
| 30 | + click.echo(f'Creating storage bucket {bucket_name} for mlflow artifacts') |
| 31 | + access_key = settings.MINIO_STORAGE_ACCESS_KEY |
| 32 | + secret_key = settings.MINIO_STORAGE_SECRET_KEY |
| 33 | + storage_endpoint: str = settings.MINIO_STORAGE_ENDPOINT |
| 34 | + if not storage_endpoint.startswith('http'): |
| 35 | + storage_endpoint = f'http://{storage_endpoint}' |
| 36 | + s3_client = boto3.client( |
| 37 | + 's3', |
| 38 | + endpoint_url=storage_endpoint, |
| 39 | + aws_access_key_id=access_key, |
| 40 | + aws_secret_access_key=secret_key, |
| 41 | + ) |
| 42 | + if not any([bucket['Name'] == bucket_name for bucket in s3_client.list_buckets()['Buckets']]): |
| 43 | + s3_client.create_bucket(Bucket=bucket_name) |
| 44 | + click.echo(f'Created bucket {bucket_name} for mlflow artifacts') |
| 45 | + else: |
| 46 | + click.echo(f'Bucket {bucket_name} already exists') |
0 commit comments