You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2020/03/12 14:00:32 UTC

[GitHub] [airflow] mik-laj commented on a change in pull request #7217: [AIRFLOW-5946] Store source code in db

mik-laj commented on a change in pull request #7217: [AIRFLOW-5946] Store source code in db
URL: https://github.com/apache/airflow/pull/7217#discussion_r391632828
 
 

 ##########
 File path: airflow/models/dagcode.py
 ##########
 @@ -0,0 +1,147 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import logging
+import os
+import struct
+from datetime import datetime, timedelta
+from typing import Iterable, List
+
+from sqlalchemy import BigInteger, Column, String, UnicodeText, and_, exists
+
+from airflow.exceptions import AirflowException
+from airflow.models import Base
+from airflow.utils import timezone
+from airflow.utils.file import correct_maybe_zipped, open_maybe_zipped
+from airflow.utils.session import provide_session
+from airflow.utils.sqlalchemy import UtcDateTime
+
+log = logging.getLogger(__name__)
+
+
+class DagCode(Base):
+    """A table for DAGs code.
+
+    dag_code table contains code of DAG files synchronized by scheduler.
+    This feature is controlled by:
+
+    * ``[core] store_serialized_dags = True``: enable this feature
+    * ``[core] store_dag_code = True``: enable this feature
+
+    For details on dag serialization see SerializedDagModel
+    """
+    __tablename__ = 'dag_code'
+
+    fileloc_hash = Column(
+        BigInteger, nullable=False, primary_key=True, autoincrement=False)
+    fileloc = Column(String(2000), nullable=False)
+    # The max length of fileloc exceeds the limit of indexing.
+    last_updated = Column(UtcDateTime, nullable=False)
+    source_code = Column(UnicodeText(), nullable=False)
+
+    def __init__(self, full_filepath: str):
+        self.fileloc = full_filepath
+        self.fileloc_hash = DagCode.dag_fileloc_hash(self.fileloc)
+        self.last_updated = timezone.utcnow()
+        self.source_code = DagCode._read_code(self.fileloc)
+
+    @classmethod
+    def _read_code(cls, fileloc: str):
+        with open_maybe_zipped(fileloc, 'r') as source:
+            source_code = source.read()
+        return source_code
+
+    @provide_session
+    def sync_to_db(self, session=None):
+        """Writes code into database.
+
+        :param session: ORM Session
+        """
+        old_version = session.query(
+            DagCode.fileloc, DagCode.fileloc_hash, DagCode.last_updated) \
+            .filter(DagCode.fileloc_hash == self.fileloc_hash) \
+            .first()
+
+        if old_version and old_version.fileloc != self.fileloc:
+            raise AirflowException(
+                "Filename '{}' causes a hash collision in the database with "
+                "'{}'. Please rename the file.".format(
+                    self.fileloc, old_version.fileloc))
+
+        file_modified = datetime.fromtimestamp(
+            os.path.getmtime(correct_maybe_zipped(self.fileloc)), tz=timezone.utc)
+
+        if old_version and (file_modified - timedelta(seconds=120)) < \
+                old_version.last_updated:
+            return
+
+        session.merge(self)
+
+    @classmethod
+    @provide_session
+    def bulk_sync_to_db(cls, filelocs: Iterable[str], session=None):
+        """Writes code in bulk into database.
+
+        :param filelocs: file paths of DAGs to sync
+        :param session: ORM Session
+        """
+        filelocs = set(filelocs)
+        for file in filelocs:
+            DagCode(file).sync_to_db(session=session)
+
+    @classmethod
+    @provide_session
+    def remove_deleted_code(cls, alive_dag_filelocs: List[str], session=None):
+        """Deletes code not included in alive_dag_filelocs.
+
+        :param alive_dag_filelocs: file paths of alive DAGs
+        :param session: ORM Session
+        """
+        alive_fileloc_hashes = [
+            cls.dag_fileloc_hash(fileloc) for fileloc in alive_dag_filelocs]
+
+        log.debug("Deleting code from %s table ", cls.__tablename__)
+
+        session.execute(
+            cls.__table__.delete().where(
 
 Review comment:
   ```suggestion
               session.query(cls).filter(
   ```
   This way you don't need to use magic methods.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services