atlas_config.py 20.9 KB
Newer Older
Jon Maron committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/usr/bin/env python

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import getpass
import os
20
import re
Jon Maron committed
21 22 23 24 25
import platform
import subprocess
import sys
import time
import errno
26
import socket
27
from re import split
28
from time import sleep
Jon Maron committed
29

30
BIN = "bin"
Jon Maron committed
31 32
LIB = "lib"
CONF = "conf"
33 34
LOG = "logs"
WEBAPP = "server" + os.sep + "webapp"
35
CONFIG_SETS_CONF = "server" + os.sep + "solr" + os.sep + "configsets" + os.sep + "_default" + os.sep + "conf"
36
DATA = "data"
37 38 39 40
ATLAS_CONF = "ATLAS_CONF"
ATLAS_LOG = "ATLAS_LOG_DIR"
ATLAS_PID = "ATLAS_PID_DIR"
ATLAS_WEBAPP = "ATLAS_EXPANDED_WEBAPP_DIR"
41
ATLAS_SERVER_OPTS = "ATLAS_SERVER_OPTS"
42
ATLAS_OPTS = "ATLAS_OPTS"
43
ATLAS_SERVER_HEAP = "ATLAS_SERVER_HEAP"
44 45
ATLAS_DATA = "ATLAS_DATA_DIR"
ATLAS_HOME = "ATLAS_HOME_DIR"
46
HBASE_CONF_DIR = "HBASE_CONF_DIR"
47 48
MANAGE_LOCAL_HBASE = "MANAGE_LOCAL_HBASE"
MANAGE_LOCAL_SOLR = "MANAGE_LOCAL_SOLR"
49
MANAGE_EMBEDDED_CASSANDRA = "MANAGE_EMBEDDED_CASSANDRA"
50
MANAGE_LOCAL_ELASTICSEARCH = "MANAGE_LOCAL_ELASTICSEARCH"
51 52 53 54 55 56 57 58 59
SOLR_BIN = "SOLR_BIN"
SOLR_CONF = "SOLR_CONF"
SOLR_PORT = "SOLR_PORT"
DEFAULT_SOLR_PORT = "9838"
SOLR_SHARDS = "SOLR_SHARDS"
DEFAULT_SOLR_SHARDS = "1"
SOLR_REPLICATION_FACTOR = "SOLR_REPLICATION_FACTOR"
DEFAULT_SOLR_REPLICATION_FACTOR = "1"

60
ENV_KEYS = ["JAVA_HOME", ATLAS_OPTS, ATLAS_SERVER_OPTS, ATLAS_SERVER_HEAP, ATLAS_LOG, ATLAS_PID, ATLAS_CONF,
61
            "ATLASCPPATH", ATLAS_DATA, ATLAS_HOME, ATLAS_WEBAPP, HBASE_CONF_DIR, SOLR_PORT, MANAGE_LOCAL_HBASE,
62
            MANAGE_LOCAL_SOLR, MANAGE_EMBEDDED_CASSANDRA, MANAGE_LOCAL_ELASTICSEARCH]
Jon Maron committed
63 64
IS_WINDOWS = platform.system() == "Windows"
ON_POSIX = 'posix' in sys.builtin_module_names
65
CONF_FILE="atlas-application.properties"
66
STORAGE_BACKEND_CONF="atlas.graph.storage.backend"
67
HBASE_STORAGE_LOCAL_CONF_ENTRY="atlas.graph.storage.hostname\s*=\s*localhost"
68
SOLR_INDEX_CONF_ENTRY="atlas.graph.index.search.backend\s*=\s*solr"
69 70
SOLR_INDEX_LOCAL_CONF_ENTRY="atlas.graph.index.search.solr.zookeeper-url\s*=\s*localhost"
SOLR_INDEX_ZK_URL="atlas.graph.index.search.solr.zookeeper-url"
71
TOPICS_TO_CREATE="atlas.notification.topics"
72 73 74 75 76
ATLAS_HTTP_PORT="atlas.server.http.port"
ATLAS_HTTPS_PORT="atlas.server.https.port"
DEFAULT_ATLAS_HTTP_PORT="21000"
DEFAULT_ATLAS_HTTPS_PORT="21443"
ATLAS_ENABLE_TLS="atlas.enableTLS"
77 78
ATLAS_SERVER_BIND_ADDRESS="atlas.server.bind.address"
DEFAULT_ATLAS_SERVER_HOST="localhost"
79

Jon Maron committed
80 81 82 83 84 85 86 87
DEBUG = False

def scriptDir():
    """
    get the script path
    """
    return os.path.dirname(os.path.realpath(__file__))

88
def atlasDir():
Jon Maron committed
89
    home = os.path.dirname(scriptDir())
90
    return os.environ.get(ATLAS_HOME, home)
Jon Maron committed
91 92 93 94 95 96

def libDir(dir) :
    return os.path.join(dir, LIB)

def confDir(dir):
    localconf = os.path.join(dir, CONF)
97
    return os.environ.get(ATLAS_CONF, localconf)
Jon Maron committed
98

99 100 101 102 103
def hbaseBinDir(dir):
    return os.path.join(dir, "hbase", BIN)

def hbaseConfDir(dir):
    return os.environ.get(HBASE_CONF_DIR, os.path.join(dir, "hbase", CONF))
104

105 106 107
def zookeeperBinDir(dir):
    return os.environ.get(SOLR_BIN, os.path.join(dir, "zk", BIN))

108 109 110
def solrBinDir(dir):
    return os.environ.get(SOLR_BIN, os.path.join(dir, "solr", BIN))

111 112 113
def elasticsearchBinDir(dir):
    return os.environ.get(SOLR_BIN, os.path.join(dir, "elasticsearch", BIN))

114
def solrConfDir(dir):
115
    return os.environ.get(SOLR_CONF, os.path.join(dir, "solr", CONFIG_SETS_CONF))
116 117 118 119 120 121 122 123 124 125

def solrPort():
    return os.environ.get(SOLR_PORT, DEFAULT_SOLR_PORT)

def solrShards():
    return os.environ.get(SOLR_SHARDS, DEFAULT_SOLR_SHARDS)

def solrReplicationFactor():
    return os.environ.get(SOLR_REPLICATION_FACTOR, DEFAULT_SOLR_REPLICATION_FACTOR)

Jon Maron committed
126 127
def logDir(dir):
    localLog = os.path.join(dir, LOG)
128
    return os.environ.get(ATLAS_LOG, localLog)
Jon Maron committed
129

130 131
def pidFile(dir):
    localPid = os.path.join(dir, LOG)
132
    return os.path.join(os.environ.get(ATLAS_PID, localPid), 'atlas.pid')
133

Jon Maron committed
134 135
def dataDir(dir):
    data = os.path.join(dir, DATA)
136
    return os.environ.get(ATLAS_DATA, data)
Jon Maron committed
137 138 139

def webAppDir(dir):
    webapp = os.path.join(dir, WEBAPP)
140
    return os.environ.get(ATLAS_WEBAPP, webapp)
Jon Maron committed
141

142 143 144
def kafkaTopicSetupDir(homeDir):
    return os.path.join(homeDir, "hook", "kafka-topic-setup")

Jon Maron committed
145 146
def expandWebApp(dir):
    webappDir = webAppDir(dir)
147
    webAppMetadataDir = os.path.join(webappDir, "atlas")
Jon Maron committed
148 149 150 151
    d = os.sep
    if not os.path.exists(os.path.join(webAppMetadataDir, "WEB-INF")):
        try:
            os.makedirs(webAppMetadataDir)
152
        except OSError as e:
Jon Maron committed
153 154 155
            if e.errno != errno.EEXIST:
                raise e
            pass
156 157 158
        atlasWarPath = os.path.join(atlasDir(), "server", "webapp", "atlas.war")
        if (isCygwin()):
            atlasWarPath = convertCygwinPath(atlasWarPath)
Jon Maron committed
159
        os.chdir(webAppMetadataDir)
160
        jar(atlasWarPath)
Jon Maron committed
161 162 163 164 165 166 167

def dirMustExist(dirname):
    if not os.path.exists(dirname):
        os.mkdir(dirname)
    return dirname

def executeEnvSh(confDir):
168
    envscript = '%s/atlas-env.sh' % confDir
Jon Maron committed
169 170 171 172 173 174 175 176 177 178 179 180 181
    if not IS_WINDOWS and os.path.exists(envscript):
        envCmd = 'source %s && env' % envscript
        command = ['bash', '-c', envCmd]

        proc = subprocess.Popen(command, stdout = subprocess.PIPE)

        for line in proc.stdout:
            (key, _, value) = line.strip().partition("=")
            if key in ENV_KEYS:
                os.environ[key] = value

        proc.communicate()

182
def java(classname, args, classpath, jvm_opts_list, logdir=None):
183 184 185
    java_home = os.environ.get("JAVA_HOME", None)
    if java_home:
        prg = os.path.join(java_home, "bin", "java")
Jon Maron committed
186 187 188
    else:
        prg = which("java")

189 190 191
    if prg is None:
        raise EnvironmentError('The java binary could not be found in your path or JAVA_HOME')

Jon Maron committed
192 193 194 195 196 197
    commandline = [prg]
    commandline.extend(jvm_opts_list)
    commandline.append("-classpath")
    commandline.append(classpath)
    commandline.append(classname)
    commandline.extend(args)
198
    return runProcess(commandline, logdir)
Jon Maron committed
199 200

def jar(path):
201 202 203
    java_home = os.environ.get("JAVA_HOME", None)
    if java_home:
        prg = os.path.join(java_home, "bin", "jar")
Jon Maron committed
204 205 206
    else:
        prg = which("jar")

207 208 209
    if prg is None:
        raise EnvironmentError('The jar binary could not be found in your path or JAVA_HOME')

Jon Maron committed
210 211 212
    commandline = [prg]
    commandline.append("-xf")
    commandline.append(path)
213 214
    process = runProcess(commandline)
    process.wait()
Jon Maron committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

def is_exe(fpath):
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

def which(program):

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

234
def runProcess(commandline, logdir=None, shell=False, wait=False):
Jon Maron committed
235 236 237 238 239 240
    """
    Run a process
    :param commandline: command line
    :return:the return code
    """
    global finished
241
    debug ("Executing : %s" % str(commandline))
242
    timestr = time.strftime("atlas.%Y%m%d-%H%M%S")
243 244 245 246 247
    stdoutFile = None
    stderrFile = None
    if logdir:
        stdoutFile = open(os.path.join(logdir, timestr + ".out"), "w")
        stderrFile = open(os.path.join(logdir,timestr + ".err"), "w")
248 249 250 251 252 253 254

    p = subprocess.Popen(commandline, stdout=stdoutFile, stderr=stderrFile, shell=shell)

    if wait:
        p.communicate()

    return p
Jon Maron committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361

def print_output(name, src, toStdErr):
    """
    Relay the output stream to stdout line by line
    :param name:
    :param src: source stream
    :param toStdErr: flag set if stderr is to be the dest
    :return:
    """

    global needPassword
    debug ("starting printer for %s" % name )
    line = ""
    while not finished:
        (line, done) = read(src, line)
        if done:
            out(toStdErr, line + "\n")
            flush(toStdErr)
            if line.find("Enter password for") >= 0:
                needPassword = True
            line = ""
    out(toStdErr, line)
    # closedown: read remainder of stream
    c = src.read(1)
    while c!="" :
        c = c.decode('utf-8')
        out(toStdErr, c)
        if c == "\n":
            flush(toStdErr)
        c = src.read(1)
    flush(toStdErr)
    src.close()

def read_input(name, exe):
    """
    Read input from stdin and send to process
    :param name:
    :param process: process to send input to
    :return:
    """
    global needPassword
    debug ("starting reader for %s" % name )
    while not finished:
        if needPassword:
            needPassword = False
            if sys.stdin.isatty():
                cred = getpass.getpass()
            else:
                cred = sys.stdin.readline().rstrip()
            exe.stdin.write(cred + "\n")

def debug(text):
    if DEBUG: print '[DEBUG] ' + text


def error(text):
    print '[ERROR] ' + text
    sys.stdout.flush()

def info(text):
    print text
    sys.stdout.flush()


def out(toStdErr, text) :
    """
    Write to one of the system output channels.
    This action does not add newlines. If you want that: write them yourself
    :param toStdErr: flag set if stderr is to be the dest
    :param text: text to write.
    :return:
    """
    if toStdErr:
        sys.stderr.write(text)
    else:
        sys.stdout.write(text)

def flush(toStdErr) :
    """
    Flush the output stream
    :param toStdErr: flag set if stderr is to be the dest
    :return:
    """
    if toStdErr:
        sys.stderr.flush()
    else:
        sys.stdout.flush()

def read(pipe, line):
    """
    read a char, append to the listing if there is a char that is not \n
    :param pipe: pipe to read from
    :param line: line being built up
    :return: (the potentially updated line, flag indicating newline reached)
    """

    c = pipe.read(1)
    if c != "":
        o = c.decode('utf-8')
        if o != '\n':
            line += o
            return line, False
        else:
            return line, True
    else:
        return line, False

362 363
def writePid(atlas_pid_file, process):
    f = open(atlas_pid_file, 'w')
Jon Maron committed
364 365 366
    f.write(str(process.pid))
    f.close()

367 368 369 370 371 372 373 374 375 376 377 378 379 380
def exist_pid(pid):
    if  ON_POSIX:
        #check if process id exist in the current process table
        #See man 2 kill - Linux man page for info about the kill(pid,0) system function
        try:
            os.kill(pid, 0)
        except OSError as e :
            return e.errno == errno.EPERM
        else:
            return True

    elif IS_WINDOWS:
        #The os.kill approach does not work on Windows with python 2.7
        #the output from tasklist command is searched for the process id
381 382
        pidStr = str(pid)
        command='tasklist /fi  "pid eq %s"' % pidStr
383 384 385 386 387
        sub_process=subprocess.Popen(command, stdout = subprocess.PIPE, shell=False)
        sub_process.communicate()
        output = subprocess.check_output(command)
        output=split(" *",output)
        for line in output:
388
            if pidStr in line:
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
                return True
        return False
    #os other than nt or posix - not supported - need to delete the file to restart server if pid no longer exist
    return True

def wait_for_shutdown(pid, msg, wait):
    count = 0
    sys.stdout.write(msg)
    while exist_pid(pid):
        sys.stdout.write('.')
        sys.stdout.flush()
        sleep(1)
        if count > wait:
            break
        count = count + 1

    sys.stdout.write('\n')

def is_hbase(confdir):
408 409 410 411 412
    confFile = os.path.join(confdir, CONF_FILE)
    storageBackEnd = getConfig(confFile, STORAGE_BACKEND_CONF)
    if storageBackEnd is not None:
        storageBackEnd = storageBackEnd.strip()
    return storageBackEnd is None or storageBackEnd == '' or storageBackEnd == 'hbase' or storageBackEnd == 'hbase2'
413 414

def is_hbase_local(confdir):
415
    if os.environ.get(MANAGE_LOCAL_HBASE, "False").lower() == 'false':
416 417
        return False

418 419
    confFile = os.path.join(confdir, CONF_FILE)
    return is_hbase(confdir) and grep(confFile, HBASE_STORAGE_LOCAL_CONF_ENTRY) is not None
420

421 422 423 424 425 426 427 428 429 430
def run_hbase_action(dir, action, hbase_conf_dir = None, logdir = None, wait=True):
    if IS_WINDOWS:
        if action == 'start':
            hbaseScript = 'start-hbase.cmd'
        else:
            hbaseScript = 'stop-hbase.cmd'
        if hbase_conf_dir is not None:
            cmd = [os.path.join(dir, hbaseScript), '--config', hbase_conf_dir]
        else:
            cmd = [os.path.join(dir, hbaseScript)]
431
    else:
432 433 434 435 436 437
        hbaseScript = 'hbase-daemon.sh'
        if hbase_conf_dir is not None:
            cmd = [os.path.join(dir, hbaseScript), '--config', hbase_conf_dir, action, 'master']
        else:
            cmd = [os.path.join(dir, hbaseScript), action, 'master']

438

439
    return runProcess(cmd, logdir, False, wait)
440

441 442 443 444
def is_solr(confdir):
    confdir = os.path.join(confdir, CONF_FILE)
    return grep(confdir, SOLR_INDEX_CONF_ENTRY) is not None

445 446 447 448 449 450
def is_cassandra_local(configdir):
    if os.environ.get(MANAGE_EMBEDDED_CASSANDRA, "False").lower() == 'false':
        return False

    return True

451
def is_solr_local(confdir):
452
    if os.environ.get(MANAGE_LOCAL_SOLR, "False").lower() == 'false':
453 454 455 456 457
        return False

    confdir = os.path.join(confdir, CONF_FILE)
    return grep(confdir, SOLR_INDEX_CONF_ENTRY) is not None and grep(confdir, SOLR_INDEX_LOCAL_CONF_ENTRY) is not None

458 459 460 461 462 463
def is_elasticsearch_local():
    if os.environ.get(MANAGE_LOCAL_ELASTICSEARCH, "False").lower() == 'false':
        return False

    return True

464 465 466 467
def get_solr_zk_url(confdir):
    confdir = os.path.join(confdir, CONF_FILE)
    return getConfig(confdir, SOLR_INDEX_ZK_URL)

468 469 470 471 472 473
def get_topics_to_create(confdir):
    confdir = os.path.join(confdir, CONF_FILE)
    topic_list = getConfig(confdir, TOPICS_TO_CREATE)
    if topic_list is not None:
        topics = topic_list.split(",")
    else:
474
        topics = [getConfigWithDefault("atlas.notification.hook.topic.name", "ATLAS_HOOK"), getConfigWithDefault("atlas.notification.entities.topic.name", "ATLAS_ENTITIES")]
475 476
    return topics

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
def get_atlas_url_port(confdir):
    port = None
    if '-port' in sys.argv:
        port = sys.argv[sys.argv.index('-port')+1]

    if port is None:
        confdir = os.path.join(confdir, CONF_FILE)
        enable_tls = getConfig(confdir, ATLAS_ENABLE_TLS)
        if enable_tls is not None and enable_tls.lower() == 'true':
            port = getConfigWithDefault(confdir, ATLAS_HTTPS_PORT, DEFAULT_ATLAS_HTTPS_PORT)
        else:
            port = getConfigWithDefault(confdir, ATLAS_HTTP_PORT, DEFAULT_ATLAS_HTTP_PORT)

    print "starting atlas on port %s" % port
    return port

493 494 495 496 497 498 499 500
def get_atlas_url_host(confdir):
    confdir = os.path.join(confdir, CONF_FILE)
    host = getConfigWithDefault(confdir, ATLAS_SERVER_BIND_ADDRESS, DEFAULT_ATLAS_SERVER_HOST)
    if (host == '0.0.0.0'):
        host = DEFAULT_ATLAS_SERVER_HOST
    print "starting atlas on host %s" % host
    return host

501 502
def wait_for_startup(confdir, wait):
    count = 0
503
    host = get_atlas_url_host(confdir)
504 505 506 507 508
    port = get_atlas_url_port(confdir)
    while True:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
509
            s.connect((host, int(port)))
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
            s.close()
            break
        except Exception as e:
            # Wait for 1 sec before next ping
            sys.stdout.write('.')
            sys.stdout.flush()
            sleep(1)

        if count > wait:
            s.close()
            break

        count = count + 1

    sys.stdout.write('\n')
525

526 527 528 529 530 531 532 533 534 535
def run_zookeeper(dir, action, logdir = None, wait=True):
    zookeeperScript = "zkServer.sh"

    if IS_WINDOWS:
        zookeeperScript = "zkServer.cmd"

    cmd = [os.path.join(dir, zookeeperScript), action, os.path.join(dir, '../../conf/zookeeper/zoo.cfg')]

    return runProcess(cmd, logdir, False, wait)

536 537 538 539 540 541 542 543 544 545 546 547 548
def start_elasticsearch(dir, logdir = None, wait=True):

    elasticsearchScript = "elasticsearch"

    if IS_WINDOWS:
        elasticsearchScript = "elasticsearch.bat"

    cmd = [os.path.join(dir, elasticsearchScript), '-d', '-p', os.path.join(logdir, 'elasticsearch.pid')]

    processVal = runProcess(cmd, logdir, False, wait)
    sleep(6)
    return processVal

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
def run_solr(dir, action, zk_url = None, port = None, logdir = None, wait=True):

    solrScript = "solr"

    if IS_WINDOWS:
        solrScript = "solr.cmd"

    if zk_url is None:
        if port is None:
            cmd = [os.path.join(dir, solrScript), action]
        else:
            cmd = [os.path.join(dir, solrScript), action, '-p', str(port)]
    else:
        if port is None:
            cmd = [os.path.join(dir, solrScript), action, '-z', zk_url]
        else:
            cmd = [os.path.join(dir, solrScript), action, '-z', zk_url, '-p', port]

    return runProcess(cmd, logdir, False, wait)

def create_solr_collection(dir, confdir, index, logdir = None, wait=True):
    solrScript = "solr"

    if IS_WINDOWS:
        solrScript = "solr.cmd"

    cmd = [os.path.join(dir, solrScript), 'create', '-c', index, '-d', confdir,  '-shards',  solrShards(),  '-replicationFactor', solrReplicationFactor()]

    return runProcess(cmd, logdir, False, wait)

579 580 581 582
def configure_hbase(dir):
    env_conf_dir = os.environ.get(HBASE_CONF_DIR)
    conf_dir = os.path.join(dir, "hbase", CONF)
    tmpl_dir = os.path.join(dir, CONF, "hbase")
583
    data_dir = dataDir(atlasDir())
584 585 586 587 588

    if env_conf_dir is None or env_conf_dir == conf_dir:
        hbase_conf_file = "hbase-site.xml"

        tmpl_file = os.path.join(tmpl_dir, hbase_conf_file + ".template")
589 590 591 592 593
        if IS_WINDOWS:
             url_prefix="file:///"
        else:
             url_prefix="file://"

594 595 596 597 598 599 600 601 602
        conf_file = os.path.join(conf_dir, hbase_conf_file)
        if os.path.exists(tmpl_file):

            debug ("Configuring " + tmpl_file + " to " + conf_file)
            f = open(tmpl_file,'r')
            template = f.read()
            f.close()

            config = template.replace("${hbase_home}", dir)
603
            config = config.replace("${atlas_data}", data_dir)
604
            config = config.replace("${url_prefix}", url_prefix)
605 606 607 608 609

            f = open(conf_file,'w')
            f.write(config)
            f.close()
            os.remove(tmpl_file)
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
def configure_zookeeper(dir):

    conf_dir = os.path.join(dir, CONF, "zookeeper")
    zk_conf_file = "zoo.cfg"
    tmpl_file = os.path.join(conf_dir, zk_conf_file + ".template")

    conf_file = os.path.join(conf_dir, zk_conf_file)
    if os.path.exists(tmpl_file):
        debug ("Configuring " + tmpl_file + " to " + conf_file)

        f = open(tmpl_file,'r')
        template = f.read()
        f.close()

        config = template.replace("${atlas_home}", dir)

        f = open(conf_file,'w')
        f.write(config)
        f.close()
        os.remove(tmpl_file)

def configure_cassandra(dir):

    conf_dir = os.path.join(dir, CONF)
    cassandra_conf_file = "cassandra.yml"
    tmpl_file = os.path.join(conf_dir, cassandra_conf_file + ".template")

    conf_file = os.path.join(conf_dir, cassandra_conf_file)
    if os.path.exists(tmpl_file):
        debug ("Configuring " + tmpl_file + " to " + conf_file)

        f = open(tmpl_file,'r')
        template = f.read()
        f.close()

        config = template.replace("${atlas_home}", dir)

        f = open(conf_file,'w')
        f.write(config)
        f.close()
        os.remove(tmpl_file)

653
def server_already_running(pid):
654
    print "Atlas server is already running under process %s" % pid
655 656
    sys.exit()

657
def server_pid_not_running(pid):
658 659 660 661
    print "The Server is no longer running with pid %s" %pid

def grep(file, value):
    for line in open(file).readlines():
662
        if re.match(value, line):
663 664
           return line
    return None
665

666 667 668 669 670 671 672
def getConfig(file, key):
    key = key + "\s*="
    for line in open(file).readlines():
        if re.match(key, line):
            return line.split('=')[1].strip()
    return None

673 674 675 676 677 678
def getConfigWithDefault(file, key, defaultValue):
    value = getConfig(file, key)
    if value is None:
        value = defaultValue
    return value

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
def isCygwin():
    return platform.system().startswith("CYGWIN")

# Convert the specified cygwin-style pathname to Windows format,
# using the cygpath utility.  By default, path is assumed
# to be a file system pathname.  If isClasspath is True,
# then path is treated as a Java classpath string.
def convertCygwinPath(path, isClasspath=False):
    if (isClasspath):
        cygpathArgs = ["cygpath", "-w", "-p", path]
    else:
        cygpathArgs = ["cygpath", "-w", path]
    windowsPath = subprocess.Popen(cygpathArgs, stdout=subprocess.PIPE).communicate()[0]
    windowsPath = windowsPath.strip()
    return windowsPath