#!/usr/bin/env python
#
# Copyright (c) 2016 Samsung Electronics.Co.Ltd.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
"""
BuildMonitor APIs

1. Related files
  (1) gbs submit --------------- [job_submit.py]
  (2) [pre] packae build ------- [on OBS]
  (3) [pre] snapshot create ---- [job_pre_release_obs.py]
  (4) [pre] image creation  ---- [job_imager.py][job_post_imager.py]
  (5) SR accept or reject ------ [job_request.py]
  (6) [post] package build ----- [on OBS]
  (7) [post] snapshot creation - [job_create_snapshot.py]
  (8) [post] image creation ---- [job_imager.py]
  (9) Completed
  * pre : pre build / post : post build

2. function naming rules

[ACTION]_for_[TABLE]

ex) sr_submit_for_sr_status
ACTION : Submit
TABLE  : sr_status

3. db table list

[SR    parts] sr_stage | sr_status | sr_commit | sr_status_details
[BUILD parts] build_snapshot | build_snapshot_package | build_image
"""

import os
import sys
import json
import base64
import re

from datetime import datetime
from time import sleep
from common import buildmonitor_db
from common.buildtrigger import trigger_info, trigger_next, remote_jenkins_build_job
from common.buildmonitor_extention import BuildMonitorExtention, put_snapshot_manifest

class LocalError(Exception):
    """Local error exception."""
    pass

#===============================================================================
# for global variables

INVALID_ID = 0

#===============================================================================
# for info_stage_id

SR_SUBMIT  = 1
TRBS_BUILD = 2
TRBS_SNAP  = 3
TRBS_IMAGE = 4
PRE_BUILD  = 5
PRE_SNAP   = 6
PRE_IMAGE  = 7
SR_ACCEPT  = 8
POST_BUILD = 9
POST_SNAP  = 10
POST_IMAGE = 11

#===============================================================================
# connect & disconnect db

def bm_connect_db():
    buildmonitor_db.connect_db()

def bm_disconnect_db():
    buildmonitor_db.disconnect_db()

#===============================================================================
# for remote trigger from TRBS to PRE/POST
def bm_remote_jenkins_build_job(remote_data):
    print 'remote data(%s)\n' % (remote_data)
    remote_jenkins_build_job(os.getenv('PUBLIC_JENKINS_URL'), \
                             os.getenv('PUBLIC_JENKINS_USER'), \
                             os.getenv('PUBLIC_JENKINS_PW'), \
                             os.getenv('PUBLIC_JOB_NAME'), \
                             os.getenv('PUBLIC_JOB_TOKEN'), \
                             'TRIGGER_INFO=%s\n' \
                             %(base64.b64encode(json.dumps(remote_data))))

def bm_remote_jenkins_build_job_by_file(job, remote_data):
    print 'remote data(%s)\n' % (remote_data)

    with open('TRIGGER_INFO_FILE', 'w') as f:
        f.write(base64.b64encode(json.dumps(remote_data)))

    files = [("TRIGGER_INFO_FILE", "TRIGGER_INFO_FILE")]

    remote_jenkins_build_job(os.getenv('PUBLIC_JENKINS_URL'), \
                             os.getenv('PUBLIC_JENKINS_USER'), \
                             os.getenv('PUBLIC_JENKINS_PW'), \
                             job,
                             os.getenv('PUBLIC_JOB_TOKEN'), \
                             None,
                             files)

#===============================================================================
# [job_submit.py]

def get_src_proj_lst(bm_src_prj_lst):
    print 'enter get_src_proj_lst\n'

    if not os.getenv("DROPPED_PRERELEASE_PROJECTS"):
        print 'no DROPPED_PRERELEASE_PROJECTS!!\n'
        return bm_src_prj_lst

    prefix = 'home:prerelease:'
    dropped_prj_lst = os.getenv("DROPPED_PRERELEASE_PROJECTS").split(',')

    print 'bm_src_prj_lst (%s)\n' % (bm_src_prj_lst)
    removed_lst = []
    for each_src_proj in bm_src_prj_lst:
        for each_dropped_proj in dropped_prj_lst:
            if each_src_proj.startswith(prefix + each_dropped_proj):
                removed_lst.append(each_src_proj)
                break

    # do remove
    print 'removed_lst(%s), do remove!!\n' % (removed_lst)
    bm_src_prj_lst = [x for x in bm_src_prj_lst if x not in removed_lst]

    return bm_src_prj_lst

def truncate_msg(msg):
    MAX_MSG_LEN = int(os.getenv("BUILDMONITOR_MAX_MSG_LEN"))
    ret_msg = (msg[:MAX_MSG_LEN-2] + '..') if len(msg) > MAX_MSG_LEN else msg
    return ret_msg

def transform_date(date):
    # Currently, we just remove timezone part (e.g., '+0900')
    # Should we consider timezone in the future??
    dd = date.split(' ')
    return dd[0]+' '+dd[1]

def sr_submit_for_sr_status(bm_git_tag):
    print 'enter sr_submit_for_sr_status\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    if curr_sr_status_id == INVALID_ID:
        query = "INSERT INTO sr_status (sr, status, submit_time) VALUES(%s, %s, %s)"
        query_data = (bm_git_tag, 'C', datetime.strptime(bm_git_tag[-15:], '%Y%m%d.%H%M%S'))
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'Already existing sr_status_id(%s) skip INSERT sr_stage\n' \
                % (curr_sr_status_id)

def sr_submit_for_sr_commit(commit_date, commit_msg, submit_date, submit_msg,
                            submitter, git_tag, gerrit_project,
                            gerrit_newrev, gerrit_account_name, obs_package_name, status):
    print 'enter sr_submit_for_sr_commit\n'

    # get current_sr_status_id (should be here, after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    obs_pkg_name = obs_package_name
    bm_submitter = submitter.replace('<', '').replace('>', '')

    query = "INSERT INTO sr_commit (sr_status_id, git_repository," \
            "obs_package_name, git_commit_id, git_commit_date, "   \
            "git_commit_message, git_committer, sr_submit_date, "  \
            "sr_submit_message, sr_submitter, status) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, gerrit_project, obs_pkg_name,
                    gerrit_newrev, commit_date, commit_msg,
                    gerrit_account_name, submit_date, submit_msg,
                    bm_submitter, status)
    buildmonitor_db.do_query(query, query_data)

def start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                 bm_end_datetime, pre_build_project_id):
    print 'enter start_pre_build_for_sr_stage\n'

    # get current_sr_status_id (should be here after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [SR_SUBMIT] end stage : SR submit
    info_stage_id = SR_SUBMIT
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, 'S', curr_sr_status_id, info_stage_id, pre_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    ### [PRE_BUILD] start stage : [pre] package build
    bm_start_datetime = bm_end_datetime
    info_stage_id = PRE_BUILD
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime, 'R', pre_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                           bm_end_datetime, pre_build_project_id):
    print 'enter sr_submit_for_sr_stage\n'

    ### [SR_SUBMIT] SR submit
    info_stage_id = SR_SUBMIT
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_end_time, stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime,
                  bm_end_datetime, 'S', pre_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, bm_src_project_lst):
    print 'enter package_build_for_sr_detail_sr_stage\n'

    # get current_sr_status_id (should be here after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### for sr_status_detail & sr_stage
    # bm_src_project_lst is needed for multi profile
    print 'bm_src_project_lst(%s)\n' % (bm_src_project_lst)
    for bm_src_project in bm_src_project_lst:

        # get info_project_id -> get pre_build_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_src_project,)
        info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (info_project_id,)
        pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'info_project_id(%s), pre_build_project_id(%s)\n' \
               % (info_project_id, pre_build_project_id)

        # defensive code for the duplicated build_project_id
        if pre_build_project_id == INVALID_ID:
            print 'cannot find build_project_id!! Adding NOW!!\n'
            query = "INSERT INTO build_project (info_project_id, status) VALUES(%s, %s)"
            query_data = (info_project_id, 'C')
            buildmonitor_db.do_query(query, query_data)
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
            print '[After] info_project_id(%s), pre_build_project_id(%s)\n' \
                   % (info_project_id, pre_build_project_id)

        # get sr_status_detail_id for checking group submit
        query = "SELECT id FROM sr_status_detail WHERE sr_status_id = %s " \
                "AND pre_build_project_id = %s"
        query_data = (curr_sr_status_id, pre_build_project_id)
        sr_status_detail_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        if sr_status_detail_id == INVALID_ID:
            # get pre_build_project_id
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            ### for sr_status_detail
            query = "INSERT INTO sr_status_detail (sr_status_id, pre_build_project_id) " \
                    "VALUES(%s, %s)"
            query_data = (curr_sr_status_id, pre_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [1] start stage
            sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                   bm_end_datetime, pre_build_project_id)
            # [1] end stage / [2] start stage
            start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, pre_build_project_id)
        else:
            # clear the existing tables (sr_stage & build_snapshot)
            print 'Already existing sr_status_id(%s)!! clear the related tables\n' \
                  % (sr_status_detail_id)
            query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND build_project_id = %s"
            query_data = (curr_sr_status_id, pre_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            # get build_snapshot_id for deleting build_snapshot_package & build_image
            query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
            query_data = (pre_build_project_id,)
            build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            # delete build_snapshot & build_snapshot_package & build_image
            query = "DELETE FROM build_snapshot WHERE build_project_id = %s"
            query_data = (pre_build_project_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_snapshot_package WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_image WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [1] start stage
            sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                   bm_end_datetime, pre_build_project_id)
            # [1] end stage / [2] start stage
            start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, pre_build_project_id)

#===============================================================================
# [job_pre_release_obs.py]

def update_fail_status_for_sr_stage(project, bm_git_tag):
    print 'enter update_fail_status_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # Skip updating the fail status if Base project
    if 'base' in project.lower() and 'basechecker' not in project.lower(): 
        sr_stage_status = 'S'

        ### [PRE_SNAP] stage end : update 'S' status
        info_stage_id = PRE_SNAP
        query = "UPDATE sr_stage SET stage_end_time = NOW(), stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (sr_stage_status, curr_sr_status_id, info_stage_id, curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### [PRE_IMAGE] stage end : insert 'S' status
        info_stage_id = PRE_IMAGE
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                "stage_end_time, stage_status, build_project_id) " \
                "VALUES(%s, %s, NOW(), NOW(), %s, %s)"
        query_data = (curr_sr_status_id, info_stage_id,
                      sr_stage_status, curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        print 'This is [Base] project!! All stages are done\n'
    else:
        sr_stage_status = 'F'

        ### [PRE_SNAP] stage end : update 'F' status
        info_stage_id = PRE_SNAP
        query = "UPDATE sr_stage SET stage_end_time = NOW(), stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (sr_stage_status, curr_sr_status_id, info_stage_id, curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)

def update_comment(sr, comment):

    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (sr,)
    parent_sr_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "SELECT submit_time FROM sr_status WHERE sr = %s"
    parent_sr_time = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "SELECT id FROM sr_comment WHERE sr_status_id=%s AND comment=%s"
    query_data = (parent_sr_id, comment)
    #prev_comment_id = buildmonitor_db.do_query(query, query_data)
    prev_comment_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # Do not insert duplicated records
    if prev_comment_id != buildmonitor_db.INVALID_ID: #exist such records
        return

    query = "INSERT INTO sr_comment (sr_status_id, user, comment, commented_date) VALUES(%s, %s, %s, %s)"
    query_data = (parent_sr_id, "Tizen Build Bot", comment, parent_sr_time)
    buildmonitor_db.do_query(query, query_data)

    query = "UPDATE sr_status SET num_comments = num_comments + 1 WHERE sr = %s"
    query_data = (sr,)
    buildmonitor_db.do_query(query, query_data)

def clear_following_stages(sr_status_id, build_project_id, info_stage_id_greater_than=9999):
    query = "DELETE from sr_stage WHERE sr_status_id=%s AND build_project_id=%s AND info_stage_id>%s"
    query_data = (sr_status_id, build_project_id, info_stage_id_greater_than)
    buildmonitor_db.do_query(query, query_data)

def start_pre_create_snapshot_for_sr_stage(project, bm_git_tag, bm_start_datetime, bBuildFail, BuildFailReason):
    print 'enter start_pre_create_snapshot_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    print 'bBuildFail(%s)\n' % (bBuildFail)
    if bBuildFail == True:
        info_stage_status = 'F'
        if BuildFailReason == 'Cycles':
            info_stage_status = 'C'
    else:
        info_stage_status = 'S'

    ### [PRE_BUILD] stage end : [pre] package build
    info_stage_id = PRE_BUILD
    bm_end_datetime = bm_start_datetime
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, info_stage_status, curr_sr_status_id,
                  info_stage_id, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    clear_following_stages(curr_sr_status_id, curr_build_project_id, info_stage_id)

    if info_stage_status == 'S':
        ### [PRE_SNAP] stage start : [pre] snapshot creation
        info_stage_id = PRE_SNAP
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
        query_data = (curr_sr_status_id, info_stage_id,
                      bm_start_datetime, 'R', curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'Build failed!! skip [3] stage start\n'

    # Update notice for cyclic dependency.
    if info_stage_status == 'C':
        update_comment(bm_git_tag, "ERROR! This SR bring about cyclic dependency!")

def start_pre_create_snapshot_for_build_snapshot(project, bm_git_tag, bm_start_datetime):
    print 'enter start_pre_create_snapshot_for_build_snapshot\n'

    # get pre_info_project_id -> get pre_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    pre_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (pre_info_project_id,)
    pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### to check duplicate build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
    query_data = (pre_build_project_id,)
    pre_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    ### for build_snapshot
    if pre_build_snapshot_id == INVALID_ID:
        query = "INSERT INTO build_snapshot (build_project_id, start_time, status) " \
                "VALUES(%s, %s, %s)"
        query_data = (pre_build_project_id, bm_start_datetime, 'R')
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'duplicated build_snapshot_id!! skip insert & clear tables\n'

        ### clear build_snapshot_package & build_image tables
        query = "DELETE FROM build_snapshot_package WHERE build_snapshot_id = %s"
        query_data = (pre_build_snapshot_id,)
        buildmonitor_db.do_query(query, query_data)
        query = "DELETE FROM build_image WHERE build_snapshot_id = %s"
        query_data = (pre_build_snapshot_id,)
        buildmonitor_db.do_query(query, query_data)

        # get curr_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        ### [PRE_SNAP] stage remove : [pre] snapshot creation
        info_stage_id = PRE_SNAP
        query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (curr_sr_status_id, info_stage_id, pre_build_project_id)
        buildmonitor_db.do_query(query, query_data)
        ### [PRE_IMAGE] stage remove : [pre] image creation
        info_stage_id = PRE_IMAGE
        query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (curr_sr_status_id, info_stage_id, pre_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### [PRE_SNAP] stage restart : [pre] snapshot creation
        info_stage_id = PRE_SNAP
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
        query_data = (curr_sr_status_id, info_stage_id,
                      bm_start_datetime, 'R', pre_build_project_id)
        buildmonitor_db.do_query(query, query_data)

def create_snapshot_packages_for_build_snapshot_package(project, bm_repo, bm_arch,
                                                        bm_pkg_url,
                                                        bm_pkg_name_lst,
                                                        bm_pkg_mdate_lst,
                                                        bm_pkg_size_lst,
                                                        bm_trg_count,
                                                        bm_pkg_count,
                                                        BM_PKG_LIMIT):
    print 'enter create_snapshot_packages_for_build_snapshot_package\n'

    # get pre_info_project_id -> get pre_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    pre_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (pre_info_project_id,)
    pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
    query_data = (pre_build_project_id,)
    curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # bulk insert
    query = "INSERT INTO build_snapshot_package (build_snapshot_id, repository, " \
            "arch, package_name, created_date, package_size, package_url) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s)"

    query_list = []
    for each_pkg_name, each_pkg_mdate, each_pkg_size in zip(bm_pkg_name_lst, bm_pkg_mdate_lst, bm_pkg_size_lst):
        timestamp = datetime.fromtimestamp(each_pkg_mdate)
        query_list.append((curr_build_snapshot_id, bm_repo, bm_arch,
                           each_pkg_name, timestamp, each_pkg_size, bm_pkg_url))

    buildmonitor_db.do_many_query(query, query_list)

def end_pre_create_snapshot_for_sr_stage(project, bm_git_tag,
                                         bm_start_datetime, bm_end_datetime):
    print 'enter end_pre_create_snapshot_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [PRE_SNAP] stage end : [pre] snapshot creation
    sr_stage_status = 'S'
    info_stage_id = PRE_SNAP
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, sr_stage_status, curr_sr_status_id,
                  info_stage_id, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    if 'base' in project.lower() and 'basechecker' not in project.lower():
        ### [PRE_IMAGE] stage end : [pre] image creation
        sr_stage_status = 'S'
        print 'This is [Base] project!! sr_stage_status(%s)\n' \
              % (sr_stage_status)
    else:
        ### [PRE_IMAGE] stage start : [pre] image creation
        sr_stage_status = 'R'

    info_stage_id = PRE_IMAGE
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_end_datetime,
                  sr_stage_status, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def end_pre_create_snapshot_for_build_snapshot(project, bm_snapshot_name,
                                               bm_snapshot_url, bm_snapshot_num,
                                               bm_end_datetime):
    print 'enter end_pre_create_snapshot_for_build_snapshot\n'

    # get pre_info_project_id -> get pre_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    pre_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (pre_info_project_id,)
    pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### for build_snapshot
    query = "UPDATE build_snapshot SET snapshot_name = %s, snapshot_url = %s, " \
            "snapshot_num = %s, end_time = %s, status = %s WHERE build_project_id = %s"
    query_data = (bm_snapshot_name, bm_snapshot_url, bm_snapshot_num,
                  bm_end_datetime, 'S', pre_build_project_id)
    buildmonitor_db.do_query(query, query_data)

#===============================================================================
# [job_imager.py]

def update_fail_create_image_for_sr_stage(fields, bm_start_datetime, bm_snapshot_name):
    print 'enter update_fail_create_image_for_sr_stage\n'

    bm_prj_name = fields["project"]
    bm_split_data = fields["project"].split(':')[-1]
    bm_branch_name = fields["project"].split(':')[-2]
    bm_git_tag = 'submit/' + bm_prj_name.split(":submit:")[-1].replace(':', '/')
    bm_url = os.path.join(fields.get('url_pub_base', ''),
                           fields['repo_path'], fields['images_path'])

    bm_end_datetime = datetime.now()
    bm_repo = fields["repo"]
    bm_device_name = fields["name"]

    if 'prerelease' in bm_url:
        # [pre_build] get current_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_info_project_id -> get curr_build_project_id for multi profile
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_prj_name,)
        curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (curr_info_project_id,)
        curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        ### [PRE_IMAGE] stage : update fail status for [pre] image creation
        info_stage_id = PRE_IMAGE
        query = "UPDATE sr_stage SET stage_start_time = %s, stage_end_time = %s, stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (bm_start_datetime, bm_end_datetime, 'F',
                      curr_sr_status_id, info_stage_id, curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### build_image : update fail status for [pre] image creation
        # get pre_build_snapshot_id
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
        query_data = (curr_build_project_id,)
        pre_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # update fail status
        query = "UPDATE build_image SET end_time = %s, status = %s " \
                "WHERE build_snapshot_id = %s AND repository = %s AND device_name = %s"
        query_data = (bm_end_datetime, 'F',
                      pre_build_snapshot_id, bm_repo, bm_device_name)
        buildmonitor_db.do_query(query, query_data)
    else:
        # get post_build_project_id by using bm_snapshot_name
        query = "SELECT build_project_id FROM build_snapshot WHERE snapshot_name = %s"
        query_data = (bm_snapshot_name,)
        post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'post_build_project_id(%s)\n' % (post_build_project_id)
        if post_build_project_id == 0:
            print 'NULL id - Not updating POST_IMAGE stage'
            return

        # get multi_sr_status_id
        query = "SELECT sr_status_id FROM sr_status_detail WHERE post_build_project_id = %s"
        query_data = (post_build_project_id,)
        multi_sr_status_id = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

        ### [POST_IMAGE] stage end : [POST] image creation
        for each_sr_status_id in multi_sr_status_id:
            print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

            if each_sr_status_id == 0:
                print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
                break

            ### [POST_IMAGE] stage : update fail status for [post] image creation
            info_stage_id = POST_IMAGE
            query = "UPDATE sr_stage SET stage_start_time = %s, stage_end_time = %s, stage_status = %s " \
                    "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
            query_data = (bm_start_datetime, bm_end_datetime, 'F',
                          each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
            buildmonitor_db.do_query(query, query_data)

def create_image_for_build_image(fields, bm_start_datetime,
                                 bm_end_datetime, bm_snapshot_name, bm_img_size):
    print 'enter create_image_for_build_image\n'

    bm_repository = fields['repo']
    bm_device_name = fields['name']
    if fields['status'].lower() == 'failed':
        bm_status = 'F'
    else:
        bm_status = 'S'
    bm_url = fields['url']

    # get curr_build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE snapshot_name = %s"
    query_data = (bm_snapshot_name,)
    curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### for build_image
    #TODO: Update it if exists
    query = "SELECT id FROM build_image WHERE build_snapshot_id=%s AND repository=%s AND device_name=%s"
    query_data = (curr_build_snapshot_id, bm_repository, bm_device_name)
    prev_image_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    if prev_image_id != 0:
        query = "UPDATE build_image SET build_snapshot_id=%s, repository=%s, device_name=%s, " \
                "start_time=%s, end_time=%s, status=%s, image_size=%s, image_url=%s " \
                "WHERE id=%s LIMIT 1"
        query_data = (curr_build_snapshot_id, bm_repository, bm_device_name,
                      bm_start_datetime, bm_end_datetime,
                      bm_status, bm_img_size, bm_url, prev_image_id)
        buildmonitor_db.do_query(query, query_data)
    else:
        query = "INSERT INTO build_image (build_snapshot_id, repository, device_name, " \
                "start_time, end_time, status, image_size, image_url) " \
                "VALUES(%s, %s, %s, %s, %s, %s, %s, %s)"
        query_data = (curr_build_snapshot_id, bm_repository, bm_device_name,
                      bm_start_datetime, bm_end_datetime,
                      bm_status, bm_img_size, bm_url)
        buildmonitor_db.do_query(query, query_data)

#===============================================================================
# [job_post_image.py]

def end_create_image_for_sr_stage(bm_start_datetime, project, bm_snapshot_name):
    print 'enter end_create_image_for_sr_stage project(%s)\n' % (project)

    bm_end_datetime = datetime.now()

    if project.startswith("home:prerelease:") or project.startswith("home:trbs:"):
        bm_git_tag = 'submit/' + project.split(":submit:")[-1].replace(':', '/')

        # [pre_build] get current_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_info_project_id -> get curr_build_project_id for multi profile
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (project,)
        curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (curr_info_project_id,)
        curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_build_snapshot_id
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s ORDER BY id DESC LIMIT 1"
        query_data = (curr_build_project_id,)
        curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        # get multi_build_image_status
        query = "SELECT status FROM build_image WHERE build_snapshot_id = %s"
        query_data = (curr_build_snapshot_id,)
        multi_build_image_status = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
        print 'multi_build_image_status(%s)\n' % str(multi_build_image_status)

        isFailed = 0
        for each_build_image_status in multi_build_image_status:
            if each_build_image_status and each_build_image_status[0] == 'F': #pylint: disable=unsubscriptable-object
                isFailed = 1
                print 'isFailed(%s)!! skip updating the sr_stage\n' % (isFailed)

        if isFailed == 0:
            ### [PRE_IMAGE] stage : [pre] image creation
            info_stage_id = PRE_IMAGE
            query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                    "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
            query_data = (bm_end_datetime, 'S',
                          curr_sr_status_id, info_stage_id, curr_build_project_id)
            buildmonitor_db.do_query(query, query_data)
    else:
        # get post_build_project_id by using bm_snapshot_name
        query = "SELECT build_project_id FROM build_snapshot WHERE snapshot_name = %s"
        query_data = (bm_snapshot_name,)
        post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'post_build_project_id(%s)\n' % (post_build_project_id)

        # get curr_build_snapshot_id
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s ORDER BY id DESC LIMIT 1"
        query_data = (post_build_project_id,)
        curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        # get multi_build_image_status
        query = "SELECT status FROM build_image WHERE build_snapshot_id = %s"
        query_data = (curr_build_snapshot_id,)
        multi_build_image_status = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
        print 'multi_build_image_status(%s)\n' % str(multi_build_image_status)

        isFailed = 0
        for each_build_image_status in multi_build_image_status:
            if each_build_image_status and each_build_image_status[0] == 'F': #pylint: disable=unsubscriptable-object
                isFailed = 1
                print 'isFailed(%s)!! skip updating the sr_stage\n' % (isFailed)

        if isFailed == 0:
            if post_build_project_id == 0:
                print 'NULL id - Not updating POST_SNAP/POST_IMAGE stage'
                return
            # get multi_sr_status_id
            query = "SELECT sr_status_id FROM sr_status_detail WHERE post_build_project_id = %s"
            query_data = (post_build_project_id,)
            multi_sr_status_id = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

            ### [POST_SNAP/POST_IMAGE] stage end : [POST] snapshot & image creation
            for each_sr_status_id in multi_sr_status_id:
                print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

                if each_sr_status_id == 0:
                    print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
                    break

                info_stage_id = POST_SNAP
                query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                        "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
                query_data = (bm_end_datetime, 'S',
                              each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
                buildmonitor_db.do_query(query, query_data)

                info_stage_id = POST_IMAGE
                query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                        "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
                query_data = (bm_end_datetime, 'S',
                              each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
                buildmonitor_db.do_query(query, query_data)
#===============================================================================
# [job_request.py]

def sr_accept_for_sr_stage(bm_src_prj_name, bm_target_prj_name,
                           bm_start_datetime, bm_end_datetime, bm_git_tag):
    print 'enter sr_accept_for_sr_stage\n'

    # get current_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (bm_src_prj_name,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [SR_ACCEPT] stage : SR aceept
    info_stage_id = SR_ACCEPT
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, " \
            "stage_start_time, stage_end_time, stage_status, build_project_id) " \
            "VALUES(%s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id,
                  bm_start_datetime, bm_end_datetime, 'S', curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    # get curr_info_project_id -> get post_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (bm_target_prj_name,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get last_bpid_of_build_snapshot
    query = "SELECT bp.id " \
            "FROM build_project bp, info_project ip, build_snapshot bs " \
            "WHERE ip.project_name = %s " \
            "AND ip.id = bp.info_project_id " \
            "AND bp.id = bs.build_project_id " \
            "ORDER BY id desc LIMIT 1"
    query_data = (bm_target_prj_name,)
    last_bpid_of_build_snapshot = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'last_bpid_of_build_snapshot(%s)\n' \
          % (last_bpid_of_build_snapshot)

    # get post_build_project_id
    query = "SELECT bp.id " \
            "FROM build_project bp " \
            "WHERE bp.info_project_id = %s " \
            "AND bp.id > %s " \
            "ORDER BY id LIMIT 1"
    query_data = (curr_info_project_id, last_bpid_of_build_snapshot)
    post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'post_build_project_id(%s)\n' \
          % (post_build_project_id)

    # use the prev last_bpid if there is no post_build_project_id
    if post_build_project_id == 0:
        print 'post_build_project_id is (%s)!! use the previous last_bpid(%s)\n' % \
              (post_build_project_id, last_bpid_of_build_snapshot)
        post_build_project_id = last_bpid_of_build_snapshot

    ### [POST_BUILD] stage start : [post] package build
    info_stage_id = POST_BUILD
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, " \
            "stage_start_time, stage_status, build_project_id) " \
            "VALUES(%s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime,
                  'R', post_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def sr_reject_for_sr_stage(bm_src_prj_name, bm_start_datetime,
                           bm_end_datetime, bm_git_tag):
    print 'enter sr_reject_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (bm_src_prj_name,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [SR_ACCEPT] stage : SR reject
    info_stage_id = SR_ACCEPT
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_end_time, stage_status, build_project_id) " \
            "VALUES(%s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime, bm_end_datetime,
                  'F', curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def sr_accept_reject_for_sr_status_detail(event_fields, bm_start_datetime,
                                          bm_end_datetime, bm_git_tag):
    print 'enter sr_accept_reject_for_sr_status_detail\n'

    obs_req_no = event_fields['id']
    obs_req_comment = truncate_msg(event_fields['description'])
    obs_req_date = bm_end_datetime
    obs_req_status = event_fields['state']
    obs_req_status = obs_req_status.upper()
    bm_src_prj_name = event_fields['sourceproject']
    bm_target_prj_name = event_fields['targetproject']

    if obs_req_status == 'ACCEPTED':
        print '[ACCEPTED] obs_req_status(%s)\n' % (obs_req_status)

        # get pre_info_project_id -> get pre_build_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_src_prj_name,) # should use bm_src_prj_name
        pre_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (pre_info_project_id,)
        pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get post_info_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_target_prj_name,)
        post_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get last_bpid_of_build_snapshot
        query = "SELECT bp.id " \
                "FROM build_project bp, info_project ip, build_snapshot bs " \
                "WHERE ip.project_name = %s " \
                "AND ip.id = bp.info_project_id " \
                "AND bp.id = bs.build_project_id " \
                "ORDER BY id desc LIMIT 1"
        query_data = (bm_target_prj_name,)
        last_bpid_of_build_snapshot = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'last_bpid_of_build_snapshot(%s)\n' \
              % (last_bpid_of_build_snapshot)

        # get post_build_project_id
        query = "SELECT bp.id " \
                "FROM build_project bp " \
                "WHERE bp.info_project_id = %s " \
                "AND bp.id > %s " \
                "ORDER BY id LIMIT 1"
        query_data = (post_info_project_id, last_bpid_of_build_snapshot)
        post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'post_build_project_id(%s)\n' \
              % (post_build_project_id)

        # use the prev last_bpid if there is no post_build_project_id
        if post_build_project_id == 0:
            print 'post_build_project_id is (%s)!! use the previous last_bpid(%s)\n' % \
                  (post_build_project_id, last_bpid_of_build_snapshot)
            post_build_project_id = last_bpid_of_build_snapshot

        ### for sr_status_detail
        query = "UPDATE sr_status_detail SET post_build_project_id = %s, obs_request_no = %s, " \
                "obs_request_comment = %s, obs_request_date = %s, obs_request_status = %s " \
                "WHERE pre_build_project_id = %s"
        query_data = (post_build_project_id, obs_req_no, obs_req_comment,
                      obs_req_date, 'A', pre_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### for sr_stage (now can find the build_project_id of the target prj)
        sr_accept_for_sr_stage(bm_src_prj_name, bm_target_prj_name,
                               bm_start_datetime, bm_end_datetime, bm_git_tag)

    elif obs_req_status == 'DECLINED':
        print '[DECLINED] obs_req_status(%s)\n' \
              % (obs_req_status)

        # get info_project_id -> get pre_build_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_src_prj_name,)
        info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (info_project_id,)
        pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        ### for sr_status_detail
        query = "UPDATE sr_status_detail SET obs_request_no = %s, " \
                "obs_request_comment = %s, obs_request_date = %s, obs_request_status = %s " \
                "WHERE pre_build_project_id = %s"
        query_data = (obs_req_no, obs_req_comment, obs_req_date,
                      'R', pre_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### for sr_stage
        sr_reject_for_sr_stage(bm_src_prj_name, bm_start_datetime,
                               bm_end_datetime, bm_git_tag)

#===============================================================================
# [job_create_snapshot.py]

def update_fail_create_snapshot_for_sr_stage(bm_snapshot_name):
    print 'enter update_fail_create_snapshot_for_sr_stage\n'

    # get post_build_project_id by using bm_snapshot_name
    query = "SELECT build_project_id FROM build_snapshot WHERE snapshot_name = %s"
    query_data = (bm_snapshot_name,)
    post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'post_build_project_id(%s)\n' % (post_build_project_id)

    # get multi_sr_status_id
    query = "SELECT sr_status_id FROM sr_status_detail WHERE post_build_project_id = %s"
    query_data = (post_build_project_id,)
    multi_sr_status_id = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

    # Skip updating the fail status if Base project
    if 'base' in bm_snapshot_name.lower():
        sr_stage_status = 'S'

        for each_sr_status_id in multi_sr_status_id:
            print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

            if each_sr_status_id == 0:
                print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
                break

            ### [POST_SNAP] stage end : update 'S' status
            info_stage_id = POST_SNAP
            query = "UPDATE sr_stage SET stage_end_time = NOW(), stage_status = %s " \
                    "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
            query_data = (sr_stage_status, each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
            buildmonitor_db.do_query(query, query_data)

            ### [POST_IMAGE] stage end : insert 'S' status
            info_stage_id = POST_IMAGE
            query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                    "stage_end_time, stage_status, build_project_id) " \
                    "VALUES(%s, %s, NOW(), NOW(), %s, %s)"
            query_data = (each_sr_status_id[0], info_stage_id, sr_stage_status, post_build_project_id) #pylint: disable=unsubscriptable-object
            buildmonitor_db.do_query(query, query_data)

            print 'This is [Base] project!! All stages are done\n'

    else:
        sr_stage_status = 'F'

        for each_sr_status_id in multi_sr_status_id:
            print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

            if each_sr_status_id == 0:
                print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
                break

            ### [POST_SNAP] stage end : update 'F' status
            info_stage_id = POST_SNAP
            query = "UPDATE sr_stage SET stage_end_time = NOW(), stage_status = %s " \
                    "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
            query_data = (sr_stage_status, each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
            buildmonitor_db.do_query(query, query_data)

def start_create_snapshot_for_sr_stage(project, bm_start_datetime):
    print 'enter start_create_snapshot_for_sr_stage\n'

    # get post_info_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    post_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get last_bpid_of_build_snapshot
    query = "SELECT bp.id " \
            "FROM build_project bp, info_project ip, build_snapshot bs " \
            "WHERE ip.project_name = %s " \
            "AND ip.id = bp.info_project_id " \
            "AND bp.id = bs.build_project_id " \
            "ORDER BY id desc LIMIT 1"
    query_data = (project,)
    last_bpid_of_build_snapshot = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'last_bpid_of_build_snapshot(%s)\n' \
          % (last_bpid_of_build_snapshot)

    # get post_build_project_id
    query = "SELECT bp.id " \
            "FROM build_project bp " \
            "WHERE bp.info_project_id = %s " \
            "AND bp.id > %s " \
            "ORDER BY id LIMIT 1"
    query_data = (post_info_project_id, last_bpid_of_build_snapshot)
    post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'post_build_project_id(%s)\n' \
          % (post_build_project_id)

    # use the prev last_bpid if there is no post_build_project_id
    if post_build_project_id == 0:
        print 'post_build_project_id is (%s)!! use the previous last_bpid(%s)\n' % \
              (post_build_project_id, last_bpid_of_build_snapshot)
        post_build_project_id = last_bpid_of_build_snapshot

    # get multi_sr_status_id
    query = "SELECT sr_status_id FROM sr_status_detail WHERE post_build_project_id = %s"
    query_data = (post_build_project_id,)
    multi_sr_status_id = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

    ### [POST_BUILD] end / [POST_SNAP/POST_IMAGE] start : [post] snapshot creation
    for each_sr_status_id in multi_sr_status_id:
        print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

        if each_sr_status_id == 0:
            print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
            break

        info_stage_id = POST_BUILD
        bm_end_datetime = datetime.now()
        query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (bm_end_datetime, 'S',
                      each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
        buildmonitor_db.do_query(query, query_data)

        info_stage_id = POST_SNAP
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, " \
                "stage_start_time, stage_end_time, stage_status, build_project_id) " \
                "VALUES(%s, %s, %s, %s, %s, %s)"
        query_data = (each_sr_status_id[0], info_stage_id, #pylint: disable=unsubscriptable-object
                      bm_start_datetime, bm_end_datetime, 'R', post_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        info_stage_id = POST_IMAGE
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, " \
                "stage_start_time, stage_end_time, stage_status, build_project_id) " \
                "VALUES(%s, %s, %s, %s, %s, %s)"
        query_data = (each_sr_status_id[0], info_stage_id, #pylint: disable=unsubscriptable-object
                      bm_start_datetime, bm_end_datetime, 'R', post_build_project_id)
        buildmonitor_db.do_query(query, query_data)

def update_build_snapshot_status_info(build_project_id, snapshot_name):

    query = "SELECT id FROM build_snapshot WHERE snapshot_name=%s AND build_project_id=%s "
    query_data = (snapshot_name, build_project_id)
    build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    if build_snapshot_id == 0:
        return

    # Get OBS Build Fail Stat
    query_2 = " " \
              " SELECT bt.repository, bt.arch, ipa.package_name, bpa.id, bpa.build_status, bpa.end_time " \
              " FROM build_project bp, info_project ip, build_target bt, build_package bpa, info_package ipa, build_snapshot bs " \
              " WHERE bp.info_project_id = ip.id " \
              " AND bt.build_project_id = bp.id " \
              " AND bpa.build_target_id = bt.id " \
              " AND bpa.info_package_id = ipa.id " \
              " AND bs.id = %s" \
              " AND bs.snapshot_name = %s " \
              " AND bs.build_project_id = bp.id " \
              " ORDER BY ipa.package_name, bt.repository, bt.arch, bpa.end_time " \
              " "
    query_data_2 = (build_snapshot_id, snapshot_name)
    obs_results = buildmonitor_db.get_multi_values_from_query_data(query_2, query_data_2, verbose=False)

    if obs_results == 0:
        return

    build_list = {}
    for build_result in obs_results:
        if build_result == 0:
            return
        repository           = build_result[0] #pylint: disable=unsubscriptable-object
        arch                 = build_result[1] #pylint: disable=unsubscriptable-object
        package_name         = build_result[2] #pylint: disable=unsubscriptable-object
        package_id           = build_result[3] #pylint: disable=unsubscriptable-object
        package_build_status = build_result[4] #pylint: disable=unsubscriptable-object
        build_time           = build_result[5] #pylint: disable=unsubscriptable-object
        key = "%s,%s" % (repository, arch)
        if package_build_status != "succeeded" and package_build_status != "Building":
            if package_name not in build_list:
                build_list[package_name] = {}
            build_list[package_name][key] = package_build_status
        elif package_name in build_list:
            if key in build_list[package_name]:
                del build_list[package_name][key]
                if len(build_list[package_name]) <= 0:
                    del build_list[package_name]

    # Update it if failed item found
    if len(build_list) > 0:
        fail_info = "fail(%d)" % len(build_list)
        query = "UPDATE build_snapshot SET status_info=%s WHERE id=%s AND snapshot_name=%s LIMIT 1"
        query_data = (fail_info, build_snapshot_id, snapshot_name)
        buildmonitor_db.do_query(query, query_data)

def start_create_snapshot_for_post_build_snapshot(project, bm_snapshot_name,
                                                  bm_start_datetime):
    print 'enter start_create_snapshot_for_post_build_snapshot\n'

    # get post_info_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s ORDER BY id DESC LIMIT 1"
    query_data = (project,)
    post_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get last_bpid_of_build_snapshot
    query = "SELECT bp.id " \
            "FROM build_project bp, info_project ip, build_snapshot bs " \
            "WHERE ip.project_name = %s " \
            "AND ip.id = bp.info_project_id " \
            "AND bp.id = bs.build_project_id " \
            "ORDER BY id desc LIMIT 1"
    query_data = (project,)
    last_bpid_of_build_snapshot = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'last_bpid_of_build_snapshot(%s)\n' \
          % (last_bpid_of_build_snapshot)

    # get post_build_project_id
    query = "SELECT bp.id " \
            "FROM build_project bp " \
            "WHERE bp.info_project_id = %s " \
            "AND bp.id > %s " \
            "ORDER BY id LIMIT 1"
    query_data = (post_info_project_id, last_bpid_of_build_snapshot)
    post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'post_build_project_id(%s)\n' \
          % (post_build_project_id)

    # use the prev last_bpid if there is no post_build_project_id
    if post_build_project_id == 0:
        print 'post_build_project_id is (%s)!! use the previous last_bpid(%s)\n' % \
              (post_build_project_id, last_bpid_of_build_snapshot)
        post_build_project_id = last_bpid_of_build_snapshot

    # insert new post_build_project_id
    query = "INSERT INTO build_snapshot (build_project_id, snapshot_name, " \
            "start_time, status) VALUES(%s, %s, %s, %s)"
    query_data = (post_build_project_id, bm_snapshot_name, bm_start_datetime, 'R')
    buildmonitor_db.do_query(query, query_data)

    # Update summary info of the OBS Build Status
    update_build_snapshot_status_info(post_build_project_id, bm_snapshot_name)

def create_snapshot_packages_for_post_build_snapshot_package(bm_snapshot_name,
                                                             bm_repo, bm_arch,
                                                             bm_pkg_url,
                                                             bm_pkg_name_lst,
                                                             bm_pkg_mdate_lst,
                                                             bm_pkg_size_lst):
    print 'enter create_snapshot_packages_for_post_build_snapshot_package\n'

    # get curr_build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE snapshot_name = %s"
    query_data = (bm_snapshot_name,)
    curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'curr_build_snapshot_id(%s)\n' % (curr_build_snapshot_id)


    # bulk insert
    query = "INSERT INTO build_snapshot_package (build_snapshot_id, repository, arch, " \
            "package_name, created_date, package_size, package_url) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s)"

    query_list = []
    for each_pkg_name, each_pkg_mdate, each_pkg_size in zip(bm_pkg_name_lst, bm_pkg_mdate_lst, bm_pkg_size_lst):
        timestamp = datetime.fromtimestamp(each_pkg_mdate)
        # post build
        query_list.append((curr_build_snapshot_id, bm_repo, bm_arch,
                           each_pkg_name, timestamp, each_pkg_size, bm_pkg_url))

    buildmonitor_db.do_many_query(query, query_list)

def end_create_snapshot_create_images_for_sr_stage(bm_snapshot_name,
                                                   bm_start_datetime,
                                                   bm_end_datetime):
    print 'enter end_create_snapshot_create_images_for_sr_stage\n'

    ### [POST_SNAP/POST_IMAGE] end : [post] snapshot creation / [post] image creation

    # get post_build_project_id by using bm_snapshot_name
    query = "SELECT build_project_id FROM build_snapshot WHERE snapshot_name = %s"
    query_data = (bm_snapshot_name,)
    post_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print 'post_build_project_id(%s)\n' % (post_build_project_id)

    # get multi_sr_status_id
    query = "SELECT sr_status_id FROM sr_status_detail WHERE post_build_project_id = %s"
    query_data = (post_build_project_id,)
    multi_sr_status_id = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

    for each_sr_status_id in multi_sr_status_id:
        print 'each_sr_status_id(%s)\n' % (each_sr_status_id)

        if each_sr_status_id == 0:
            print 'each_sr_status_id is zero!! skip updating the sr_stage\n'
            break

        ### [POST_SNAP] stage end : update 'S' status
        sr_stage_status = 'S'
        info_stage_id = POST_SNAP
        query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (bm_end_datetime, sr_stage_status,
                      each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
        buildmonitor_db.do_query(query, query_data)

        ### [POST_IMAGE] stage end : update 'S' or 'R' status
        if 'base' in bm_snapshot_name.lower():
            sr_stage_status = 'S'
            print 'This is [Base] project!! sr_stage_status(%s)\n' \
                  % (sr_stage_status)
        else:
            sr_stage_status = 'R'

        info_stage_id = POST_IMAGE
        query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (bm_end_datetime, sr_stage_status,
                      each_sr_status_id[0], info_stage_id, post_build_project_id) #pylint: disable=unsubscriptable-object
        buildmonitor_db.do_query(query, query_data)

def end_create_snapshot_for_post_build_snapshot(bm_end_datetime,
                                                bm_snapshot_url,
                                                bm_snapshot_name):
    print 'enter end_create_snapshot_for_post_build_snapshot\n'

    # update the build_snapshot data
    query = "UPDATE build_snapshot SET snapshot_url = %s, " \
            "end_time = %s, status = %s WHERE snapshot_name = %s"
    query_data = (bm_snapshot_url, bm_end_datetime, 'S', bm_snapshot_name)
    buildmonitor_db.do_query(query, query_data)

def update_duplicated_package_warning(bm_snapshot_name, duplicated):

    if duplicated is not None and len(duplicated) > 0:
        # Add git repository
        for git_repo in duplicated:
            query = "INSERT INTO git_repository (name) SELECT * FROM (SELECT %s) AS tmp WHERE NOT EXISTS (SELECT name FROM git_repository WHERE name = %s) LIMIT 1"
            buildmonitor_db.do_query(query, (git_repo, git_repo))

        git_repo_str = "%s" % "','".join(duplicated)
        param_count_str = ','.join(["%s"] * len(duplicated))
        query = "SELECT id FROM git_repository WHERE name IN (%s)" % param_count_str
        query_data = set(duplicated)
        rows = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
        if rows == 0:
            return
        git_repo_ids = []
        for x in rows:
            git_repo_ids.append("%s" % x)
  
        query = "SELECT status_info FROM build_snapshot WHERE snapshot_name=%s "
        query_data = (bm_snapshot_name, )
        existing_info = buildmonitor_db.get_value_from_query_data(query, query_data)
        if existing_info == 0 or existing_info is None:
            info_str = "dup(%s)" % ",".join(git_repo_ids)
        else:
            info_str = "%s dup(%s)" % (existing_info, ",".join(git_repo_ids))
        query = "UPDATE build_snapshot SET status_info=%s WHERE snapshot_name=%s LIMIT 1"
        query_data = (info_str, bm_snapshot_name)
        buildmonitor_db.do_query(query, query_data)
        sys.stdout.flush()

def update_build_fail_reason_warning(bm_snapshot_name, bm_buildfailreason):

    if bm_buildfailreason is None or bm_buildfailreason == '':
        return

    query = "SELECT status_info FROM build_snapshot WHERE snapshot_name=%s "
    query_data = (bm_snapshot_name, )
    existing_info = buildmonitor_db.get_value_from_query_data(query, query_data)
    if existing_info == 0 or existing_info is None:
        info_str = bm_buildfailreason
    else:
        info_str = "%s %s" % (existing_info, bm_buildfailreason)
    query = "UPDATE build_snapshot SET status_info=%s WHERE snapshot_name=%s LIMIT 1"
    query_data = (info_str, bm_snapshot_name)
    buildmonitor_db.do_query(query, query_data)

def update_base_build_id(bm_snapshot_name, bm_base_build_id):

    query = "UPDATE build_snapshot dest, (SELECT id FROM build_snapshot WHERE snapshot_name=%s) src " \
            " SET dest.base_build_id = src.id WHERE dest.snapshot_name=%s "
    query_data = (bm_base_build_id, bm_snapshot_name)
    buildmonitor_db.do_query(query, query_data)

def update_sr_submit_log(sr_submit_log_id, sr_tag, status, status_reason):
    print "update_str_submit_log %s, %s, %s\n" % (sr_submit_log_id, sr_tag, status_reason)

    query = "UPDATE sr_submit_log SET status=%s,sr_tag=%s,reason=%s WHERE id=%s"
    query_data = (status, sr_tag, status_reason, sr_submit_log_id)
    buildmonitor_db.do_query(query, query_data)

def update_sr_submit_log_completed(git_tag):
    print "update_sr_submit_log_completed %s\n" % (git_tag)

    query = "UPDATE sr_submit_log SET status='Completed' WHERE sr_tag=%s ORDER BY id DESC LIMIT 1"
    query_data = (git_tag,)
    buildmonitor_db.do_query(query, query_data)

def update_repa(sr_tag, profile, status, status_reason):
    print "update_repa %s, %s, %s, %s\n", (sr_tag, profile, status, status_reason)

    query = "UPDATE sr_accept_log SET status=%s,status_reason=%s WHERE sr=%s AND profile=%s ORDER BY id DESC LIMIT 1"
    query_data = (status, status_reason, sr_tag, profile)
    buildmonitor_db.do_query(query, query_data)

def update_build_log(content):
    project = content.get('project')
    repo = content.get('repo')
    base_url = content.get('base_url')
    pkgs = content.get('pkgs')

    print "update build log %s %s %s\n" % (project, repo, base_url)
    query = "SELECT bt.id, ipa.id, bt.arch, ipa.package_name "+ \
        "FROM info_project ip, build_project bp, build_target bt, info_package ipa "+\
        "WHERE bp.info_project_id = ip.id "+ \
        "AND bt.build_project_id = bp.id "+\
        "AND ipa.info_project_id = ip.id "+\
        "AND ip.project_name = %s "+ \
        "AND bt.repository = %s ORDER BY bt.id"
    query_data = (project, repo)
    rows = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
    id_data = {}
    for row in rows:
        if len(row) == 1:
            raise LocalError("Got no data! exiting...\n")
        build_target_id = row[0] #pylint: disable=unsubscriptable-object
        info_package_id = row[1] #pylint: disable=unsubscriptable-object
        arch = row[2] #pylint: disable=unsubscriptable-object
        package_name = row[3] #pylint: disable=unsubscriptable-object

        if arch not in id_data:
            id_data[arch] = {}
        if package_name not in id_data[arch]:
            id_data[arch][package_name] = {}

        id_data[arch][package_name]['bt_id'] = build_target_id
        id_data[arch][package_name]['ipa_id'] = info_package_id

    for arch in pkgs.keys():
        for pkg in pkgs[arch].keys():
            build_log_url = os.path.join(base_url, pkgs[arch][pkg])
            print 'build_log %s %s %s\n' % (arch, pkg, build_log_url)
            query = "UPDATE build_package SET build_log_url=%s WHERE build_target_id=%s AND info_package_id=%s"
            build_target_id = id_data[arch][pkg]['bt_id']
            info_package_id = id_data[arch][pkg]['ipa_id']
            query_data = (build_log_url, build_target_id, info_package_id)
            buildmonitor_db.do_query(query, query_data)

def update_release_snapshot(content):
    snapshot = content.get('snapshot_name')
    release_type = content.get('release_type')
    version = content.get('version')

    print "update snapshot %s as a %s release with version %s" % (snapshot, release_type, version)
    query = "UPDATE build_snapshot SET {release_type}=%s WHERE snapshot_name=%s".format(release_type=release_type)
    query_data = (version, snapshot)
    buildmonitor_db.do_query(query, query_data)

def update_gbsfullbuild_snapshot(content):
    snapshot = content.get('snapshot_name')
    gbsfullbuild_string = content.get('gbsfullbuild_string')

    print "update snapshot %s as a gbsfullbuild string is %s" % (snapshot, gbsfullbuild_string)
    query = "UPDATE build_snapshot SET gbsfullbuild=%s WHERE snapshot_name=%s"
    query_data = (gbsfullbuild_string, snapshot)
    buildmonitor_db.do_query(query, query_data)

def start_gbsdbbuild(content):
    gbsbuild_tag = content.get('gbsbuild_tag')
    trigger_category = content.get('trigger_category')
    obs_prj = content.get('obs_prj')

    #get info_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (obs_prj,)
    info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    #set gbs_build_project
    query = "INSERT INTO gbs_build_project (info_project_id, gbsbuild_tag, trigger_category, stage) VALUES(%s, %s, %s, 'Building')"
    query_data = (info_project_id,gbsbuild_tag,trigger_category)
    buildmonitor_db.do_query(query, query_data)

    #get gbs_build_project_id
    query = "SELECT id FROM gbs_build_project WHERE gbsbuild_tag = %s"
    query_data = (gbsbuild_tag,)
    gbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

def update_gbsdbbuild_target(content):
    repository = content.get('repository')
    architecture = content.get('architecture')
    start_time = content.get('bm_start_datetime')
    end_time = content.get('bm_end_datetime')
    gbsbuild_tag = content.get('gbsbuild_tag')
    status = content.get('gbs_build_status')
    status_reason = content.get('status_reason')

    #get gbsbuild_tag from gbs_build_project, repository_id from build_repository_name
    #and arch_id from build_arch_name
    query = "SELECT gbp.id, brn.id, ban.id "\
            "FROM gbs_build_project gbp, build_repository_name brn, build_arch_name ban "\
            "WHERE gbp.gbsbuild_tag= %s and brn.repository= %s and ban.arch = %s "\
            "ORDER BY gbp.id DESC LIMIT 1"
    query_data = (gbsbuild_tag,repository,architecture)
    query_result = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
    (gbs_build_project_id,repository_id,arch_id) = query_result[0]

    #set gbs_build_target
    query = "INSERT INTO gbs_build_target"\
            "(gbs_build_project_id, repository, arch, start_time, end_time, status, status_reason)"\
            " VALUES(%s, %s, %s, %s, %s, %s, %s)"
    query_data = (gbs_build_project_id,repository_id,arch_id,start_time,end_time,status,status_reason)
    buildmonitor_db.do_query(query, query_data)

def update_gbs_build_package(content):
    gbsbuild_tag = content.get('gbsbuild_tag')
    bm_repo = content.get('bm_repo')
    bm_arch = content.get('bm_arch')
    bm_pkg_git_repo_list = content.get('bm_pkg_git_repo_list')
    bm_pkg_git_commit_id_list = content.get('bm_pkg_git_commit_id_list')
    bm_pkg_spec_name_list = content.get('bm_pkg_spec_name_list')
    bm_pkg_rpm_name_list = content.get('bm_pkg_rpm_name_list')
    bm_pkg_build_time_list = content.get('bm_pkg_build_time_list')
    bm_pkg_status_list = content.get('bm_pkg_status_list')
    bm_pkg_status_reason_list = content.get('bm_pkg_status_reason_list')
    bm_trg_count = content.get('bm_trg_count')
    bm_pkg_count = content.get('bm_pkg_count')
    BM_PKG_LIMIT = content.get('BM_PKG_LIMIT')

    # get gbs_build_target_id
    query = "SELECT gbt.id FROM gbs_build_target gbt, "\
            "gbs_build_project gbp, build_repository_name brn, build_arch_name ban "\
            "WHERE gbp.gbsbuild_tag = %s and brn.repository = %s and ban.arch = %s " \
            "and gbt.gbs_build_project_id = gbp.id and gbt.repository = brn.id and gbt.arch = ban.id "\
            "ORDER BY gbp.id DESC LIMIT 1"
    query_data = (gbsbuild_tag,bm_repo,bm_arch)
    gbs_build_target_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    print "gbs_build_target_id: %s" %gbs_build_target_id

    query_data=()
    query = "SELECT gc.id,gc.commit_id,gr.name FROM git_commit gc, git_repository gr WHERE "
    for each_pkg_git_repo,each_pkg_commit_id in zip(bm_pkg_git_repo_list,bm_pkg_git_commit_id_list):
        query += "gr.name = %s and gc.commit_id = %s or "
        query_data+=(each_pkg_git_repo,each_pkg_commit_id,)
    query = query.rstrip("or ")

    query_result = buildmonitor_db.get_multi_values_from_query_data(query, query_data)

    git_id_dic = {}
    for each_result in query_result:
        print "git repo db: git_id: %s git_commit_id: %s git_repository: %s"\
               %(each_result[0],each_result[1],each_result[2]) #pylint: disable=unsubscriptable-object
        git_id_dic[each_result[2]] = each_result[0] #pylint: disable=unsubscriptable-object

    # bulk insert
    query = "INSERT INTO gbs_build_package (gbs_build_target_id, git_id, " \
            "spec_name, rpm_name, build_time, status, status_reason) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s)"

    query_list = []
    for each_pkg_git_repo,each_pkg_spec_name,each_pkg_rpm_name,each_pkg_build_time,each_pkg_status,each_pkg_status_reason in zip(bm_pkg_git_repo_list,bm_pkg_spec_name_list,bm_pkg_rpm_name_list,bm_pkg_build_time_list,bm_pkg_status_list,bm_pkg_status_reason_list):
        query_list.append((gbs_build_target_id, git_id_dic[each_pkg_git_repo], each_pkg_spec_name,
                           each_pkg_rpm_name, each_pkg_build_time, each_pkg_status,
                           each_pkg_status_reason))

    buildmonitor_db.do_many_query(query, query_list)

def update_gbsdbbuild_snapshot(content):
    bm_stage = content.get('bm_stage')
    snapshot_name = content.get('snapshot_name')
    snapshot_url = content.get('snapshot_url')
    start_time = content.get('bm_start_datetime')
    end_time = content.get('bm_end_datetime')
    status_reason = content.get('status_reason')
    gbsbuild_tag = content.get('gbsbuild_tag')

    #get gbs_build_project_id
    query = "SELECT id FROM gbs_build_project WHERE gbsbuild_tag = %s "\
            "ORDER BY id DESC LIMIT 1"
    query_data = (gbsbuild_tag,)
    gbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    if bm_stage == 'GBSDBBuild_Snapshot_Start':
        #set gbs_build_snapshot
        query = "INSERT INTO gbs_build_snapshot "\
                "(gbs_build_project_id, snapshot_name, snapshot_url, start_time, status) "\
                "VALUES(%s, %s, %s, %s, 'R')"
        query_data = (gbs_build_project_id,snapshot_name,snapshot_url,start_time)
        buildmonitor_db.do_query(query, query_data)

    elif bm_stage == 'GBSDBBuild_Snapshot_End' or bm_stage == 'GBSDBBuild_Snapshot_Failed':
        if bm_stage == 'GBSDBBuild_Snapshot_End':
            status = 'S'
        elif bm_stage == 'GBSDBBuild_Snapshot_Failed':
            status = 'F'
        #update status of gbs_build_snapshot
        query = "UPDATE gbs_build_snapshot SET end_time = %s, status = %s, status_reason = %s WHERE gbs_build_project_id = %s"
        query_data = (end_time,status,status_reason,gbs_build_project_id)
        buildmonitor_db.do_query(query, query_data)

def update_gbsdbbuild_image(content):
    fields = content.get('fields')
    bm_stage = content.get('bm_stage')
    image_status = content.get('status')
    start_time = content.get('bm_start_datetime')
    end_time = content.get('bm_end_datetime')
    build_id = content.get('build_id')
    image_size = content.get('bm_img_size')

    repository = fields['repo']
    ks_name = fields['name']
    image_url = fields['url']

    #get gbs_build_snapshot_id and repository_id
    query = "SELECT gbs.id, brn.id FROM gbs_build_snapshot gbs, build_repository_name brn "\
            "WHERE gbs.snapshot_name = %s and brn.repository = %s "\
            "ORDER by gbs.id DESC LIMIT 1"
    query_data = (build_id,repository)
    query_result = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
    (gbs_build_snapshot_id,repository_id) = query_result[0]

    #set gbs_build_image
    query = "INSERT INTO gbs_build_image "\
            "(gbs_build_snapshot_id, repository, ks_name, start_time, end_time, status, image_size, image_url) "\
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s)"
    query_data = (gbs_build_snapshot_id,repository_id,ks_name,start_time,end_time,image_status,image_size,image_url)
    buildmonitor_db.do_query(query, query_data)

def update_unresolvable_broken_packages(project, unresolvable_broken_packages):

    if unresolvable_broken_packages is None:
        return

    nowtime = datetime.now()
    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)

    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s ORDER BY id DESC LIMIT 1"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    for repo in unresolvable_broken_packages:
        for arch in unresolvable_broken_packages[repo]:
            bulk_packages = []
            for p in unresolvable_broken_packages[repo][arch]:
                status = unresolvable_broken_packages[repo][arch][p]

                # INSERT build_target_id if not present
                query = "SELECT id FROM build_target WHERE build_project_id=%s AND repository=%s "\
                        "AND arch=%s ORDER BY id DESC LIMIT 1"
                query_data = (curr_build_project_id, repo, arch)
                curr_build_target_id = buildmonitor_db.get_value_from_query_data(query, query_data)

                if curr_build_target_id == INVALID_ID:
                    query = "INSERT INTO build_target (build_project_id, repository, arch, "\
                            "start_time, end_time, status, status_reason, last_flag) "\
                            "VALUES (%s, %s, %s, NOW(), NOW(), 'S', '', 'Y')"
                    query_data = (curr_build_project_id, repo, arch)
                    buildmonitor_db.do_query(query, query_data)

                    query = "SELECT id FROM build_target WHERE build_project_id=%s AND repository=%s "\
                            "AND arch=%s ORDER BY id DESC LIMIT 1"
                    query_data = (curr_build_project_id, repo, arch)
                    curr_build_target_id = buildmonitor_db.get_value_from_query_data(query, query_data)

                # INSERT package if package is not present.
                query = "SELECT id FROM info_package WHERE info_project_id=%s AND package_name=%s "\
                        "AND active_flag='Y' ORDER BY id DESC LIMIT 1"
                query_data = (curr_info_project_id, p)
                curr_info_package_id = buildmonitor_db.get_value_from_query_data(query, query_data)

                if curr_info_package_id == INVALID_ID:
                    query = "INSERT INTO info_package (info_project_id,package_name,description,"\
                            "latest_sr_status_id,active_flag) VALUES (%s, %s, %s, %s, %s)"
                    query_data = (curr_info_project_id, p, "", 0, 'Y')
                    buildmonitor_db.do_query(query, query_data)

                    query = "SELECT id FROM info_package WHERE info_project_id=%s AND package_name=%s "\
                            "AND active_flag='Y' ORDER BY id DESC LIMIT 1"
                    query_data = (curr_info_project_id, p)
                    curr_info_package_id = buildmonitor_db.get_value_from_query_data(query, query_data)

                bulk_packages.append((curr_build_target_id, curr_info_package_id, nowtime, nowtime, status))
            query = "INSERT INTO build_package (build_target_id, info_package_id, start_time," \
                    "end_time, build_status) "\
                    "VALUES (%s, %s, %s, %s, %s)"
            buildmonitor_db.do_many_query(query, bulk_packages)

def update_snapshot_manifest(snapshot_name, manifestdata, datetime):

    print 'enter update_snapshot_manifest\n'
    if snapshot_name and manifestdata:
        bm_ext = BuildMonitorExtention()
        #INSERT MANIFEST DATA TO BUILDMONITOR 
        put_snapshot_manifest(bm_ext, snapshot_name, manifestdata, datetime)

#===============================================================================
# [TRBS][job_submit.py]

def TRBS_start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                      bm_end_datetime, trbs_build_project_id):
    print 'enter TRBS_start_pre_build_for_sr_stage\n'

    # get current_sr_status_id (should be here after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [SR_SUBMIT] end stage : SR submit
    info_stage_id = SR_SUBMIT
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, 'S', curr_sr_status_id, info_stage_id, trbs_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    ### [TRBS_BUILD] start stage : [trbs] package build
    bm_start_datetime = bm_end_datetime
    info_stage_id = TRBS_BUILD
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime, 'R', trbs_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def TRBS_sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                           bm_end_datetime, trbs_build_project_id):
    print 'enter TRBS_sr_submit_for_sr_stage\n'

    ### [SR_SUBMIT] SR submit
    info_stage_id = SR_SUBMIT
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_end_time, stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_start_datetime,
                  bm_end_datetime, 'S', trbs_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def TRBS_package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, bm_src_project_lst):
    print 'enter TRBS_package_build_for_sr_detail_sr_stage\n'

    # get current_sr_status_id (should be here after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # Wait 60 seconds to find the info_project_id

    ### for sr_status_detail & sr_stage
    # bm_src_project_lst is needed for multi profile
    print 'bm_src_project_lst(%s)\n' % (bm_src_project_lst)
    for bm_src_project in bm_src_project_lst:
        # get info_project_id -> get trbs_build_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_src_project,)
        info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (info_project_id,)
        trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'info_project_id(%s), trbs_build_project_id(%s)\n' \
               % (info_project_id, trbs_build_project_id)

        # defensive code for the duplicated build_project_id
        if trbs_build_project_id == INVALID_ID:
            print 'cannot find build_project_id!! Adding NOW!!\n'
            query = "INSERT INTO build_project (info_project_id, status) VALUES(%s, %s)"
            query_data = (info_project_id, 'C')
            buildmonitor_db.do_query(query, query_data)
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
            print '[After] info_project_id(%s), trbs_build_project_id(%s)\n' \
                   % (info_project_id, trbs_build_project_id)

        # get sr_status_detail_id for checking group submit
        query = "SELECT id FROM sr_status_detail WHERE sr_status_id = %s " \
                "AND trbs_build_project_id = %s"
        query_data = (curr_sr_status_id, trbs_build_project_id)
        sr_status_detail_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        if sr_status_detail_id == INVALID_ID:
            # get trbs_build_project_id
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            ### for sr_status_detail
            query = "INSERT INTO sr_status_detail (sr_status_id, trbs_build_project_id) " \
                    "VALUES(%s, %s)"
            query_data = (curr_sr_status_id, trbs_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [SR_SUBMIT] start stage
            TRBS_sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                   bm_end_datetime, trbs_build_project_id)
            # [SR_SUBMIT] end stage / [TRBS_BUILD] start stage
            TRBS_start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, trbs_build_project_id)
        else:
            # clear the existing tables (sr_stage & build_snapshot)
            print 'Already existing sr_status_id(%s)!! clear the related tables\n' \
                  % (sr_status_detail_id)
            query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND build_project_id = %s"
            query_data = (curr_sr_status_id, trbs_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            # get build_snapshot_id for deleting build_snapshot_package & build_image
            query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
            query_data = (trbs_build_project_id,)
            build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            # delete build_snapshot & build_snapshot_package & build_image
            query = "DELETE FROM build_snapshot WHERE build_project_id = %s"
            query_data = (trbs_build_project_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_snapshot_package WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_image WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [SR_SUBMIT] start stage
            TRBS_sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                        bm_end_datetime, trbs_build_project_id)
            # [SR_SUBMIT] end stage / [TRBS_BUILD] start stage
            TRBS_start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                              bm_end_datetime, trbs_build_project_id)

#===============================================================================
# [TRBS][job_pre_release_obs.py]

def TRBS_update_fail_status_for_sr_stage(project, bm_git_tag):
    print 'enter TRBS_update_fail_status_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [TRBS_SNAP] stage end : update fail status [trbs] snapshot creation
    info_stage_id = TRBS_SNAP
    query = "UPDATE sr_stage SET stage_status = %s WHERE sr_status_id = %s " \
            "AND info_stage_id = %s AND build_project_id = %s"
    query_data = ('F', curr_sr_status_id, info_stage_id, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def TRBS_start_pre_create_snapshot_for_sr_stage(project, bm_git_tag, bm_start_datetime, bBuildFail):
    print 'enter TRBS_start_pre_create_snapshot_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    print 'bBuildFail(%s)\n' % (bBuildFail)
    if bBuildFail == True:
        info_stage_status = 'F'
    else:
        info_stage_status = 'S'

    ### [TRBS_BUILD] stage end : [trbs] package build
    info_stage_id = TRBS_BUILD
    bm_end_datetime = bm_start_datetime
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, info_stage_status, curr_sr_status_id,
                  info_stage_id, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    if info_stage_status == 'S':
        ### [TRBS_SNAP] stage start : [trbs] snapshot creation
        info_stage_id = TRBS_SNAP
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
        query_data = (curr_sr_status_id, info_stage_id,
                      bm_start_datetime, 'R', curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'Build failed!! skip [TRBS_SNAP] stage start\n'

def TRBS_start_pre_create_snapshot_for_build_snapshot(project, bm_git_tag, bm_start_datetime):
    print 'enter TRBS_start_pre_create_snapshot_for_build_snapshot\n'

    # get pre_info_project_id -> get trbs_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    pre_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (pre_info_project_id,)
    trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### to check duplicate build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
    query_data = (trbs_build_project_id,)
    trbs_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### for build_snapshot
    if trbs_build_snapshot_id == INVALID_ID:
        query = "INSERT INTO build_snapshot (build_project_id, start_time, status) " \
                "VALUES(%s, %s, %s)"
        query_data = (trbs_build_project_id, bm_start_datetime, 'R')
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'duplicated build_snapshot_id!! skip insert & clear tables\n'

        ### clear build_snapshot_package & build_image tables
        query = "DELETE FROM build_snapshot_package WHERE build_snapshot_id = %s"
        query_data = (trbs_build_snapshot_id,)
        buildmonitor_db.do_query(query, query_data)
        query = "DELETE FROM build_image WHERE build_snapshot_id = %s"
        query_data = (trbs_build_snapshot_id,)
        buildmonitor_db.do_query(query, query_data)

        # get curr_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        ### [TRBS_SNAP] stage remove : [trbs] snapshot creation
        info_stage_id = TRBS_SNAP
        query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (curr_sr_status_id, info_stage_id, trbs_build_project_id)
        buildmonitor_db.do_query(query, query_data)
        ### [TRBS_IMAGE] stage remove : [trbs] image creation
        info_stage_id = TRBS_IMAGE
        query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (curr_sr_status_id, info_stage_id, trbs_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### [TRBS_SNAP] stage restart : [trbs] snapshot creation
        info_stage_id = TRBS_SNAP
        query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
                "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
        query_data = (curr_sr_status_id, info_stage_id,
                      bm_start_datetime, 'R', trbs_build_project_id)
        buildmonitor_db.do_query(query, query_data)

def TRBS_create_snapshot_packages_for_build_snapshot_package(project, bm_repo, bm_arch,
                                                        bm_pkg_url,
                                                        bm_pkg_name_lst,
                                                        bm_pkg_mdate_lst,
                                                        bm_pkg_size_lst,
                                                        bm_trg_count,
                                                        bm_pkg_count,
                                                        BM_PKG_LIMIT):
    print 'enter TRBS_create_snapshot_packages_for_build_snapshot_package\n'

    # get trbs_info_project_id -> get trbs_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    trbs_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (trbs_info_project_id,)
    trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_build_snapshot_id
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
    query_data = (trbs_build_project_id,)
    curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # bulk insert
    query = "INSERT INTO build_snapshot_package (build_snapshot_id, repository, " \
            "arch, package_name, created_date, package_size, package_url) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s)"

    query_list = []
    for each_pkg_name, each_pkg_mdate, each_pkg_size in zip(bm_pkg_name_lst, bm_pkg_mdate_lst, bm_pkg_size_lst):
        timestamp = datetime.fromtimestamp(each_pkg_mdate)
        query_list.append((curr_build_snapshot_id, bm_repo, bm_arch,
                           each_pkg_name, timestamp, each_pkg_size, bm_pkg_url))

    buildmonitor_db.do_many_query(query, query_list)

def TRBS_end_pre_create_snapshot_for_sr_stage(project, bm_git_tag,
                                         bm_start_datetime, bm_end_datetime):
    print 'enter TRBS_end_pre_create_snapshot_for_sr_stage\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # get curr_info_project_id -> get curr_build_project_id for multi profile
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (curr_info_project_id,)
    curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### [TRBS_SNAP] stage end : [trbs] snapshot creation
    info_stage_id = TRBS_SNAP
    query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
            "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
    query_data = (bm_end_datetime, 'S', curr_sr_status_id,
                  info_stage_id, curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

    ### [TRBS_IMAGE] stage start : [trbs] image creation
    info_stage_id = TRBS_IMAGE
    query = "INSERT INTO sr_stage (sr_status_id, info_stage_id, stage_start_time, " \
            "stage_status, build_project_id) VALUES(%s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, info_stage_id, bm_end_datetime,
                  'R', curr_build_project_id)
    buildmonitor_db.do_query(query, query_data)

def TRBS_end_pre_create_snapshot_for_build_snapshot(project, bm_snapshot_name,
                                                    bm_snapshot_url, bm_snapshot_num,
                                                    bm_end_datetime):
    print 'enter TRBS_end_pre_create_snapshot_for_build_snapshot\n'

    # get trbs_info_project_id -> get trbs_build_project_id
    query = "SELECT id FROM info_project WHERE project_name = %s"
    query_data = (project,)
    trbs_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    query = "SELECT id FROM build_project WHERE info_project_id = %s"
    query_data = (trbs_info_project_id,)
    trbs_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    ### for build_snapshot
    query = "UPDATE build_snapshot SET snapshot_name = %s, snapshot_url = %s, " \
            "snapshot_num = %s, end_time = %s, status = %s WHERE build_project_id = %s"
    query_data = (bm_snapshot_name, bm_snapshot_url, bm_snapshot_num,
                  bm_end_datetime, 'S', trbs_build_project_id)
    buildmonitor_db.do_query(query, query_data)

#===============================================================================
# [TRBS][job_imager.py]

def TRBS_update_fail_create_image_for_sr_stage(fields, bm_start_datetime):
    print 'enter TRBS_update_fail_create_image_for_sr_stage\n'

    bm_prj_name = fields["project"]
    bm_split_data = fields["project"].split(':')[-1]
    bm_branch_name = fields["project"].split(':')[-2]
    bm_git_tag = 'submit/' + bm_prj_name.split(":submit:")[-1].replace(':', '/')
    bm_url = os.path.join(fields.get('url_pub_base', ''),
                           fields['repo_path'], fields['images_path'])

    bm_end_datetime = datetime.now()
    bm_repo = fields["repo"]
    bm_device_name = fields["name"]

    if 'prerelease' in bm_url:
        # [trbs_build] get current_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_info_project_id -> get curr_build_project_id for multi profile
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_prj_name,)
        curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (curr_info_project_id,)
        curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        ### [TRBS_IMAGE] stage : update fail status for [trbs] image creation
        info_stage_id = TRBS_IMAGE
        query = "UPDATE sr_stage SET stage_start_time = %s, stage_end_time = %s, stage_status = %s " \
                "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
        query_data = (bm_start_datetime, bm_end_datetime, 'F',
                      curr_sr_status_id, info_stage_id, curr_build_project_id)
        buildmonitor_db.do_query(query, query_data)

        ### build_image : update fail status for [trbs] image creation
        # get curr_build_snapshot_id
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
        query_data = (curr_build_project_id,)
        curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # update fail status
        query = "UPDATE build_image SET end_time = %s, status = %s " \
                "WHERE build_snapshot_id = %s AND repository = %s AND device_name = %s"
        query_data = (bm_end_datetime, 'F',
                      curr_build_snapshot_id, bm_repo, bm_device_name)
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'There is no postrelease stage in TRBS system\n'

#===============================================================================
# [TRBS][job_post_image.py]

def TRBS_end_create_image_for_sr_stage(bm_start_datetime, project):
    print 'enter TRBS_end_create_image_for_sr_stage project(%s)\n' % (project)

    if project.startswith("home:prerelease:") or project.startswith("home:trbs:"):
        bm_end_datetime = datetime.now()
        bm_git_tag = 'submit/' + project.split(":submit:")[-1].replace(':', '/')

        # [trbs_build] get current_sr_status_id
        query = "SELECT id FROM sr_status WHERE sr = %s"
        query_data = (bm_git_tag,)
        curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_info_project_id -> get curr_build_project_id for multi profile
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (project,)
        curr_info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (curr_info_project_id,)
        curr_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        # get curr_build_snapshot_id
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
        query_data = (curr_build_project_id,)
        curr_build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        # get multi_build_image_status
        query = "SELECT status FROM build_image WHERE build_snapshot_id = %s"
        query_data = (curr_build_snapshot_id,)
        multi_build_image_status = buildmonitor_db.get_multi_values_from_query_data(query, query_data)
        print 'multi_build_image_status(%s)\n' % (multi_build_image_status)

        isFailed = 0
        for each_build_image_status in multi_build_image_status:
            if each_build_image_status and each_build_image_status[0] == 'F': #pylint: disable=unsubscriptable-object
                isFailed = 1
                print 'isFailed(%s)!! skip updating the sr_stage\n' % (isFailed)

        if isFailed == 0:
            ### [TRBS_IMAGE] stage : [trbs] image creation
            info_stage_id = TRBS_IMAGE
            query = "UPDATE sr_stage SET stage_end_time = %s, stage_status = %s " \
                    "WHERE sr_status_id = %s AND info_stage_id = %s AND build_project_id = %s"
            query_data = (bm_end_datetime, 'S',
                          curr_sr_status_id, info_stage_id, curr_build_project_id)
            buildmonitor_db.do_query(query, query_data)
    else:
        print 'There is no postrelease stage in TRBS system\n'

#==================================================================================
# Sync_SR

def sync_sr_submit_for_sync_sr_map(bm_sync_git_tag, bm_member_git_tag_list, source_snapshot_name=None):
    print 'enter sync_sr_submit_for_sync_sr_map\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_sync_git_tag,)
    sync_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_member_git_tag_list,)
    member_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    #Fake snapshot name
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s AND snapshot_name = %s"
    query_data = ('0', source_snapshot_name,)
    build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    if build_snapshot_id == INVALID_ID:
        query = "INSERT INTO build_snapshot (build_project_id, snapshot_name) " \
                "VALUES(%s, %s)"
        query_data = ('0', source_snapshot_name)
        buildmonitor_db.do_query(query, query_data)
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s AND snapshot_name = %s"
        query_data = ('0', source_snapshot_name,)
        build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "INSERT INTO sync_sr_map (sync_sr_status_id, member_sr_status_id, build_snapshot_id) VALUES(%s, %s, %s)"
    query_data = (sync_sr_status_id, member_sr_status_id, build_snapshot_id)
    buildmonitor_db.do_query(query, query_data)

#==================================================================================
# Base_chacker
def base_checker_sr_submit_for_sync_sr_map(bm_sync_git_tag, bm_member_git_tag_list, source_snapshot_name=None):
    print 'enter create_sr_submit_for_basechecker_sr_map\n'

    #sync_type
    bm_sync_type = "B"

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_sync_git_tag,)
    sync_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_member_git_tag_list,)
    member_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    #Fake snapshot name
    query = "SELECT id FROM build_snapshot WHERE build_project_id = %s AND snapshot_name = %s"
    query_data = ('0', source_snapshot_name,)
    build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)
    if build_snapshot_id == INVALID_ID:
        query = "INSERT INTO build_snapshot (build_project_id, snapshot_name) " \
                "VALUES(%s, %s)"
        query_data = ('0', source_snapshot_name)
        buildmonitor_db.do_query(query, query_data)
        query = "SELECT id FROM build_snapshot WHERE build_project_id = %s AND snapshot_name = %s"
        query_data = ('0', source_snapshot_name,)
        build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "INSERT INTO sync_sr_map (sync_sr_status_id, member_sr_status_id, build_snapshot_id, sync_type) VALUES(%s, %s, %s, %s)"
    query_data = (sync_sr_status_id, member_sr_status_id, build_snapshot_id, bm_sync_type)
    buildmonitor_db.do_query(query, query_data)

def sync_sr_submit_for_sr_status(bm_git_tag):
    print 'enter sync_sr_submit_for_sr_status\n'

    # get curr_sr_status_id
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (bm_git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    if curr_sr_status_id == INVALID_ID:
        query = "INSERT INTO sr_status (sr, status, submit_time) VALUES(%s, %s, %s)"
        query_data = (bm_git_tag, 'C', datetime.strptime(bm_git_tag[-15:], '%Y%m%d.%H%M%S'))
        buildmonitor_db.do_query(query, query_data)
    else:
        print 'Already existing sr_status_id(%s) skip INSERT sr_stage\n' \
                % (curr_sr_status_id)

def sync_sr_submit_for_sr_commit(commit_date, commit_msg, submit_date, submit_msg,
                                 submitter, git_tag, gerrit_project,
                                 gerrit_newrev, gerrit_account_name):
    print 'enter sync_sr_submit_for_sr_commit\n'

    # get current_sr_status_id (should be here, after sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    print 'gerrit_project(%s)\n' % (gerrit_project)
    if gerrit_project[0] == '-':
        print 'mixed git(%s)\n' % (gerrit_project)
        gerrit_project = gerrit_project[1:]
        obs_pkg_name = os.path.basename(gerrit_project) + '(mixed)'
    elif gerrit_project[0] == '+':
        print 'pure git(%s)\n' % (gerrit_project)
        gerrit_project = gerrit_project[1:]
        obs_pkg_name = os.path.basename(gerrit_project[1:])
    elif gerrit_project == "N/A":
        print 'Sync SR(%s)\n' % (gerrit_project)
        obs_pkg_name = "N/A"
    else:
        print 'no mixed marker "+" or "-", will be set as default(%s)\n' \
              % (gerrit_project)
        obs_pkg_name = os.path.basename(gerrit_project)

    bm_submitter = submitter.replace('<', '').replace('>', '')
    print 'bm_submitter(%s) obs_pkg_name(%s)' \
          % (bm_submitter, obs_pkg_name)

    query = "INSERT INTO sr_commit (sr_status_id, git_repository," \
            "obs_package_name, git_commit_id, git_commit_date, "   \
            "git_commit_message, git_committer, sr_submit_date, "  \
            "sr_submit_message, sr_submitter) " \
            "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    query_data = (curr_sr_status_id, gerrit_project, obs_pkg_name,
                    gerrit_newrev, commit_date, commit_msg,
                    gerrit_account_name, submit_date, submit_msg,
                    bm_submitter)
    buildmonitor_db.do_query(query, query_data)

def sync_package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
                                              bm_end_datetime, bm_src_project_lst):
    print 'enter sync_package_build_for_sr_detail_sr_stage\n'

    # get current_sr_status_id (should be here after sync_sr_submit_for_sr_status)
    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (git_tag,)
    curr_sr_status_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    # Wait 60 seconds to find the info_project_id

    ### for sr_status_detail & sr_stage
    # bm_src_project_lst is needed for multi profile
    print 'bm_src_project_lst(%s)\n' % (bm_src_project_lst)
    for bm_src_project in bm_src_project_lst:
        # get info_project_id -> get pre_build_project_id
        query = "SELECT id FROM info_project WHERE project_name = %s"
        query_data = (bm_src_project,)
        info_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        query = "SELECT id FROM build_project WHERE info_project_id = %s"
        query_data = (info_project_id,)
        pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
        print 'info_project_id(%s), pre_build_project_id(%s)\n' \
               % (info_project_id, pre_build_project_id)

        # defensive code for the duplicated build_project_id
        if pre_build_project_id == INVALID_ID:
            print 'cannot find build_project_id!! Adding NOW!!\n'
            query = "INSERT INTO build_project (info_project_id, status) VALUES(%s, %s)"
            query_data = (info_project_id, 'C')
            buildmonitor_db.do_query(query, query_data)
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)
            print '[After] info_project_id(%s), pre_build_project_id(%s)\n' \
                   % (info_project_id, pre_build_project_id)

        # get sr_status_detail_id for checking group submit
        query = "SELECT id FROM sr_status_detail WHERE sr_status_id = %s " \
                "AND pre_build_project_id = %s"
        query_data = (curr_sr_status_id, pre_build_project_id)
        sr_status_detail_id = buildmonitor_db.get_value_from_query_data(query, query_data)

        if sr_status_detail_id == INVALID_ID:
            # get pre_build_project_id
            query = "SELECT id FROM build_project WHERE info_project_id = %s"
            query_data = (info_project_id,)
            pre_build_project_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            ### for sr_status_detail
            query = "INSERT INTO sr_status_detail (sr_status_id, pre_build_project_id) " \
                    "VALUES(%s, %s)"
            query_data = (curr_sr_status_id, pre_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [1] start stage
            sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                   bm_end_datetime, pre_build_project_id)
            # [1] end stage / [2] start stage
            start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, pre_build_project_id)
        else:
            # clear the existing tables (sr_stage & build_snapshot)
            print 'Already existing sr_status_id(%s)!! clear the related tables\n' \
                  % (sr_status_detail_id)
            query = "DELETE FROM sr_stage WHERE sr_status_id = %s AND build_project_id = %s"
            query_data = (curr_sr_status_id, pre_build_project_id)
            buildmonitor_db.do_query(query, query_data)

            # get build_snapshot_id for deleting build_snapshot_package & build_image
            query = "SELECT id FROM build_snapshot WHERE build_project_id = %s"
            query_data = (pre_build_project_id,)
            build_snapshot_id = buildmonitor_db.get_value_from_query_data(query, query_data)

            # delete build_snapshot & build_snapshot_package & build_image
            query = "DELETE FROM build_snapshot WHERE build_project_id = %s"
            query_data = (pre_build_project_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_snapshot_package WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)
            query = "DELETE FROM build_image WHERE build_snapshot_id = %s"
            query_data = (build_snapshot_id,)
            buildmonitor_db.do_query(query, query_data)

            ### for sr_stage for multi profile
            # [1] start stage
            sr_submit_for_sr_stage(curr_sr_status_id, bm_start_datetime,
                                   bm_end_datetime, pre_build_project_id)
            # [1] end stage / [2] start stage
            start_pre_build_for_sr_stage(git_tag, bm_start_datetime,
                                         bm_end_datetime, pre_build_project_id)

def sync_sr_update_comment(sr, email, bm_member_sr_info):

    query = "SELECT id FROM sr_status WHERE sr = %s"
    query_data = (sr,)
    parent_sr_id = buildmonitor_db.get_value_from_query_data(query, query_data)

    query = "SELECT submit_time FROM sr_status WHERE sr = %s"
    parent_sr_time = buildmonitor_db.get_value_from_query_data(query, query_data)

    if parent_sr_id != INVALID_ID:
        comment = ''
        sr_mapping = {}
        for pname in bm_member_sr_info:
            for item in bm_member_sr_info[pname]:
                if item.get('snapshot', 'SYNC') not in sr_mapping:
                    sr_mapping[item.get('snapshot', 'SYNC')] = [item.get('git_tag')]
                else:
                    if item.get('git_tag') not in sr_mapping[item.get('snapshot', 'SYNC')]:
                        sr_mapping[item.get('snapshot', 'SYNC')].append(item.get('git_tag'))
        for snapshot in sr_mapping:
            comment = '%s\n%s:' % (comment, snapshot)
            for _sr in sr_mapping[snapshot]:
                query = "SELECT id FROM sr_status WHERE sr = %s"
                query_data = (_sr,)
                _sr_id = buildmonitor_db.get_value_from_query_data(query, query_data)
                comment = '%s%s,' % (comment, _sr_id)
        print comment

        query = "INSERT INTO sr_comment (sr_status_id, user, comment, commented_date) VALUES(%s, %s, %s, %s)"
        query_data = (parent_sr_id, email.replace('<', '').replace('>', ''), comment, parent_sr_time)
        buildmonitor_db.do_query(query, query_data)

        #query = "UPDATE sr_status SET num_comments = num_comments + 1 WHERE sr = %s"
        #query_data = (sr,)
        #buildmonitor_db.do_query(query, query_data)

#==================================================================================
def main():
    """
    Script entry point.
    """
    bm_connect_db()

    # check TRBS Sender mode
    if not os.getenv("TRBS_BUILDMONITOR_ENABLED"):
        trbs_buildmonitor_enabled = 0
        print 'TRBS_BUILDMONITOR_ENABLED does not exist!!, set the public mode forcely(%s)\n' \
              % trbs_buildmonitor_enabled
    else:
        trbs_buildmonitor_enabled = int(os.getenv("TRBS_BUILDMONITOR_ENABLED"))
        print 'TRBS_BUILDMONITOR_ENABLED is %s\n' % trbs_buildmonitor_enabled

    # prevent base64 decoding error when triggered by the remote host
    trigger_info_data = os.getenv('TRIGGER_INFO').replace(' ', '+')

    if trigger_info_data:
        content = trigger_info(trigger_info_data)
    else:
        print 'trigger_info_data is empty!!(%s)\n' \
              % (trigger_info_data)
        return 1

    bm_stage = content.get("bm_stage")

    #=======================================================
    # Add_Tag
    if bm_stage == "Add_Tag":
        print '[Add_Tag]\n'
        sr_submit_log_id = content.get("sr_submit_log_id")
        sr_tag = content.get("sr_tag")
        status = content.get("status")
        status_reason = content.get("status_reason")

        update_sr_submit_log(sr_submit_log_id, sr_tag, status, status_reason)

    #=======================================================
    # Submit
    elif bm_stage == 'Submit' or bm_stage == '[TRBS]_Submit':
        print '[Submit]\n'

        # get vars
        commit_date = transform_date(content.get("commit_date"))
        commit_msg = truncate_msg(content.get("commit_msg"))
        submit_date = transform_date(content.get("submit_date"))
        submit_msg = truncate_msg(content.get("submit_msg"))
        submitter = content.get("submitter")
        status = content.get("status")
        git_tag = content.get("git_tag")
        obs_package_name = content.get("obs_package_name")
        gerrit_project = content.get("gerrit_project")
        gerrit_newrev = content.get("gerrit_newrev")
        gerrit_account_name = content.get("gerrit_account_name")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        #bm_src_project_lst = get_src_proj_lst(content.get("bm_src_project_lst"))
        bm_src_project_lst = content.get("bm_src_project_lst")

        # func call
        ### sr_status -> sr_commit -> sr_stage & sr_status_detail
        sr_submit_for_sr_status(git_tag)
        sr_submit_for_sr_commit(commit_date, commit_msg, submit_date, submit_msg,
                                submitter, git_tag, gerrit_project,
                                gerrit_newrev, gerrit_account_name, obs_package_name, status)

        if bm_stage == 'Submit':
            print '[Submit]\n'
            package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
                                                 bm_end_datetime,
                                                 bm_src_project_lst)
        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Submit':
            print '[[TRBS]_Submit]\n'
            TRBS_package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
                                                      bm_end_datetime,
                                                      bm_src_project_lst)

        update_sr_submit_log_completed(git_tag)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Submit'
            bm_remote_jenkins_build_job(remote_data)

    #=======================================================
    # Sync_SR_Submit
    elif bm_stage == 'Sync_SR_Submit':
        print '[Sync_SR_Submit]\n'

        # get vars
        commit_date = transform_date(content.get("commit_date"))
        commit_msg = truncate_msg(content.get("commit_msg"))
        submit_date = transform_date(content.get("submit_date"))
        submit_msg = truncate_msg(content.get("submit_msg"))
        submitter = content.get("submitter")
        gerrit_project = content.get("gerrit_project")
        gerrit_newrev = content.get("gerrit_newrev")
        gerrit_account_name = content.get("gerrit_account_name")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_src_project_lst = content.get("bm_src_project_lst")

        bm_member_sr_info = content.get("bm_member_sr_info")
        print 'bm_member_sr_info(%s)\n' % (bm_member_sr_info)
        bm_sync_git_tag = content.get("bm_sync_git_tag")
        print 'bm_sync_git_tag(%s)\n' % (bm_sync_git_tag)

        # func call
        ### 1. bm_sync_git_tag (sr_status + sr_commit + sr_status_detail + sr_stage)
        sync_sr_submit_for_sr_status(bm_sync_git_tag)
        sync_sr_submit_for_sr_commit(commit_date, commit_msg, submit_date, submit_msg,
                                     submitter, bm_sync_git_tag, gerrit_project,
                                     gerrit_newrev, gerrit_account_name)
        sync_package_build_for_sr_detail_sr_stage(bm_sync_git_tag, bm_start_datetime,
                                                 bm_end_datetime,
                                                 bm_src_project_lst)

        ### 2. bm_member_git_tag_list (sr_status + sr_commit)
        for each_project in bm_member_sr_info:
            print '  tester_project: %s' % each_project
            print '  submit_list:'
            for item in bm_member_sr_info[each_project]:
                _sr        = item.get('git_tag')
                _cid       = item.get('cid')
                _rev       = item.get('rev')
                _submitter = item.get('submitter')
                _project   = item.get('gerrit_project')
                _package   = item.get('package')
                _snapshot  = item.get('snapshot')
                print '    SR:%s' % item.get('git_tag')
                print '    CID:%s' % item.get('cid')
                print '    REV:%s' % item.get('rev')
                print '    SUBMITTER:%s' % item.get('submitter')
                print '    PROJECT:%s' % item.get('gerrit_project')
                print '    PACKAGE:%s' % item.get('package')
                print '    SNAPSHOT:%s' % item.get('snapshot')

                # member_sr for [sr_status] table
                sync_sr_submit_for_sr_status(_sr)

                # member sr & sync_sr for [sync_sr_map] table
                sync_sr_submit_for_sync_sr_map(bm_sync_git_tag, _sr, _snapshot)

                # member sr for [sr_commit]
                sync_sr_submit_for_sr_commit(commit_date, commit_msg,
                                             submit_date, submit_msg,
                                             _submitter, _sr,
                                             _project, _rev,
                                             gerrit_account_name)

        #update_sr_submit_log_completed(git_tag)

        # Update log for tracing
        #sync_sr_update_comment(bm_sync_git_tag, submitter, bm_member_sr_info)

    #=======================================================
    # Sync_SR_Submit_BaseCheck
    elif bm_stage == 'Sync_SR_Submit_BaseCheck':
        print '[Sync_SR_Submit_baseCheck]\n'

        # get vars
        commit_date = transform_date(content.get("commit_date"))
        commit_msg = truncate_msg(content.get("commit_msg"))
        submit_date = transform_date(content.get("submit_date"))
        submit_msg = truncate_msg(content.get("submit_msg"))
        submitter = content.get("submitter")
        gerrit_project = content.get("gerrit_project")
        gerrit_newrev = content.get("gerrit_newrev")
        gerrit_account_name = content.get("gerrit_account_name")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_src_project_lst = content.get("bm_src_project_lst")

        bm_member_sr_info = content.get("bm_member_sr_info")
        print 'bm_member_sr_info(%s)\n' % (bm_member_sr_info)
        bm_sync_git_tag = content.get("bm_sync_git_tag")
        bm_sync_git_tag_list = content.get("git_tag_list")
        print 'bm_sync_git_tag(%s)\n' % (bm_sync_git_tag)

        # func call
        ### 1. bm_sync_git_tag (sr_status + sr_commit + sr_status_detail + sr_stage)
        sync_sr_submit_for_sr_status(bm_sync_git_tag)
        sync_sr_submit_for_sr_commit(commit_date, commit_msg, submit_date, submit_msg,
                                     submitter, bm_sync_git_tag, gerrit_project,
                                     gerrit_newrev, gerrit_account_name)
        sync_package_build_for_sr_detail_sr_stage(bm_sync_git_tag, bm_start_datetime,
                                                 bm_end_datetime,
                                                 bm_src_project_lst)


        # member sr & sync_sr for [sync_sr_map] table
        for git in bm_sync_git_tag_list:
            base_checker_sr_submit_for_sync_sr_map(bm_sync_git_tag, git)

    #=======================================================
    # [PRE] Build
    #=======================================================
    # [PRE] Snap
    elif bm_stage == 'Pre_Snap_Start' or bm_stage == '[TRBS]_Pre_Snap_Start':
        print '[Pre_Snap_Start]\n'

        # get vars
        project = content.get("project")
        bm_git_tag = content.get("bm_git_tag")
        bm_start_datetime = content.get("bm_start_datetime")
        bBuildFail = content.get("bBuildFail")
        BuildFailReason = content.get("BuildFailReason", None)
        unresolvable_broken_packages = content.get("unresolvable_broken_packages")

        # func call
        if bm_stage == 'Pre_Snap_Start':
            print '[Pre_Snap_Start]\n'
            start_pre_create_snapshot_for_sr_stage(project, bm_git_tag, bm_start_datetime, bBuildFail, BuildFailReason)

        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Pre_Snap_Start':
            print '[[TRBS]_Pre_Snap_Start]\n'
            TRBS_start_pre_create_snapshot_for_sr_stage(project, bm_git_tag, bm_start_datetime, bBuildFail)

        # if bBuildFail is True then skip Creating images
        if bBuildFail != True:
            if bm_stage == 'Pre_Snap_Start':
                start_pre_create_snapshot_for_build_snapshot(project, bm_git_tag, bm_start_datetime)

            # [17_0110] TRBS
            if bm_stage == '[TRBS]_Pre_Snap_Start':
                TRBS_start_pre_create_snapshot_for_build_snapshot(project, bm_git_tag, bm_start_datetime)
        else:
            print 'Build failed!! skip insert build_snapshot_id\n'

        update_unresolvable_broken_packages(project, unresolvable_broken_packages)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Pre_Snap_Start'
            bm_remote_jenkins_build_job(remote_data)

    elif bm_stage == 'Pre_Snap_End' or bm_stage == '[TRBS]_Pre_Snap_End':
        print '[Pre_Snap_End]\n'

        # get vars
        project = content.get("project")
        bm_git_tag = content.get("bm_git_tag")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_snapshot_url = content.get("bm_snapshot_url")
        bm_snapshot_num = content.get("bm_snapshot_num")


        # func call
        if bm_stage == 'Pre_Snap_End':
            print '[Pre_Snap_End]\n'
            end_pre_create_snapshot_for_sr_stage(project, bm_git_tag,
                                                          bm_start_datetime,
                                                          bm_end_datetime)
            end_pre_create_snapshot_for_build_snapshot(project,
                                                       bm_snapshot_name,
                                                       bm_snapshot_url,
                                                       bm_snapshot_num,
                                                       bm_end_datetime)

        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Pre_Snap_End':
            print '[[TRBS]_Pre_Snap_End]\n'
            TRBS_end_pre_create_snapshot_for_sr_stage(project, bm_git_tag,
                                                               bm_start_datetime,
                                                               bm_end_datetime)
            TRBS_end_pre_create_snapshot_for_build_snapshot(project,
                                                            bm_snapshot_name,
                                                            bm_snapshot_url,
                                                            bm_snapshot_num,
                                                            bm_end_datetime)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Pre_Snap_End'
            bm_spl_data = os.getenv('BUILDMONITOR_SPIN_URL')
            if bm_spl_data in bm_snapshot_url:
                remote_data['bm_snapshot_url'] = bm_snapshot_url.split(bm_spl_data)[1]
            else:
                print 'check the bm_spl_data(%s)!!\n' \
                      % (bm_spl_data)
            bm_remote_jenkins_build_job(remote_data)

    elif bm_stage == 'Pre_Snap_packages' or bm_stage == '[TRBS]_Pre_Snap_packages':
        print '[Pre_Snap_packages]\n'

        # get vars
        project = content.get("project")
        bm_repo = content.get("bm_repo")
        bm_arch = content.get("bm_arch")
        bm_pkg_url = content.get("bm_pkg_url")
        bm_pkg_name_lst = content.get("bm_pkg_name_lst")
        bm_pkg_mdate_lst = content.get("bm_pkg_mdate_lst")
        bm_pkg_size_lst = content.get("bm_pkg_size_lst")
        bm_trg_count = content.get("bm_trg_count ")
        bm_pkg_count = content.get("bm_pkg_count")
        BM_PKG_LIMIT = content.get("BM_PKG_LIMIT ")

        # func call
        if bm_stage == 'Pre_Snap_packages':
            print '[Pre_Snap_packages]\n'
            create_snapshot_packages_for_build_snapshot_package(project, bm_repo, bm_arch,
                                                                bm_pkg_url,
                                                                bm_pkg_name_lst,
                                                                bm_pkg_mdate_lst,
                                                                bm_pkg_size_lst,
                                                                bm_trg_count,
                                                                bm_pkg_count,
                                                                BM_PKG_LIMIT)
        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Pre_Snap_packages':
            print '[[TRBS]_Pre_Snap_packages]\n'
            TRBS_create_snapshot_packages_for_build_snapshot_package(project, bm_repo, bm_arch,
                                                                     bm_pkg_url,
                                                                     bm_pkg_name_lst,
                                                                     bm_pkg_mdate_lst,
                                                                     bm_pkg_size_lst,
                                                                     bm_trg_count,
                                                                     bm_pkg_count,
                                                                     BM_PKG_LIMIT)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Pre_Snap_packages'
            bm_spl_data = os.getenv('BUILDMONITOR_SPIN_URL')
            if bm_spl_data in bm_pkg_url:
                remote_data['bm_pkg_url'] = bm_pkg_url.split(bm_spl_data)[1]
            else:
                print 'check the bm_spl_data(%s)!!\n' \
                      % (bm_spl_data)
            bm_remote_jenkins_build_job(remote_data)

    elif bm_stage == 'Pre_Snap_Fail' or bm_stage == '[TRBS]_Pre_Snap_Fail':
        print '[Pre_Snap_Fail]\n'

        # get vars
        project = content.get("project")
        bm_git_tag = content.get("bm_git_tag")

        # func call
        if bm_stage == 'Pre_Snap_Fail':
            print '[Pre_Snap_Fail]\n'
            update_fail_status_for_sr_stage(project, bm_git_tag)

        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Pre_Snap_Fail':
            print '[TRBS]_Pre_Snap_Fail]\n'
            TRBS_update_fail_status_for_sr_stage(project, bm_git_tag)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Pre_Snap_Fail'
            bm_remote_jenkins_build_job(remote_data)

    #=======================================================
    # [PRE]/[POST] Image
    elif bm_stage == 'Image' or bm_stage == '[TRBS]_Image':
        print '[Image]\n'

        # get vars
        image_status = content.get("status")
        fields = content.get("fields")
        bm_start_datetime  = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_snapshot_name = content.get("build_id")
        bm_img_size = content.get("bm_img_size")

        create_image_for_build_image(fields, bm_start_datetime,
                                     bm_end_datetime, bm_snapshot_name, bm_img_size)

        if image_status == 'failed':
            if bm_stage == 'Image':
                print '[Image]\n'
                update_fail_create_image_for_sr_stage(fields, bm_start_datetime, bm_snapshot_name)

            # [17_0110] TRBS]
            if bm_stage == '[TRBS]_Image':
                print '[[TRBS]_Image]\n'
                TRBS_update_fail_create_image_for_sr_stage(fields, bm_start_datetime)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Image'
            (remote_data['fields'])['url'] = os.path.join(fields['repo_path'],
                                                      fields['images_path'])
            # prevent long param error
            (remote_data['fields'])['kickstart'] = 0
            bm_remote_jenkins_build_job(remote_data)

    #=======================================================
    # [PRE]/[POST] Post_Image
    elif bm_stage == 'Post_Image' or bm_stage == '[TRBS]_Post_Image':
        print '[Post_Image]\n'

        # get vars
        bm_start_datetime = content.get("bm_start_datetime")
        project = content.get("project")

        # func call
        if bm_stage == 'Post_Image':
            print '[Post_Image]\n'
            bm_snapshot_name = content.get("bm_snapshot_name")
            end_create_image_for_sr_stage(bm_start_datetime, project, bm_snapshot_name)

        # [17_0110] TRBS
        if bm_stage == '[TRBS]_Post_Image':
            print '[[TRBS]_Post_Image]\n'
            TRBS_end_create_image_for_sr_stage(bm_start_datetime, project)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['bm_stage'] = '[TRBS]_Post_Image'
            bm_remote_jenkins_build_job(remote_data)

    #=======================================================
    # SR Accept or Reject
    elif bm_stage == 'SR_Accept':
        print '[SR_Accept]\n'

        # get vars
        event_fields = content.get("event_fields")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_git_tag = content.get("bm_git_tag")

        # func call
        sr_accept_reject_for_sr_status_detail(event_fields, bm_start_datetime,
                                              bm_end_datetime, bm_git_tag)
    #=======================================================
    # [POST] Build
    #=======================================================
    # [POST] Snap
    elif bm_stage == 'Post_Snap_Start':
        print '[Post_Snap_Start]\n'

        # get vars
        project = content.get("project")
        bm_start_datetime = content.get("bm_start_datetime")
        unresolvable_broken_packages = content.get("unresolvable_broken_packages")

        # func call
        start_create_snapshot_for_sr_stage(project, bm_start_datetime)

        update_unresolvable_broken_packages(project, unresolvable_broken_packages)

    elif bm_stage == 'Post_Snap_snapshot':
        print '[Post_Snap_snapshot]\n'
        project = content.get("project")
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_start_datetime = content.get("bm_start_datetime")
        start_create_snapshot_for_post_build_snapshot(project,
                                                      bm_snapshot_name,
                                                      bm_start_datetime)
    elif bm_stage == 'Post_Snap_packages':
        print '[Post_Snap_packages]\n'

        # get vars
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_repo = content.get("bm_repo")
        bm_arch = content.get("bm_arch")
        bm_pkg_url = content.get("bm_pkg_url")
        bm_pkg_name_lst = content.get("bm_pkg_name_lst")
        bm_pkg_mdate_lst = content.get("bm_pkg_mdate_lst")
        bm_pkg_size_lst = content.get("bm_pkg_size_lst")

        # func call
        create_snapshot_packages_for_post_build_snapshot_package(bm_snapshot_name,
                                                                 bm_repo,
                                                                 bm_arch,
                                                                 bm_pkg_url,
                                                                 bm_pkg_name_lst,
                                                                 bm_pkg_mdate_lst,
                                                                 bm_pkg_size_lst)
    elif bm_stage == 'Post_Snap_End':
        print '[Post_Snap_End]\n'

        # get vars
        bm_start_datetime = content.get("bm_start_datetime")
        bm_end_datetime = content.get("bm_end_datetime")
        bm_snapshot_url = content.get("bm_snapshot_url")
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_duplicated = content.get("bm_duplicated")
        bm_buildfailreason = content.get("bm_buildfailreason")
        bm_base_build_id = content.get("bm_base_build_id")

        # func call
        # for sr_stage & build_snapshot
        end_create_snapshot_create_images_for_sr_stage(bm_snapshot_name,
                                                       bm_start_datetime,
                                                       bm_end_datetime)
        end_create_snapshot_for_post_build_snapshot(bm_end_datetime,
                                                    bm_snapshot_url,
                                                    bm_snapshot_name)
        update_duplicated_package_warning(bm_snapshot_name, list(set(bm_duplicated)))
        update_build_fail_reason_warning(bm_snapshot_name, bm_buildfailreason)
        if bm_base_build_id is not None and bm_base_build_id != '':
            update_base_build_id(bm_snapshot_name, bm_base_build_id)

    elif bm_stage == 'Post_Snap_Fail':
        print '[Post_Snap_Fail]\n'
        bm_snapshot_name = content.get("bm_snapshot_name")
        update_fail_create_snapshot_for_sr_stage(bm_snapshot_name)

    elif bm_stage == 'Update_Manifest':
        print '[Update_Manifest]\n'
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_start_datetime = content.get("bm_start_datetime")
        bm_snapshot_name = content.get("bm_snapshot_name")
        bm_manifestdata = content.get("bm_manifestdata")

        update_snapshot_manifest(bm_snapshot_name, bm_manifestdata, bm_start_datetime)

    elif bm_stage == 'REPA':
        print '[REPA]\n'
        sr_tag = content.get("sr_tag")
        profile = content.get("profile")
        status = content.get("status")
        status_str = content.get("status_reason")

        update_repa(sr_tag, profile, status, status_str)

    elif bm_stage == "UPDATE_BUILD_LOG":
        print "[UPDATE_BUILD_LOG]\n"
        update_build_log(content)

        # TRBS Sender mode
        if trbs_buildmonitor_enabled:
            # remote trigger BUILD-MONITOR job of public
            remote_data = content
            remote_data['base_url'] = content.get('base_url')[len(os.getenv("URL_PUBLIC_REPO_BASE")):]
            remote_data['bm_stage'] = '[TRBS]_UPDATE_BUILD_LOG'
            bm_remote_jenkins_build_job_by_file("BUILD-MONITOR-TRBS-UPDATE-BUILD-LOG", remote_data)

    elif bm_stage == "[TRBS]_UPDATE_BUILD_LOG":
        print "[%s][[TRBS]_UPDATE_BUILD_LOG]\n" % (__file__)
        update_build_log(content)

    elif bm_stage == "RELEASE_SNAPSHOT":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_release_snapshot(content)

    elif bm_stage == "GBSFULLBUILD_SNAPSHOT":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_gbsfullbuild_snapshot(content)

    elif bm_stage == "GBSDBBuild_Start":
        print "[%s][%s]\n" % (__file__, bm_stage)
        start_gbsdbbuild(content)

    elif bm_stage == "GBSDBBuild_Target":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_gbsdbbuild_target(content)

    elif bm_stage == "GBSDBBuild_Snapshot_Start" or bm_stage == "GBSDBBuild_Snapshot_End" or bm_stage == "GBSDBBuild_Snapshot_Fail":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_gbsdbbuild_snapshot(content)

    elif bm_stage == "GBSDBBuild_Image":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_gbsdbbuild_image(content)

    elif bm_stage == "GBSDBBuild_Package":
        print "[%s][%s]\n" % (__file__, bm_stage)
        update_gbs_build_package(content)

    #=======================================================
    # [POST] Image / Post_Image => N/A
    #=======================================================
    else:
        print 'no bm_stage\n'

    bm_disconnect_db()

if __name__ == '__main__':
    try:
        sys.exit(main())
    except LocalError, err:
        print err
        bm_disconnect_db()
        sys.exit(1)

