azure_dag.yml 13 KB
Newer Older
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
# EXPECTED PIPELINE INHERITED GROUP VARIABLES
# --------------------------------------------------------------------------------
# AZURE                     (Protected Branch)
# AZURE_APP_ID              (Protected Branch)
# AZURE_APP_ID_OTHER        (Protected Branch)
# AZURE_APP_OID_OTHER       (Protected Branch)
# AZURE_BASE                (Protected Branch)
# AZURE_BASENAME_21         (Protected Branch)
# AZURE_DNS_NAME            (Protected Branch)
# AZURE_ELASTIC_HOST        (Protected Branch)
# AZURE_ELASTIC_PASSWORD    (Protected Branch/Masked Variable)
# AZURE_INVALID_JWT         (Protected Branch)
# AZURE_NO_ACCESS_ID        (Protected Branch)
# AZURE_NO_ACCESS_SECRET    (Protected Branch/Masked Variable)
# AZURE_PRINCIPAL_ID        (Protected Branch)
# AZURE_PRINCIPAL_SECRET    (Protected Branch/Masked Variable)
# AZURE_REGISTRY            (Protected Branch)
# AZURE_SERVICEBUS_KEY      (Protected Branch/Masked Variable)
# AZURE_STORAGE_KEY         (Protected Branch/Masked Variable)
# AZURE_SUBSCRIPTION_ID     (Protected Branch)
# AZURE_SUBSCRIPTION_NAME   (Protected Branch)
# AZURE_TENANT_ID           (Protected Branch)
# AZURE_APPINSIGHTS_KEY     (Protected Branch/Masked Variable)

# EXPECTED PIPELINE VARIABLES
# --------------------------------------------------------------------------------
# AZURE_TEST_SUBDIR

.azure_variables:
  variables:
    WORKFLOW_URL: https://${AZURE_DNS_NAME}/api/workflow/v1/
    AZURE_AD_TENANT_ID: $AZURE_TENANT_ID
    AZURE_CLIENT_ID: $AZURE_PRINCIPAL_ID
    AZURE_CLIENT_SECRET: $AZURE_PRINCIPAL_SECRET
    AZURE_AD_APP_RESOURCE_ID: $AZURE_APP_ID
    SHARED_TENANT: opendes
    DATA_PARTITION_ID: opendes

# JOBS
# --------------------------------------------------------------------------------

harshit aggarwal's avatar
init    
harshit aggarwal committed
42
43
44
45
azure_test_dag:
  tags: ["osdu-medium"]
  image: $CI_REGISTRY/danielscholl/azure-maven/azure-maven:v1.0
  stage: integration
harshit aggarwal's avatar
harshit aggarwal committed
46
  needs: ["compile-and-unit-test"]
harshit aggarwal's avatar
init    
harshit aggarwal committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  variables:
    AZURE_SERVICE: csv-parser
    AZURE_TENANT_ID: $AZURE_TENANT_ID
    KEYVAULT_URI: $AZURE_KEYVAULT_URI
    partition_service_endpoint: https://${AZURE_DNS_NAME}/api/partition/v1
    storage_service_endpoint: https://${AZURE_DNS_NAME}/api/storage/v2
    schema_service_endpoint: https://${AZURE_DNS_NAME}/api/schema-service/v1
    search_service_endpoint: https://${AZURE_DNS_NAME}/api/search/v2
    unit_service_endpoint: https://${AZURE_DNS_NAME}/api/unit/v2/unit/symbol
    legal_service_endpoint: https://${AZURE_DNS_NAME}/api/legal/v1
    file_service_endpoint: https://${AZURE_DNS_NAME}/api/file/v2
    DMS_KIND: opendes:testcsv:wellbore:1.0.0
    DMS_ACL: data.default.viewers@opendes.contoso.com
    DMS_LEGAL_TAG: opendes-public-usa-dataset-7643990
    aad_client_id: $AZURE_APP_ID
    AZURE_AD_TENANT_ID: $AZURE_TENANT_ID
    AZURE_CLIENT_ID: $AZURE_PRINCIPAL_ID
    AZURE_CLIENT_SECRET: $AZURE_PRINCIPAL_SECRET
    AZURE_AD_APP_RESOURCE_ID: $AZURE_APP_ID
    DATA_PARTITION_ID: opendes

  extends:
    - .azure_variables
  script:
harshit aggarwal's avatar
harshit aggarwal committed
71
72
    - mvn clean install -pl $AZURE_PARSER_BUILD_SUBDIR -am
    - mvn clean verify -f $AZURE_TEST_SUBDIR/pom.xml
harshit aggarwal's avatar
init    
harshit aggarwal committed
73
74
75
76
77
78
79
80
  only:
    variables:
      - $AZURE == 'true'
  except:
    variables:
      - $AZURE_SKIP_TEST == 'true'


81
82
83
84
85
86
87
88
89
# This stage generates the output dag folder by running a docker container which will
# built via Dockerfile present in DAD repository root. This Dockerfile should contain the
# logic to generate all the prerequisite artifacts for the DAG and output all the
# Dag related files in folder

azure_create_dag:
  tags: ["osdu-medium"]
  image: danielscholl/azure-build-image
  stage: containerize
harshit aggarwal's avatar
init    
harshit aggarwal committed
90
  needs: ["azure_test_dag"]
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
  variables:
    PARSER_IMAGE: ${CI_PROJECT_NAME}-${CI_COMMIT_REF_SLUG}:${CI_COMMIT_SHA}
    DAG_IMAGE: ${CI_PROJECT_NAME}-dag-${CI_COMMIT_REF_SLUG}:${CI_COMMIT_SHA}
  extends:
    - .azure_variables
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - az --version
    - az login --service-principal -u $AZURE_PRINCIPAL_ID -p $AZURE_PRINCIPAL_SECRET --tenant $AZURE_TENANT_ID
  script:
    - |
      # Generating environment file to be passed while running the docker container
      cat > .env << EOF
      CI_REGISTRY_USER=${CI_REGISTRY_USER}
      CI_REGISTRY_PASSWORD=${CI_REGISTRY_PASSWORD}
      CI_REGISTRY=${CI_REGISTRY}
      AZURE_REGISTRY=${AZURE_REGISTRY}
      AZURE_PRINCIPAL_ID=${AZURE_PRINCIPAL_ID}
      AZURE_PRINCIPAL_SECRET=${AZURE_PRINCIPAL_SECRET}
      AZURE_TENANT_ID=${AZURE_TENANT_ID}
      CI_PROJECT_NAME=${CI_PROJECT_NAME}
      CI_COMMIT_REF_SLUG=${CI_COMMIT_REF_SLUG}
      CI_COMMIT_SHA=${CI_COMMIT_SHA}
      CI_REGISTRY_IMAGE=${CI_REGISTRY_IMAGE}
      AZURE_DEPLOYMENTS_SCRIPTS_SUBDIR=${AZURE_DEPLOYMENTS_SCRIPTS_SUBDIR}
      PARSER_IMAGE=${PARSER_IMAGE}
      DAG_IMAGE=${DAG_IMAGE}
      SHARED_TENANT=$SHARED_TENANT
      AZURE_DNS_NAME=$AZURE_DNS_NAME
      EOF

    - docker build -t $CI_REGISTRY_IMAGE/$PARSER_IMAGE-orchestrator --file $AZURE_DEPLOYMENTS_SCRIPTS_SUBDIR/dockerFolder/output_dags_dockerfile .

    - |
      # Checking if container with name docker_generate_dags exists then delete
      # Container with a name is required to perform the copy operation below

      if [ "$(docker ps -a | grep docker_generate_dags)" ]; then
        docker stop docker_generate_dags
        docker rm docker_generate_dags
      fi

    - docker run --name "docker_generate_dags" -v /var/run/docker.sock:/var/run/docker.sock --env-file .env $CI_REGISTRY_IMAGE/$PARSER_IMAGE-orchestrator

    # Copying the dag folder from the docker container to he host
    - docker cp "docker_generate_dags:$AZURE_OUTPUT_DAG_FOLDER" .

  artifacts:
    paths:
      - "output_dags"
  only:
    variables:
      - $AZURE == 'true'

azure_copy_dag:
  image: danielscholl/azure-build-image
  tags: ["osdu-medium"]
  stage: deploy
  needs: ["azure_create_dag"]
  extends:
    - .azure_variables
  before_script:
    - az login --service-principal -u $AZURE_PRINCIPAL_ID -p $AZURE_PRINCIPAL_SECRET --tenant $AZURE_TENANT_ID
    - az aks get-credentials -g $AZURE_UNIQUE-rg -n $AZURE_UNIQUE-aks
  script:
    - |
      # Installing the Azcopy utility

      apk add --update coreutils && rm -rf /var/cache/apk/*
      mkdir -p tmp
      cd tmp
      wget -O azcopy_v10.tar.gz https://aka.ms/downloadazcopy-v10-linux && tar -xf azcopy_v10.tar.gz --strip-components=1
      cp ./azcopy /usr/bin/
      cd ..

    - EXPIRE=$(date -u -d "59 minutes" '+%Y-%m-%dT%H:%M:%SZ')
    - START=$(date -u -d "-1 minute" '+%Y-%m-%dT%H:%M:%SZ')

    - accountKey=$(kubectl get secret airflow -n osdu -o jsonpath='{.data.azurestorageaccountkey}' | base64 -d)
    - accountName=$(kubectl get secret airflow -n osdu -o jsonpath='{.data.azurestorageaccountname}' | base64 -d)

    # Generating the SAS Token required for Authorization
    - AZURE_STORAGE_SAS_TOKEN=$(az storage account generate-sas --account-name $accountName  --account-key $accountKey --start $START --expiry $EXPIRE --https-only --resource-types sco --services f --permissions cwdlur -o tsv)
    - cd output_dags

    - |
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
      if [ "$AZURE_DEPLOY_PACKAGED_DAG"  == "true" ]; then
        echo "Packaged Dags are enabled"
        if [ -d "./dags/" ]; then
          # Copying the zipped dag inside the dags folder
          azcopy cp "./dags/*.zip" "https://${accountName}.file.core.windows.net/airflowdags/dags?${AZURE_STORAGE_SAS_TOKEN}"
        fi
      else
          echo "Packaged Dags are disabled"
          if [ -d "./dags/" ]; then
            # Copying all the contents inside the dags folder
            azcopy cp "./dags/*" "https://${accountName}.file.core.windows.net/airflowdags/dags?${AZURE_STORAGE_SAS_TOKEN}" --recursive=true
            cd dags

            # Now syncing only the folders which are part of source to remove the deleted files
            for directory in *; do
              if [ -d "$directory" ]; then
                azcopy sync "./$directory/" "https://${accountName}.file.core.windows.net/airflowdags/dags/$directory?${AZURE_STORAGE_SAS_TOKEN}" --recursive=true --delete-destination=true
              fi
            done
            cd ..
197
198
          fi

199
200
201
202
203
204
205
206
207
208
209
210
211
212
          if [ -d "./plugins/" ]; then
            # Copying all the contents inside the plugins folder
            azcopy cp "./plugins/*" "https://${accountName}.file.core.windows.net/airflowdags/plugins?${AZURE_STORAGE_SAS_TOKEN}" --recursive=true
            cd plugins

            if [ -d "operators" ]; then
              cd operators
              # Syncing only the sub folders which are part of source in operators folder
              for directory in *; do
                if [ -d "$directory" ]; then
                  azcopy sync "./$directory/" "https://${accountName}.file.core.windows.net/airflowdags/plugins/operators/$directory?${AZURE_STORAGE_SAS_TOKEN}" --recursive=true --delete-destination=true
                fi
              done
              cd ..
213
214
            fi

215
216
217
218
219
220
221
222
223
            if [ -d "hooks" ]; then
              cd hooks
              # Syncing only the sub folders which are part of source in hooks folder
              for directory in *; do
                if [ -d "$directory" ]; then
                  azcopy sync "./$directory/" "https://${accountName}.file.core.windows.net/airflowdags/plugins/hooks/$directory?${AZURE_STORAGE_SAS_TOKEN}" --recursive=true --delete-destination=true
                fi
              done
              cd ..
224
            fi
225
226
            cd ..
          fi
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
      fi

  artifacts:
    paths:
      - "output_dags"
  only:
    variables:
      - $AZURE == 'true'

azure_register_dag:
  tags: ["osdu-medium"]
  image: python:3.8
  stage: bootstrap
  needs: ["azure_copy_dag"]
  variables:
    PARSER_IMAGE: ${AZURE_REGISTRY}.azurecr.io/${CI_PROJECT_NAME}-${CI_COMMIT_REF_SLUG}:${CI_COMMIT_SHA}
  extends:
    - .azure_variables
  script:
    - |
      cat > requirements.txt << EOF
      msal
      EOF

    - |
      # Python script for generating the Bearer Token
      cat > Token.py << EOF
      import os
      import msal

      class AzureToken(object):

        def get_azure_id_token(self):
          tenant_id = os.getenv('AZURE_TENANT_ID')
          resource_id = os.getenv('AZURE_AD_APP_RESOURCE_ID')
          client_id = os.getenv('AZURE_CLIENT_ID')
          client_secret = os.getenv('AZURE_CLIENT_SECRET')

          if tenant_id is None:
            print('Please pass tenant Id to generate token')
            exit(1)
          if resource_id is None:
            print('Please pass resource Id to generate token')
            exit(1)
          if client_id is None:
            print('Please pass client Id to generate token')
            exit(1)
          if client_secret is None:
            print('Please pass client secret to generate token')
            exit(1)

          try:
            authority_host_uri = 'https://login.microsoftonline.com'
            authority_uri = authority_host_uri + '/' + tenant_id
            scope = [resource_id + '/.default']
            app = msal.ConfidentialClientApplication(client_id=client_id, authority=authority_uri, client_credential=client_secret)
            result = app.acquire_token_for_client(scopes=scope)
            token = 'Bearer ' +  result.get('access_token')
            print(token)
            return token
          except Exception as e:
            print(e)

      if __name__ == '__main__':
        AzureToken().get_azure_id_token()
      EOF

    - |
      # Python script for registering the DAG by calling Workflow service API
      cat > register_dag.py << EOF

      import json
      import requests
      import os

      class RegisterDag:

        def __init__(self):
          self.token = os.environ.get('BEARER_TOKEN')
          self.data_partition_id = os.environ.get('SHARED_TENANT')
          self.workflow_service_url = os.environ.get('WORKFLOW_URL') + "workflow"

        def register(self):
          self.register_dag()

        def register_dag(self):
          with open('./output_dags/workflow_request_body.json', 'r', encoding='utf-8') as f:
            file_data = json.load(f)

            for data in file_data:
              data = json.dumps(data)

              headers = {
                'Content-Type': 'application/json',
                'Authorization': self.token,
                'data-partition-id': self.data_partition_id
              }

              response = requests.post(self.workflow_service_url, headers=headers, data=data)
              if response.status_code == 200:
                workflow_id = response.json().get('workflowId')
                print("DAG registered with workflowId: {0}".format(workflow_id))
              elif response.status_code == 409:
                workflow_id = response.json().get('workflowId')
                print("DAG is already registered with workflowId: {0}".format(workflow_id))
              else:
                print("Error while registering DAG {0}".format(response.raise_for_status()))
                exit(1)

      if __name__ == "__main__":
        RegisterDag().register()

      EOF

    - pip install -r ./requirements.txt
    - export BEARER_TOKEN=$(python ./Token.py)
    - echo $BEARER_TOKEN
    - python ./register_dag.py

harshit aggarwal's avatar
init    
harshit aggarwal committed
346
347
348
  artifacts:
    paths:
      - "output_dags"
349
350
351
352
353
  only:
    variables:
      - $AZURE == 'true'