Skip to content
This repository has been archived by the owner on Sep 19, 2018. It is now read-only.

Script to Migrate Db from 1.0.1 to use CronString Format

Sam Garrett edited this page Jul 14, 2016 · 1 revision
#!/bin/python

import optparse
import sys

import pymysql.cursors

def get_conn(host, user, passwd, db):
  return pymysql.connect(host=host,
                         user=user,
                         password=passwd,
                         db=db)

def get_cron_string(interval, startM, startH, startD):
  if interval == 'Hourly':
    return "%d * * * *" % startM
  elif interval == 'Daily':
    return "%d %d * * *" % (startM, startH)
  elif interval == 'Weekly':
    return "%d %d * * %d" % (startM, startH, startD-1)
  elif interval == 'Monthly':
    return "%d %d 1 * *" % (startM, startH)

def get_jobs(conn):
  cur = conn.cursor()
  params = tuple()
  cur.execute('''SELECT id, lastModified, `interval`, startMinute, startHour, startDay FROM jobs ''', params)
  to_ret = list()
  for entry in cur: # 
    to_ret.append(entry)
  cur.close()
  return to_ret

def update_jobs(conn, jobs, debug=True):
  rc = 0
  job_len = len(jobs)
  print("Should update %d jobs..." % job_len)
  for (id, last_mod, interval, startM, startH, startD) in jobs:
    cron_string = get_cron_string(interval, startM, startH, startD)
    query = "UPDATE jobs SET cronString = %s WHERE id = %s AND lastModified = %s"
    params = (cron_string, id, last_mod.strftime('%Y-%m-%d %H:%M:%S'))
    print('params:', params)
    if debug:
      print("would run:")
      print(query % params)
    else:
      cur = conn.cursor()
      cur.execute(query, params)
      rc += cur.rowcount
      cur.close()

  if job_len != rc:
    print("ERROR: total changed %d does not match expected %d" % (rc, job_len))
  elif not debug:
    conn.commit()

  return rc

def main():
  parser = optparse.OptionParser()
  parser.add_option("-e", type='string', dest='env')
  (opts, args) = parser.parse_args()

  if opts.env == 'staging':
    conn = get_conn('staging.example.com', 'user', 'pass', 'chronos')
  elif opts.env == 'production':
    conn = get_conn('production.example.com', 'user', 'pass', 'chronos')
  else:
    print("ERROR expected env option 'staging' or 'production'")
    sys.exit(1)

  jobs = get_jobs(conn)
  updated = update_jobs(conn, jobs, debug=False)

if __name__ == "__main__": 
  main()
Clone this wiki locally