File size: 10,809 Bytes
70a2533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
from flask import Flask, request, jsonify
import threading
import requests
import json

app = Flask(__name__)

def create_databricks_job(data):
    mode = data.get('mode')
    databricks_instance = data.get('databricks_instance')
    databricks_api_key = data.get('databricks_api_key')
    new_dataset = data.get('new_dataset')
    dataset_id = data.get('dataset_id')
    table_path = data.get('table_path')
    labelbox_api_key = data.get('labelbox_api_key')
    frequency = data.get('frequency')
    new_cluster = data.get('new_cluster')
    cluster_id = data.get('cluster_id')
    schema_map = data.get('schema_map')

    # Define the authentication headers
    headers = {
        "Authorization": f"Bearer {databricks_api_key}",
        "Content-Type": "application/json",
    }

    # ----- CLUSTER CREATION LOGIC -----

    def create_all_purpose_cluster(databricks_instance):
        url = f"https://{databricks_instance}/api/2.0/clusters/create"

        cluster_payload = {
            "autoscale": {
                "min_workers": 1,
                "max_workers": 10
            },
            "cluster_name": "Labelbox Worker",
            "spark_version": "11.3.x-scala2.12",
            "gcp_attributes": {
                "use_preemptible_executors": False,
                "availability": "PREEMPTIBLE_WITH_FALLBACK_GCP",
                "zone_id": "HA"
            },
            "node_type_id": "n2-highmem-4",
            "driver_node_type_id": "n2-highmem-4",
            "ssh_public_keys": [],
            "custom_tags": {},
            "cluster_log_conf": {
                "dbfs": {
                    "destination": "dbfs:/cluster-logs"
                }
            },
            "spark_env_vars": {},
            "autotermination_minutes": 60,
            "enable_elastic_disk": False,
            "init_scripts": [],
            "enable_local_disk_encryption": False,
            "runtime_engine": "STANDARD"
        }
        
        response = requests.post(url, data=json.dumps(cluster_payload), headers=headers)
        if response.status_code == 200:
            return response.json()['cluster_id']
        else:
            raise Exception(f"Failed to create all-purpose cluster. Error: {response.text}")
        
    # ----- PREVIEW MODE LOGIC -----

    def create_preview(dataset_id, table_path, labelbox_api_key, frequency, cluster_id):
            # ----- JOB SCHEDULING LOGIC -----
            if frequency == "continuous":
                schedule_block = {
                    "continuous": {
                        "pause_status": "UNPAUSED"
                    }
                }
            else:
                schedule_block = {
                    "schedule": {
                        "quartz_cron_expression": frequency,
                        "timezone_id": "UTC",
                        "pause_status": "UNPAUSED"
                    }
                }

            # ----- JOB DEFINITION -----

        # Define the parameters and structure of the job to be created in Databricks

            payload = {
                "name": "PREVIEW_upload_to_labelbox",
                "email_notifications": {"no_alert_for_skipped_runs": False},
                "webhook_notifications": {},
                "timeout_seconds": 0,
                "max_concurrent_runs": 1,
                "tasks": [
                    {
                        "existing_cluster_id": cluster_id,  # Move this inside the task
                        "task_key": "PREVIEW_upload_to_labelbox",
                        "run_if": "ALL_SUCCESS",
                        "notebook_task": {
                            "notebook_path": "notebooks/databricks_pipeline_creator/preview_upload_to_labelbox",
                            "base_parameters": {
                                "dataset_id": dataset_id,
                                "table_path": table_path,
                                "labelbox_api_key": labelbox_api_key,
                                "schema_map": schema_map
                            },
                            "source": "GIT"
                        },
                        "libraries": [
                            {"pypi": {"package": "labelspark"}},
                            {"pypi": {"package": "labelbox==3.49.1"}},
                            {"pypi": {"package": "numpy==1.25"}},
                            {"pypi": {"package": "opencv-python==4.8.0.74"}}
                        ],
                        "timeout_seconds": 0,
                        "email_notifications": {},
                        "notification_settings": {
                            "no_alert_for_skipped_runs": False,
                            "no_alert_for_canceled_runs": False,
                            "alert_on_last_attempt": False
                        }
                    }
                ],
                "git_source": {
                    "git_url": "https://github.com/Labelbox/labelspark.git",
                    "git_provider": "gitHub",
                    "git_branch": "master"
                },
                "format": "MULTI_TASK"
            }

            # Merge the scheduling configuration into the main job payload
            payload.update(schedule_block)

            return payload
    
    # ----- PRODUCTION MODE LOGIC -----
    def create_production(dataset_id, table_path, labelbox_api_key, frequency):
            # ----- JOB SCHEDULING LOGIC -----

            # If the job needs to run continuously, use the "continuous" block
            # Else, use the "schedule" block with the specified cron frequency
            if frequency == "continuous":
                schedule_block = {
                    "continuous": {
                        "pause_status": "UNPAUSED"
                    }
                }
            else:
                schedule_block = {
                    "schedule": {
                        "quartz_cron_expression": frequency,
                        "timezone_id": "UTC",
                        "pause_status": "UNPAUSED"
                    }
                }

            # ----- JOB DEFINITION -----

            # Define the parameters and structure of the job to be created in Databricks
            payload = {
                "name": "upload_to_labelbox",
                "email_notifications": {"no_alert_for_skipped_runs": False},
                "webhook_notifications": {},
                "timeout_seconds": 0,
                "max_concurrent_runs": 1,
                "tasks": [
                    {
                        "task_key": "upload_to_labelbox",
                        "run_if": "ALL_SUCCESS",
                        "notebook_task": {
                            "notebook_path": "notebooks/databricks_pipeline_creator/upload_to_labelbox",
                            "base_parameters": {
                                "dataset_id": dataset_id,
                                "table_path": table_path,
                                "labelbox_api_key": labelbox_api_key,
                                "schema_map": schema_map
                            },
                            "source": "GIT"
                        },
                        "job_cluster_key": "Job_cluster",
                        "libraries": [
                            {"pypi": {"package": "labelspark"}},
                            {"pypi": {"package": "labelbox==3.49.1"}},
                            {"pypi": {"package": "numpy==1.25"}},
                            {"pypi": {"package": "opencv-python==4.8.0.74"}}
                        ],
                        "timeout_seconds": 0,
                        "email_notifications": {},
                        "notification_settings": {
                            "no_alert_for_skipped_runs": False,
                            "no_alert_for_canceled_runs": False,
                            "alert_on_last_attempt": False
                        }
                    }
                ],
                "job_clusters": [
                    {
                        "job_cluster_key": "Job_cluster",
                        "new_cluster": {
                            "cluster_name": "",
                            "spark_version": "13.3.x-scala2.12",
                            "gcp_attributes": {
                                "use_preemptible_executors": False,
                                "availability": "ON_DEMAND_GCP",
                                "zone_id": "HA"
                            },
                            "node_type_id": "n2-highmem-4",
                            "enable_elastic_disk": True,
                            "data_security_mode": "SINGLE_USER",
                            "runtime_engine": "STANDARD",
                            "autoscale": {
                                "min_workers": 1,
                                "max_workers": 10
                            }
                        }
                    }
                ],
                "git_source": {
                    "git_url": "https://github.com/Labelbox/labelspark.git",
                    "git_provider": "gitHub",
                    "git_branch": "master"
                },
                "format": "MULTI_TASK"
            }

            # Merge the scheduling configuration into the main job payload
            payload.update(schedule_block)
            return payload
        
    # if cluster_id blank or null:
    if new_cluster == True:
        cluster_id = create_all_purpose_cluster(databricks_instance)
        print(f"Created all-purpose cluster with ID: {cluster_id}")
    else:
        print(f"Using existing cluster with ID: {cluster_id}")
    
    if mode == "preview":
        payload = create_preview(dataset_id, table_path, labelbox_api_key, frequency, cluster_id)
    elif mode == "production":
        payload = create_production(dataset_id, table_path, labelbox_api_key, frequency)
    else:
        return f"Invalid mode: {mode}"

    # ----- JOB CREATION -----

    # Formulate the endpoint URL for the Databricks REST API job creation
    url = f"https://{databricks_instance}/api/2.0/jobs/create"

    # Send the POST request to Databricks to create the job
    response = requests.post(url, data=json.dumps(payload), headers=headers)

    # ----- RESPONSE HANDLING -----
    if response.status_code == 200:
        return f"Job created successfully. {response.text}"
    else:
        return f"Failed to create job. Error: {response.text}"

@app.route('/create-databricks-job', methods=['POST'])
def api_create_databricks_job():
    data = request.get_json()
    result = create_databricks_job(data)
    return jsonify({"message": result})

def run():
    app.run(port=5000)

threading.Thread(target=run).start()