From commits-return-71626-archive-asf-public=cust-asf.ponee.io@airflow.apache.org Tue Oct 22 22:09:08 2019 Return-Path: X-Original-To: archive-asf-public@cust-asf.ponee.io Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [207.244.88.153]) by mx-eu-01.ponee.io (Postfix) with SMTP id 3B2C218062C for ; Wed, 23 Oct 2019 00:09:08 +0200 (CEST) Received: (qmail 10206 invoked by uid 500); 22 Oct 2019 22:09:07 -0000 Mailing-List: contact commits-help@airflow.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@airflow.apache.org Delivered-To: mailing list commits@airflow.apache.org Received: (qmail 10197 invoked by uid 99); 22 Oct 2019 22:09:07 -0000 Received: from ec2-52-202-80-70.compute-1.amazonaws.com (HELO gitbox.apache.org) (52.202.80.70) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 22 Oct 2019 22:09:07 +0000 From: GitBox To: commits@airflow.apache.org Subject: [GitHub] [airflow] kaxil commented on a change in pull request #5743: [AIRFLOW-5088][AIP-24] Persisting serialized DAG in DB for webserver scalability Message-ID: <157178214752.937.16362266748998578480.gitbox@gitbox.apache.org> Date: Tue, 22 Oct 2019 22:09:07 -0000 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit kaxil commented on a change in pull request #5743: [AIRFLOW-5088][AIP-24] Persisting serialized DAG in DB for webserver scalability URL: https://github.com/apache/airflow/pull/5743#discussion_r337773140 ########## File path: airflow/models/serialized_dag.py ########## @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# +# 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. + +"""Serialzed DAG table in database.""" + +import hashlib +from datetime import timedelta +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +# from sqlalchemy import Column, Index, Integer, String, Text, JSON, and_, exc +from sqlalchemy import JSON, Column, Index, Integer, String, and_ +from sqlalchemy.sql import exists + +from airflow.models.base import ID_LEN, Base +from airflow.utils import db, timezone +from airflow.utils.log.logging_mixin import LoggingMixin +from airflow.utils.sqlalchemy import UtcDateTime + +if TYPE_CHECKING: + from airflow.models import DAG # noqa: F401; # pylint: disable=cyclic-import + from airflow.serialization import SerializedDAG # noqa: F401 + + +log = LoggingMixin().log + + +class SerializedDagModel(Base): + """A table for serialized DAGs. + + serialized_dag table is a snapshot of DAG files synchronized by scheduler. + This feature is controlled by: + + * ``[core] store_serialized_dags = True``: enable this feature + * ``[core] min_serialized_dag_update_interval = 30`` (s): + serialized DAGs are updated in DB when a file gets processed by scheduler, + to reduce DB write rate, there is a minimal interval of updating serialized DAGs. + * ``[scheduler] dag_dir_list_interval = 300`` (s): + interval of deleting serialized DAGs in DB when the files are deleted, suggest + to use a smaller interval such as 60 + + It is used by webserver to load dagbags when ``store_serialized_dags=True``. + Because reading from database is lightweight compared to importing from files, + it solves the webserver scalability issue. + """ + __tablename__ = 'serialized_dag' + + dag_id = Column(String(ID_LEN), primary_key=True) + fileloc = Column(String(2000), nullable=False) + # The max length of fileloc exceeds the limit of indexing. + fileloc_hash = Column(Integer, nullable=False) + data = Column(JSON, nullable=False) + last_updated = Column(UtcDateTime, nullable=False) + + __table_args__ = ( + Index('idx_fileloc_hash', fileloc_hash, unique=False), + ) + + def __init__(self, dag: 'DAG'): + from airflow.serialization import SerializedDAG # noqa # pylint: disable=redefined-outer-name + + self.dag_id = dag.dag_id + self.fileloc = dag.full_filepath + self.fileloc_hash = self.dag_fileloc_hash(self.fileloc) + self.data = SerializedDAG.to_dict(dag) + self.last_updated = timezone.utcnow() + + @staticmethod + def dag_fileloc_hash(full_filepath: str) -> int: + """"Hashing file location for indexing. + + :param full_filepath: full filepath of DAG file + :return: hashed full_filepath + """ + # hashing is needed because the length of fileloc is 2000 as an Airflow convention, + # which is over the limit of indexing. If we can reduce the length of fileloc, then + # hashing is not needed. + return int.from_bytes( + hashlib.sha1(full_filepath.encode('utf-8')).digest()[-2:], byteorder='big', signed=False) + + @classmethod + @db.provide_session + def write_dag(cls, dag: 'DAG', min_update_interval: Optional[int] = None, session=None): + """Serializes a DAG and writes it into database. + + :param dag: a DAG to be written into database + :param min_update_interval: minimal interval in seconds to update serialized DAG + :param session: ORM Session + """ + log.debug("Writing DAG: %s to the DB", dag) + # Checks if (Current Time - Time when the DAG was written to DB) < min_update_interval + # If Yes, does nothing + # If No or the DAG does not exists, updates / writes Serialized DAG to DB + if min_update_interval is not None: + if session.query(exists().where( + and_(cls.dag_id == dag.dag_id, + (timezone.utcnow() - timedelta(seconds=min_update_interval)) < cls.last_updated)) + ).scalar(): + return + session.merge(cls(dag)) + log.debug("DAG: %s written to the DB", dag) + + @classmethod + @db.provide_session + def read_all_dags(cls, session=None) -> Dict[str, 'SerializedDAG']: + """Reads all DAGs in serialized_dag table. + + :param session: ORM Session + :returns: a dict of DAGs read from database + """ + serialized_dags = session.query(cls) + + dags = {} + for row in serialized_dags: + log.debug("Deserializing DAG: %s", row.dag_id) + dag = row.dag + + # Sanity check. + if dag.dag_id == row.dag_id: + dags[row.dag_id] = dag + else: + log.warning( + "dag_id Mismatch in DB: Row with dag_id '%s' has Serialised DAG " + "with '%s' dag_id", row.dag_id, dag.dag_id) + return dags + + @property + def dag(self): + """The DAG deserialized from the ``data`` column""" + from airflow.serialization import SerializedDAG # noqa # pylint: disable=redefined-outer-name + + if isinstance(self.data, dict): Review comment: >MySQL as of version 5.7 (MariaDB as of the 10.2 series does not) https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.JSON ---------------------------------------------------------------- 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