安装完成,如果环境是Python3,则需要修改datax/bin下面的三个python文件。
win10安装dataX - 图1

GitHub

https://github.com/alibaba/DataX
https://github.com/alibaba/DataX/blob/master/introduction.md
https://github.com/alibaba/DataX/blob/master/userGuid.md

系统要求

  • Linux
  • JDK(1.8以上,推荐1.8)
  • Python(2或3都可以)
  • Apache Maven 3.x (Compile DataX)

    相关安装

    python安装

    windows10安装python详细过程
    python 3.X版本在win10安装成功后,还是直接使用python,不需要python3

    JDK安装

    请参考Jdk 8 安装与配置
    https://www.oracle.com/java/technologies/downloads/archive/
    版本说明
    Linux x86 RPM Package //适用于32bit的centos、rethat(linux)操作系统
    Linux x64 RPM Package //适用于64bit的centos、rethat(linux)操作系统
    Linux x86 Compressed Archive //适用于32bit的Linux操作系统
    Linux x64 Compressed Archive //适用于64bit的Linux操作系统

    DataX安装

    直接下载DataX工具包:DataX下载地址将下载的压缩包解压即可。,
    可参考 userGuid.md

    下载解压

    直接下载DataX工具包:DataX下载地址,将下载的压缩包解压即可。,
    我解压的存放目录在D:\DataX\DataX,
    1665456456182.jpg

    隐藏文件

    需要删除隐藏文件 (重要),以._开头的文件都删除.

    测试安装

    1. cd D:/DataX/datax/bin
    1. python D:/DataX/datax/bin/datax.py D:/DataX/datax/job/job.json
    1665468553391.jpg

    修改python文件

    安装完成,如果环境是Python3,则需要修改datax/bin下面的三个python文件。
    修改的文件 ```python

    !/usr/bin/env python

    -- coding:utf-8 --

import sys import os import signal import subprocess import time import re import socket import json from optparse import OptionParser from optparse import OptionGroup from string import Template import codecs import platform

def isWindows(): return platform.system() == ‘Windows’

DATAXHOME = os.path.dirname(os.path.dirname(os.path.abspath(_file)))

DATAX_VERSION = ‘DATAX-OPENSOURCE-3.0’ if isWindows(): codecs.register(lambda name: name == ‘cp65001’ and codecs.lookup(‘utf-8’) or None) CLASS_PATH = (“%s/lib/“) % (DATAX_HOME) else: CLASS_PATH = (“%s/lib/:.”) % (DATAX_HOME) LOGBACK_FILE = (“%s/conf/logback.xml”) % (DATAX_HOME) DEFAULT_JVM = “-Xms1g -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%s/log” % (DATAX_HOME) DEFAULT_PROPERTY_CONF = “-Dfile.encoding=UTF-8 -Dlogback.statusListenerClass=ch.qos.logback.core.status.NopStatusListener -Djava.security.egd=file:///dev/urandom -Ddatax.home=%s -Dlogback.configurationFile=%s” % ( DATAX_HOME, LOGBACK_FILE) ENGINE_COMMAND = “java -server ${jvm} %s -classpath %s ${params} com.alibaba.datax.core.Engine -mode ${mode} -jobid ${jobid} -job ${job}” % ( DEFAULT_PROPERTY_CONF, CLASS_PATH) REMOTE_DEBUG_CONFIG = “-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=9999”

RET_STATE = { “KILL”: 143, “FAIL”: -1, “OK”: 0, “RUN”: 1, “RETRY”: 2 }

def getLocalIp(): try: return socket.gethostbyname(socket.getfqdn(socket.gethostname())) except: return “Unknown”

def suicide(signum, e): global child_process print >> sys.stderr, “[Error] DataX receive unexpected signal %d, starts to suicide.” % (signum)

  1. if child_process:
  2. child_process.send_signal(signal.SIGQUIT)
  3. time.sleep(1)
  4. child_process.kill()
  5. print >> sys.stderr, "DataX Process was killed ! you did ?"
  6. sys.exit(RET_STATE["KILL"])

def register_signal(): if not isWindows(): global child_process signal.signal(2, suicide) signal.signal(3, suicide) signal.signal(15, suicide)

def getOptionParser(): usage = “usage: %prog [options] job-url-or-path” parser = OptionParser(usage=usage)

  1. prodEnvOptionGroup = OptionGroup(parser, "Product Env Options",
  2. "Normal user use these options to set jvm parameters, job runtime mode etc. "
  3. "Make sure these options can be used in Product Env.")
  4. prodEnvOptionGroup.add_option("-j", "--jvm", metavar="<jvm parameters>", dest="jvmParameters", action="store",
  5. default=DEFAULT_JVM, help="Set jvm parameters if necessary.")
  6. prodEnvOptionGroup.add_option("--jobid", metavar="<job unique id>", dest="jobid", action="store", default="-1",
  7. help="Set job unique id when running by Distribute/Local Mode.")
  8. prodEnvOptionGroup.add_option("-m", "--mode", metavar="<job runtime mode>",
  9. action="store", default="standalone",
  10. help="Set job runtime mode such as: standalone, local, distribute. "
  11. "Default mode is standalone.")
  12. prodEnvOptionGroup.add_option("-p", "--params", metavar="<parameter used in job config>",
  13. action="store", dest="params",
  14. help='Set job parameter, eg: the source tableName you want to set it by command, '
  15. 'then you can use like this: -p"-DtableName=your-table-name", '
  16. 'if you have mutiple parameters: -p"-DtableName=your-table-name -DcolumnName=your-column-name".'
  17. 'Note: you should config in you job tableName with ${tableName}.')
  18. prodEnvOptionGroup.add_option("-r", "--reader", metavar="<parameter used in view job config[reader] template>",
  19. action="store", dest="reader",type="string",
  20. help='View job config[reader] template, eg: mysqlreader,streamreader')
  21. prodEnvOptionGroup.add_option("-w", "--writer", metavar="<parameter used in view job config[writer] template>",
  22. action="store", dest="writer",type="string",
  23. help='View job config[writer] template, eg: mysqlwriter,streamwriter')
  24. parser.add_option_group(prodEnvOptionGroup)
  25. devEnvOptionGroup = OptionGroup(parser, "Develop/Debug Options",
  26. "Developer use these options to trace more details of DataX.")
  27. devEnvOptionGroup.add_option("-d", "--debug", dest="remoteDebug", action="store_true",
  28. help="Set to remote debug mode.")
  29. devEnvOptionGroup.add_option("--loglevel", metavar="<log level>", dest="loglevel", action="store",
  30. default="info", help="Set log level such as: debug, info, all etc.")
  31. parser.add_option_group(devEnvOptionGroup)
  32. return parser

def generateJobConfigTemplate(reader, writer): readerRef = “Please refer to the %s document:\n https://github.com/alibaba/DataX/blob/master/%s/doc/%s.md \n” % (reader,reader,reader) writerRef = “Please refer to the %s document:\n https://github.com/alibaba/DataX/blob/master/%s/doc/%s.md \n “ % (writer,writer,writer) print (readerRef) print (writerRef) jobGuid = ‘Please save the following configuration as a json file and use\n python {DATAX_HOME}/bin/datax.py {JSON_FILE_NAME}.json \nto run the job.\n’ print (jobGuid) jobTemplate={ “job”: { “setting”: { “speed”: { “channel”: “” } }, “content”: [ { “reader”: {}, “writer”: {} } ] } } readerTemplatePath = “%s/plugin/reader/%s/plugin_job_template.json” % (DATAX_HOME,reader) writerTemplatePath = “%s/plugin/writer/%s/plugin_job_template.json” % (DATAX_HOME,writer) try: readerPar = readPluginTemplate(readerTemplatePath); except Exception as e: print (“Read reader[%s] template error: can\’t find file %s” % (reader,readerTemplatePath)) try: writerPar = readPluginTemplate(writerTemplatePath); except Exception as e: print (“Read writer[%s] template error: : can\’t find file %s” % (writer,writerTemplatePath)) jobTemplate[‘job’][‘content’][0][‘reader’] = readerPar; jobTemplate[‘job’][‘content’][0][‘writer’] = writerPar; print (json.dumps(jobTemplate, indent=4, sort_keys=True))

def readPluginTemplate(plugin): with open(plugin, ‘r’) as f: return json.load(f)

def isUrl(path): if not path: return False

  1. assert (isinstance(path, str))
  2. m = re.match(r"^http[s]?://\S+\w*", path.lower())
  3. if m:
  4. return True
  5. else:
  6. return False

def buildStartCommand(options, args): commandMap = {} tempJVMCommand = DEFAULT_JVM if options.jvmParameters: tempJVMCommand = tempJVMCommand + “ “ + options.jvmParameters

  1. if options.remoteDebug:
  2. tempJVMCommand = tempJVMCommand + " " + REMOTE_DEBUG_CONFIG
  3. print ('local ip: ', getLocalIp())
  4. if options.loglevel:
  5. tempJVMCommand = tempJVMCommand + " " + ("-Dloglevel=%s" % (options.loglevel))
  6. if options.mode:
  7. commandMap["mode"] = options.mode
  8. # jobResource 鍙兘鏄?URL锛屼篃鍙兘鏄湰鍦版枃浠惰矾寰勶紙鐩稿,缁濆锛? jobResource = args[0]
  9. if not isUrl(jobResource):
  10. jobResource = os.path.abspath(jobResource)
  11. if jobResource.lower().startswith("file://"):
  12. jobResource = jobResource[len("file://"):]
  13. jobParams = ("-Dlog.file.name=%s") % (jobResource[-20:].replace('/', '_').replace('.', '_'))
  14. if options.params:
  15. jobParams = jobParams + " " + options.params
  16. if options.jobid:
  17. commandMap["jobid"] = options.jobid
  18. commandMap["jvm"] = tempJVMCommand
  19. commandMap["params"] = jobParams
  20. commandMap["job"] = jobResource
  21. return Template(ENGINE_COMMAND).substitute(**commandMap)

def printCopyright(): print (‘’’ DataX (%s), From Alibaba ! Copyright (C) 2010-2017, Alibaba Group. All Rights Reserved.

‘’’ % DATAX_VERSION) sys.stdout.flush()

if name == “main“: printCopyright() parser = getOptionParser() options, args = parser.parse_args(sys.argv[1:]) if options.reader is not None and options.writer is not None: generateJobConfigTemplate(options.reader,options.writer) sys.exit(RET_STATE[‘OK’]) if len(args) != 1: parser.print_help() sys.exit(RET_STATE[‘FAIL’])

  1. startCommand = buildStartCommand(options, args)
  2. # print startCommand
  3. child_process = subprocess.Popen(startCommand, shell=True)
  4. register_signal()
  5. (stdout, stderr) = child_process.communicate()
  6. sys.exit(child_process.returncode)
  1. ```python
  2. #! /usr/bin/env python
  3. # vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker nu:
  4. import re
  5. import sys
  6. import time
  7. REG_SQL_WAKE = re.compile(r'Begin\s+to\s+read\s+record\s+by\s+Sql', re.IGNORECASE)
  8. REG_SQL_DONE = re.compile(r'Finished\s+read\s+record\s+by\s+Sql', re.IGNORECASE)
  9. REG_SQL_PATH = re.compile(r'from\s+(\w+)(\s+where|\s*$)', re.IGNORECASE)
  10. REG_SQL_JDBC = re.compile(r'jdbcUrl:\s*\[(.+?)\]', re.IGNORECASE)
  11. REG_SQL_UUID = re.compile(r'(\d+\-)+reader')
  12. REG_COMMIT_UUID = re.compile(r'(\d+\-)+writer')
  13. REG_COMMIT_WAKE = re.compile(r'begin\s+to\s+commit\s+blocks', re.IGNORECASE)
  14. REG_COMMIT_DONE = re.compile(r'commit\s+blocks\s+ok', re.IGNORECASE)
  15. # {{{ function parse_timestamp() #
  16. def parse_timestamp(line):
  17. try:
  18. ts = int(time.mktime(time.strptime(line[0:19], '%Y-%m-%d %H:%M:%S')))
  19. except:
  20. ts = 0
  21. return ts
  22. # }}} #
  23. # {{{ function parse_query_host() #
  24. def parse_query_host(line):
  25. ori = REG_SQL_JDBC.search(line)
  26. if (not ori):
  27. return ''
  28. ori = ori.group(1).split('?')[0]
  29. off = ori.find('@')
  30. if (off > -1):
  31. ori = ori[off+1:len(ori)]
  32. else:
  33. off = ori.find('//')
  34. if (off > -1):
  35. ori = ori[off+2:len(ori)]
  36. return ori.lower()
  37. # }}} #
  38. # {{{ function parse_query_table() #
  39. def parse_query_table(line):
  40. ori = REG_SQL_PATH.search(line)
  41. return (ori and ori.group(1).lower()) or ''
  42. # }}} #
  43. # {{{ function parse_reader_task() #
  44. def parse_task(fname):
  45. global LAST_SQL_UUID
  46. global LAST_COMMIT_UUID
  47. global DATAX_JOBDICT
  48. global DATAX_JOBDICT_COMMIT
  49. global UNIXTIME
  50. LAST_SQL_UUID = ''
  51. DATAX_JOBDICT = {}
  52. LAST_COMMIT_UUID = ''
  53. DATAX_JOBDICT_COMMIT = {}
  54. UNIXTIME = int(time.time())
  55. with open(fname, 'r') as f:
  56. for line in f.readlines():
  57. line = line.strip()
  58. if (LAST_SQL_UUID and (LAST_SQL_UUID in DATAX_JOBDICT)):
  59. DATAX_JOBDICT[LAST_SQL_UUID]['host'] = parse_query_host(line)
  60. LAST_SQL_UUID = ''
  61. if line.find('CommonRdbmsReader$Task') > 0:
  62. parse_read_task(line)
  63. elif line.find('commit blocks') > 0:
  64. parse_write_task(line)
  65. else:
  66. continue
  67. # }}} #
  68. # {{{ function parse_read_task() #
  69. def parse_read_task(line):
  70. ser = REG_SQL_UUID.search(line)
  71. if not ser:
  72. return
  73. LAST_SQL_UUID = ser.group()
  74. if REG_SQL_WAKE.search(line):
  75. DATAX_JOBDICT[LAST_SQL_UUID] = {
  76. 'stat' : 'R',
  77. 'wake' : parse_timestamp(line),
  78. 'done' : UNIXTIME,
  79. 'host' : parse_query_host(line),
  80. 'path' : parse_query_table(line)
  81. }
  82. elif ((LAST_SQL_UUID in DATAX_JOBDICT) and REG_SQL_DONE.search(line)):
  83. DATAX_JOBDICT[LAST_SQL_UUID]['stat'] = 'D'
  84. DATAX_JOBDICT[LAST_SQL_UUID]['done'] = parse_timestamp(line)
  85. # }}} #
  86. # {{{ function parse_write_task() #
  87. def parse_write_task(line):
  88. ser = REG_COMMIT_UUID.search(line)
  89. if not ser:
  90. return
  91. LAST_COMMIT_UUID = ser.group()
  92. if REG_COMMIT_WAKE.search(line):
  93. DATAX_JOBDICT_COMMIT[LAST_COMMIT_UUID] = {
  94. 'stat' : 'R',
  95. 'wake' : parse_timestamp(line),
  96. 'done' : UNIXTIME,
  97. }
  98. elif ((LAST_COMMIT_UUID in DATAX_JOBDICT_COMMIT) and REG_COMMIT_DONE.search(line)):
  99. DATAX_JOBDICT_COMMIT[LAST_COMMIT_UUID]['stat'] = 'D'
  100. DATAX_JOBDICT_COMMIT[LAST_COMMIT_UUID]['done'] = parse_timestamp(line)
  101. # }}} #
  102. # {{{ function result_analyse() #
  103. def result_analyse():
  104. def compare(a, b):
  105. return b['cost'] - a['cost']
  106. tasklist = []
  107. hostsmap = {}
  108. statvars = {'sum' : 0, 'cnt' : 0, 'svr' : 0, 'max' : 0, 'min' : int(time.time())}
  109. tasklist_commit = []
  110. statvars_commit = {'sum' : 0, 'cnt' : 0}
  111. for idx in DATAX_JOBDICT:
  112. item = DATAX_JOBDICT[idx]
  113. item['uuid'] = idx;
  114. item['cost'] = item['done'] - item['wake']
  115. tasklist.append(item);
  116. if (not (item['host'] in hostsmap)):
  117. hostsmap[item['host']] = 1
  118. statvars['svr'] += 1
  119. if (item['cost'] > -1 and item['cost'] < 864000):
  120. statvars['sum'] += item['cost']
  121. statvars['cnt'] += 1
  122. statvars['max'] = max(statvars['max'], item['done'])
  123. statvars['min'] = min(statvars['min'], item['wake'])
  124. for idx in DATAX_JOBDICT_COMMIT:
  125. itemc = DATAX_JOBDICT_COMMIT[idx]
  126. itemc['uuid'] = idx
  127. itemc['cost'] = itemc['done'] - itemc['wake']
  128. tasklist_commit.append(itemc)
  129. if (itemc['cost'] > -1 and itemc['cost'] < 864000):
  130. statvars_commit['sum'] += itemc['cost']
  131. statvars_commit['cnt'] += 1
  132. ttl = (statvars['max'] - statvars['min']) or 1
  133. idx = float(statvars['cnt']) / (statvars['sum'] or ttl)
  134. tasklist.sort(compare)
  135. for item in tasklist:
  136. print '%s\t%s.%s\t%s\t%s\t% 4d\t% 2.1f%%\t% .2f' %(item['stat'], item['host'], item['path'],
  137. time.strftime('%H:%M:%S', time.localtime(item['wake'])),
  138. (('D' == item['stat']) and time.strftime('%H:%M:%S', time.localtime(item['done']))) or '--',
  139. item['cost'], 100 * item['cost'] / ttl, idx * item['cost'])
  140. if (not len(tasklist) or not statvars['cnt']):
  141. return
  142. print '\n--- DataX Profiling Statistics ---'
  143. print '%d task(s) on %d server(s), Total elapsed %d second(s), %.2f second(s) per task in average' %(statvars['cnt'],
  144. statvars['svr'], statvars['sum'], float(statvars['sum']) / statvars['cnt'])
  145. print 'Actually cost %d second(s) (%s - %s), task concurrency: %.2f, tilt index: %.2f' %(ttl,
  146. time.strftime('%H:%M:%S', time.localtime(statvars['min'])),
  147. time.strftime('%H:%M:%S', time.localtime(statvars['max'])),
  148. float(statvars['sum']) / ttl, idx * tasklist[0]['cost'])
  149. idx_commit = float(statvars_commit['cnt']) / (statvars_commit['sum'] or ttl)
  150. tasklist_commit.sort(compare)
  151. print '%d task(s) done odps comit, Total elapsed %d second(s), %.2f second(s) per task in average, tilt index: %.2f' % (
  152. statvars_commit['cnt'],
  153. statvars_commit['sum'], float(statvars_commit['sum']) / statvars_commit['cnt'],
  154. idx_commit * tasklist_commit[0]['cost'])
  155. # }}} #
  156. if (len(sys.argv) < 2):
  157. print "Usage: %s filename" %(sys.argv[0])
  158. quit(1)
  159. else:
  160. parse_task(sys.argv[1])
  161. result_analyse()
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. Life's short, Python more.
  5. """
  6. import re
  7. import os
  8. import sys
  9. import json
  10. import uuid
  11. import signal
  12. import time
  13. import subprocess
  14. from optparse import OptionParser
  15. reload(sys)
  16. sys.setdefaultencoding('utf8')
  17. ##begin cli & help logic
  18. def getOptionParser():
  19. usage = getUsage()
  20. parser = OptionParser(usage = usage)
  21. #rdbms reader and writer
  22. parser.add_option('-r', '--reader', action='store', dest='reader', help='trace datasource read performance with specified !json! string')
  23. parser.add_option('-w', '--writer', action='store', dest='writer', help='trace datasource write performance with specified !json! string')
  24. parser.add_option('-c', '--channel', action='store', dest='channel', default='1', help='the number of concurrent sync thread, the default is 1')
  25. parser.add_option('-f', '--file', action='store', help='existing datax configuration file, include reader and writer params')
  26. parser.add_option('-t', '--type', action='store', default='reader', help='trace which side\'s performance, cooperate with -f --file params, need to be reader or writer')
  27. parser.add_option('-d', '--delete', action='store', default='true', help='delete temporary files, the default value is true')
  28. #parser.add_option('-h', '--help', action='store', default='true', help='print usage information')
  29. return parser
  30. def getUsage():
  31. return '''
  32. The following params are available for -r --reader:
  33. [these params is for rdbms reader, used to trace rdbms read performance, it's like datax's key]
  34. *datasourceType: datasource type, may be mysql|drds|oracle|ads|sqlserver|postgresql|db2 etc...
  35. *jdbcUrl: datasource jdbc connection string, mysql as a example: jdbc:mysql://ip:port/database
  36. *username: username for datasource
  37. *password: password for datasource
  38. *table: table name for read data
  39. column: column to be read, the default value is ['*']
  40. splitPk: the splitPk column of rdbms table
  41. where: limit the scope of the performance data set
  42. fetchSize: how many rows to be fetched at each communicate
  43. [these params is for stream reader, used to trace rdbms write performance]
  44. reader-sliceRecordCount: how man test data to mock(each channel), the default value is 10000
  45. reader-column : stream reader while generate test data(type supports: string|long|date|double|bool|bytes; support constant value and random function)锛宒emo: [{"type":"string","value":"abc"},{"type":"string","random":"10,20"}]
  46. The following params are available for -w --writer:
  47. [these params is for rdbms writer, used to trace rdbms write performance, it's like datax's key]
  48. datasourceType: datasource type, may be mysql|drds|oracle|ads|sqlserver|postgresql|db2|ads etc...
  49. *jdbcUrl: datasource jdbc connection string, mysql as a example: jdbc:mysql://ip:port/database
  50. *username: username for datasource
  51. *password: password for datasource
  52. *table: table name for write data
  53. column: column to be writed, the default value is ['*']
  54. batchSize: how many rows to be storeed at each communicate, the default value is 512
  55. preSql: prepare sql to be executed before write data, the default value is ''
  56. postSql: post sql to be executed end of write data, the default value is ''
  57. url: required for ads, pattern is ip:port
  58. schme: required for ads, ads database name
  59. [these params is for stream writer, used to trace rdbms read performance]
  60. writer-print: true means print data read from source datasource, the default value is false
  61. The following params are available global control:
  62. -c --channel: the number of concurrent tasks, the default value is 1
  63. -f --file: existing completely dataX configuration file path
  64. -t --type: test read or write performance for a datasource, couble be reader or writer, in collaboration with -f --file
  65. -h --help: print help message
  66. some demo:
  67. perftrace.py --channel=10 --reader='{"jdbcUrl":"jdbc:mysql://127.0.0.1:3306/database", "username":"", "password":"", "table": "", "where":"", "splitPk":"", "writer-print":"false"}'
  68. perftrace.py --channel=10 --writer='{"jdbcUrl":"jdbc:mysql://127.0.0.1:3306/database", "username":"", "password":"", "table": "", "reader-sliceRecordCount": "10000", "reader-column": [{"type":"string","value":"abc"},{"type":"string","random":"10,20"}]}'
  69. perftrace.py --file=/tmp/datax.job.json --type=reader --reader='{"writer-print": "false"}'
  70. perftrace.py --file=/tmp/datax.job.json --type=writer --writer='{"reader-sliceRecordCount": "10000", "reader-column": [{"type":"string","value":"abc"},{"type":"string","random":"10,20"}]}'
  71. some example jdbc url pattern, may help:
  72. jdbc:oracle:thin:@ip:port:database
  73. jdbc:mysql://ip:port/database
  74. jdbc:sqlserver://ip:port;DatabaseName=database
  75. jdbc:postgresql://ip:port/database
  76. warn: ads url pattern is ip:port
  77. warn: test write performance will write data into your table, you can use a temporary table just for test.
  78. '''
  79. def printCopyright():
  80. DATAX_VERSION = 'UNKNOWN_DATAX_VERSION'
  81. print '''
  82. DataX Util Tools (%s), From Alibaba !
  83. Copyright (C) 2010-2016, Alibaba Group. All Rights Reserved.''' % DATAX_VERSION
  84. sys.stdout.flush()
  85. def yesNoChoice():
  86. yes = set(['yes','y', 'ye', ''])
  87. no = set(['no','n'])
  88. choice = raw_input().lower()
  89. if choice in yes:
  90. return True
  91. elif choice in no:
  92. return False
  93. else:
  94. sys.stdout.write("Please respond with 'yes' or 'no'")
  95. ##end cli & help logic
  96. ##begin process logic
  97. def suicide(signum, e):
  98. global childProcess
  99. print >> sys.stderr, "[Error] Receive unexpected signal %d, starts to suicide." % (signum)
  100. if childProcess:
  101. childProcess.send_signal(signal.SIGQUIT)
  102. time.sleep(1)
  103. childProcess.kill()
  104. print >> sys.stderr, "DataX Process was killed ! you did ?"
  105. sys.exit(-1)
  106. def registerSignal():
  107. global childProcess
  108. signal.signal(2, suicide)
  109. signal.signal(3, suicide)
  110. signal.signal(15, suicide)
  111. def fork(command, isShell=False):
  112. global childProcess
  113. childProcess = subprocess.Popen(command, shell = isShell)
  114. registerSignal()
  115. (stdout, stderr) = childProcess.communicate()
  116. #闃诲鐩村埌瀛愯繘绋嬬粨鏉? childProcess.wait()
  117. return childProcess.returncode
  118. ##end process logic
  119. ##begin datax json generate logic
  120. #warn: if not '': -> true; if not None: -> true
  121. def notNone(obj, context):
  122. if not obj:
  123. raise Exception("Configuration property [%s] could not be blank!" % (context))
  124. def attributeNotNone(obj, attributes):
  125. for key in attributes:
  126. notNone(obj.get(key), key)
  127. def isBlank(value):
  128. if value is None or len(value.strip()) == 0:
  129. return True
  130. return False
  131. def parsePluginName(jdbcUrl, pluginType):
  132. import re
  133. #warn: drds
  134. name = 'pluginName'
  135. mysqlRegex = re.compile('jdbc:(mysql)://.*')
  136. if (mysqlRegex.match(jdbcUrl)):
  137. name = 'mysql'
  138. postgresqlRegex = re.compile('jdbc:(postgresql)://.*')
  139. if (postgresqlRegex.match(jdbcUrl)):
  140. name = 'postgresql'
  141. oracleRegex = re.compile('jdbc:(oracle):.*')
  142. if (oracleRegex.match(jdbcUrl)):
  143. name = 'oracle'
  144. sqlserverRegex = re.compile('jdbc:(sqlserver)://.*')
  145. if (sqlserverRegex.match(jdbcUrl)):
  146. name = 'sqlserver'
  147. db2Regex = re.compile('jdbc:(db2)://.*')
  148. if (db2Regex.match(jdbcUrl)):
  149. name = 'db2'
  150. return "%s%s" % (name, pluginType)
  151. def renderDataXJson(paramsDict, readerOrWriter = 'reader', channel = 1):
  152. dataxTemplate = {
  153. "job": {
  154. "setting": {
  155. "speed": {
  156. "channel": 1
  157. }
  158. },
  159. "content": [
  160. {
  161. "reader": {
  162. "name": "",
  163. "parameter": {
  164. "username": "",
  165. "password": "",
  166. "sliceRecordCount": "10000",
  167. "column": [
  168. "*"
  169. ],
  170. "connection": [
  171. {
  172. "table": [],
  173. "jdbcUrl": []
  174. }
  175. ]
  176. }
  177. },
  178. "writer": {
  179. "name": "",
  180. "parameter": {
  181. "print": "false",
  182. "connection": [
  183. {
  184. "table": [],
  185. "jdbcUrl": ''
  186. }
  187. ]
  188. }
  189. }
  190. }
  191. ]
  192. }
  193. }
  194. dataxTemplate['job']['setting']['speed']['channel'] = channel
  195. dataxTemplateContent = dataxTemplate['job']['content'][0]
  196. pluginName = ''
  197. if paramsDict.get('datasourceType'):
  198. pluginName = '%s%s' % (paramsDict['datasourceType'], readerOrWriter)
  199. elif paramsDict.get('jdbcUrl'):
  200. pluginName = parsePluginName(paramsDict['jdbcUrl'], readerOrWriter)
  201. elif paramsDict.get('url'):
  202. pluginName = 'adswriter'
  203. theOtherSide = 'writer' if readerOrWriter == 'reader' else 'reader'
  204. dataxPluginParamsContent = dataxTemplateContent.get(readerOrWriter).get('parameter')
  205. dataxPluginParamsContent.update(paramsDict)
  206. dataxPluginParamsContentOtherSide = dataxTemplateContent.get(theOtherSide).get('parameter')
  207. if readerOrWriter == 'reader':
  208. dataxTemplateContent.get('reader')['name'] = pluginName
  209. dataxTemplateContent.get('writer')['name'] = 'streamwriter'
  210. if paramsDict.get('writer-print'):
  211. dataxPluginParamsContentOtherSide['print'] = paramsDict['writer-print']
  212. del dataxPluginParamsContent['writer-print']
  213. del dataxPluginParamsContentOtherSide['connection']
  214. if readerOrWriter == 'writer':
  215. dataxTemplateContent.get('reader')['name'] = 'streamreader'
  216. dataxTemplateContent.get('writer')['name'] = pluginName
  217. if paramsDict.get('reader-column'):
  218. dataxPluginParamsContentOtherSide['column'] = paramsDict['reader-column']
  219. del dataxPluginParamsContent['reader-column']
  220. if paramsDict.get('reader-sliceRecordCount'):
  221. dataxPluginParamsContentOtherSide['sliceRecordCount'] = paramsDict['reader-sliceRecordCount']
  222. del dataxPluginParamsContent['reader-sliceRecordCount']
  223. del dataxPluginParamsContentOtherSide['connection']
  224. if paramsDict.get('jdbcUrl'):
  225. if readerOrWriter == 'reader':
  226. dataxPluginParamsContent['connection'][0]['jdbcUrl'].append(paramsDict['jdbcUrl'])
  227. else:
  228. dataxPluginParamsContent['connection'][0]['jdbcUrl'] = paramsDict['jdbcUrl']
  229. if paramsDict.get('table'):
  230. dataxPluginParamsContent['connection'][0]['table'].append(paramsDict['table'])
  231. traceJobJson = json.dumps(dataxTemplate, indent = 4)
  232. return traceJobJson
  233. def isUrl(path):
  234. if not path:
  235. return False
  236. if not isinstance(path, str):
  237. raise Exception('Configuration file path required for the string, you configure is:%s' % path)
  238. m = re.match(r"^http[s]?://\S+\w*", path.lower())
  239. if m:
  240. return True
  241. else:
  242. return False
  243. def readJobJsonFromLocal(jobConfigPath):
  244. jobConfigContent = None
  245. jobConfigPath = os.path.abspath(jobConfigPath)
  246. file = open(jobConfigPath)
  247. try:
  248. jobConfigContent = file.read()
  249. finally:
  250. file.close()
  251. if not jobConfigContent:
  252. raise Exception("Your job configuration file read the result is empty, please check the configuration is legal, path: [%s]\nconfiguration:\n%s" % (jobConfigPath, str(jobConfigContent)))
  253. return jobConfigContent
  254. def readJobJsonFromRemote(jobConfigPath):
  255. import urllib
  256. conn = urllib.urlopen(jobConfigPath)
  257. jobJson = conn.read()
  258. return jobJson
  259. def parseJson(strConfig, context):
  260. try:
  261. return json.loads(strConfig)
  262. except Exception, e:
  263. import traceback
  264. traceback.print_exc()
  265. sys.stdout.flush()
  266. print >> sys.stderr, '%s %s need in line with json syntax' % (context, strConfig)
  267. sys.exit(-1)
  268. def convert(options, args):
  269. traceJobJson = ''
  270. if options.file:
  271. if isUrl(options.file):
  272. traceJobJson = readJobJsonFromRemote(options.file)
  273. else:
  274. traceJobJson = readJobJsonFromLocal(options.file)
  275. traceJobDict = parseJson(traceJobJson, '%s content' % options.file)
  276. attributeNotNone(traceJobDict, ['job'])
  277. attributeNotNone(traceJobDict['job'], ['content'])
  278. attributeNotNone(traceJobDict['job']['content'][0], ['reader', 'writer'])
  279. attributeNotNone(traceJobDict['job']['content'][0]['reader'], ['name', 'parameter'])
  280. attributeNotNone(traceJobDict['job']['content'][0]['writer'], ['name', 'parameter'])
  281. if options.type == 'reader':
  282. traceJobDict['job']['content'][0]['writer']['name'] = 'streamwriter'
  283. if options.reader:
  284. traceReaderDict = parseJson(options.reader, 'reader config')
  285. if traceReaderDict.get('writer-print') is not None:
  286. traceJobDict['job']['content'][0]['writer']['parameter']['print'] = traceReaderDict.get('writer-print')
  287. else:
  288. traceJobDict['job']['content'][0]['writer']['parameter']['print'] = 'false'
  289. else:
  290. traceJobDict['job']['content'][0]['writer']['parameter']['print'] = 'false'
  291. elif options.type == 'writer':
  292. traceJobDict['job']['content'][0]['reader']['name'] = 'streamreader'
  293. if options.writer:
  294. traceWriterDict = parseJson(options.writer, 'writer config')
  295. if traceWriterDict.get('reader-column'):
  296. traceJobDict['job']['content'][0]['reader']['parameter']['column'] = traceWriterDict['reader-column']
  297. if traceWriterDict.get('reader-sliceRecordCount'):
  298. traceJobDict['job']['content'][0]['reader']['parameter']['sliceRecordCount'] = traceWriterDict['reader-sliceRecordCount']
  299. else:
  300. columnSize = len(traceJobDict['job']['content'][0]['writer']['parameter']['column'])
  301. streamReaderColumn = []
  302. for i in range(columnSize):
  303. streamReaderColumn.append({"type": "long", "random": "2,10"})
  304. traceJobDict['job']['content'][0]['reader']['parameter']['column'] = streamReaderColumn
  305. traceJobDict['job']['content'][0]['reader']['parameter']['sliceRecordCount'] = 10000
  306. else:
  307. pass#do nothing
  308. return json.dumps(traceJobDict, indent = 4)
  309. elif options.reader:
  310. traceReaderDict = parseJson(options.reader, 'reader config')
  311. return renderDataXJson(traceReaderDict, 'reader', options.channel)
  312. elif options.writer:
  313. traceWriterDict = parseJson(options.writer, 'writer config')
  314. return renderDataXJson(traceWriterDict, 'writer', options.channel)
  315. else:
  316. print getUsage()
  317. sys.exit(-1)
  318. #dataxParams = {}
  319. #for opt, value in options.__dict__.items():
  320. # dataxParams[opt] = value
  321. ##end datax json generate logic
  322. if __name__ == "__main__":
  323. printCopyright()
  324. parser = getOptionParser()
  325. options, args = parser.parse_args(sys.argv[1:])
  326. #print options, args
  327. dataxTraceJobJson = convert(options, args)
  328. #鐢盡AC鍦板潃銆佸綋鍓嶆椂闂存埑銆侀殢鏈烘暟鐢熸垚,鍙互淇濊瘉鍏ㄧ悆鑼冨洿鍐呯殑鍞竴鎬? dataxJobPath = os.path.join(os.getcwd(), "perftrace-" + str(uuid.uuid1()))
  329. jobConfigOk = True
  330. if os.path.exists(dataxJobPath):
  331. print "file already exists, truncate and rewrite it? %s" % dataxJobPath
  332. if yesNoChoice():
  333. jobConfigOk = True
  334. else:
  335. print "exit failed, because of file conflict"
  336. sys.exit(-1)
  337. fileWriter = open(dataxJobPath, 'w')
  338. fileWriter.write(dataxTraceJobJson)
  339. fileWriter.close()
  340. print "trace environments:"
  341. print "dataxJobPath: %s" % dataxJobPath
  342. dataxHomePath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  343. print "dataxHomePath: %s" % dataxHomePath
  344. dataxCommand = "%s %s" % (os.path.join(dataxHomePath, "bin", "datax.py"), dataxJobPath)
  345. print "dataxCommand: %s" % dataxCommand
  346. returncode = fork(dataxCommand, True)
  347. if options.delete == 'true':
  348. os.remove(dataxJobPath)
  349. sys.exit(returncode)

cmd中文显示乱码处理

cmd中输入CHCP 65001,就是将编码方式调整为UTF-8

  1. CHCP 65001

DataX 基本使用

查看模板

  1. python D:/DataX/datax/bin/datax.py -r streamreader -w streamwriter

输出

  1. {
  2. "job": {
  3. "content": [
  4. {
  5. "reader": {
  6. "name": "streamreader",
  7. "parameter": {
  8. "column": [],
  9. "sliceRecordCount": ""
  10. }
  11. },
  12. "writer": {
  13. "name": "streamwriter",
  14. "parameter": {
  15. "encoding": "",
  16. "print": true
  17. }
  18. }
  19. }
  20. ],
  21. "setting": {
  22. "speed": {
  23. "channel": ""
  24. }
  25. }
  26. }
  27. }

run test job

根据模板编写 json 文件

  1. cd D:\DataX\datax\job

在该目录下,新建文件test.json

  1. {
  2. "job": {
  3. "content": [
  4. {
  5. "reader": {
  6. "name": "streamreader",
  7. "parameter": {
  8. "column": [
  9. {
  10. "type": "string",
  11. "value": "Hello."
  12. },
  13. {
  14. "type": "string",
  15. "value": "河北彭于晏"
  16. },
  17. ],
  18. "sliceRecordCount": "3"
  19. }
  20. },
  21. "writer": {
  22. "name": "streamwriter",
  23. "parameter": {
  24. "encoding": "utf-8",
  25. "print": true
  26. }
  27. }
  28. }
  29. ],
  30. "setting": {
  31. "speed": {
  32. "channel": "2"
  33. }
  34. }
  35. }
  36. }

,验证test.json

  1. python D:/DataX/datax/bin/datax.py D:/DataX/datax/job/test.json

输出
1665467771594.png