Esempio n. 1
0
def main():
  global datastore_path
  global deployment_config

  logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)

  parser = argparse.ArgumentParser()
  parser.add_argument('-p', '--port', type=int, default=DEFAULT_PORT,
                      required=True, help="The blobstore server's port")
  parser.add_argument('-d', '--datastore-path', required=True,
                      help='The location of the datastore server')
  args = parser.parse_args()

  datastore_path = args.datastore_path
  deployment_config = DeploymentConfig(appscale_info.get_zk_locations_string())
  setup_env()

  http_server = tornado.httpserver.HTTPServer(
    Application(), max_buffer_size=MAX_REQUEST_BUFF_SIZE)

  http_server.listen(args.port)

  acc = appscale_info.get_appcontroller_client()
  acc.add_routing_for_blob_server()

  logging.info('Starting BlobServer on {}'.format(args.port))
  tornado.ioloop.IOLoop.instance().start()
Esempio n. 2
0
def add_routing(app, port):
    """ Tells the AppController to begin routing traffic to an AppServer.

  Args:
    app: A string that contains the application ID.
    port: A string that contains the port that the AppServer listens on.
  """
    logging.info("Waiting for application {} on port {} to be active.".format(
        str(app), str(port)))
    if not wait_on_app(port):
        # In case the AppServer fails we let the AppController to detect it
        # and remove it if it still show in monit.
        logging.warning("AppServer did not come up in time, for {}:{}.".format(
            str(app), str(port)))
        return

    acc = appscale_info.get_appcontroller_client()
    appserver_ip = appscale_info.get_private_ip()

    while True:
        result = acc.add_routing_for_appserver(app, appserver_ip, port)
        if result == AppControllerClient.NOT_READY:
            logging.info('AppController not yet ready to add routing.')
            time.sleep(ROUTING_RETRY_INTERVAL)
        else:
            break

    logging.info('Successfully established routing for {} on port {}'.format(
        app, port))
Esempio n. 3
0
def add_routing(version_key, port):
    """ Tells the AppController to begin routing traffic to an AppServer.

  Args:
    version_key: A string that contains the version key.
    port: A string that contains the port that the AppServer listens on.
  """
    logging.info('Waiting for {}:{}'.format(version_key, port))
    if not wait_on_app(port):
        # In case the AppServer fails we let the AppController to detect it
        # and remove it if it still show in monit.
        logging.warning('{}:{} did not come up in time'.format(
            version_key, port))
        return

    acc = appscale_info.get_appcontroller_client()

    while True:
        result = acc.add_routing_for_appserver(version_key, options.private_ip,
                                               port)
        if result == AppControllerClient.NOT_READY:
            logging.info('AppController not yet ready to add routing.')
            time.sleep(ROUTING_RETRY_INTERVAL)
        else:
            break

    logging.info('Successfully established routing for {}:{}'.format(
        version_key, port))
Esempio n. 4
0
def add_routing(version_key, port):
  """ Tells the AppController to begin routing traffic to an AppServer.

  Args:
    version_key: A string that contains the version key.
    port: A string that contains the port that the AppServer listens on.
  """
  logging.info('Waiting for {}:{}'.format(version_key, port))
  if not wait_on_app(port):
    # In case the AppServer fails we let the AppController to detect it
    # and remove it if it still show in monit.
    logging.warning('{}:{} did not come up in time'.format(version_key, port))
    return

  acc = appscale_info.get_appcontroller_client()

  while True:
    result = acc.add_routing_for_appserver(version_key, options.private_ip,
                                           port)
    if result == AppControllerClient.NOT_READY:
      logging.info('AppController not yet ready to add routing.')
      time.sleep(ROUTING_RETRY_INTERVAL)
    else:
      break

  logging.info(
    'Successfully established routing for {}:{}'.format(version_key, port))
Esempio n. 5
0
def main():
    """ Starts the AdminServer. """
    logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        default=constants.DEFAULT_PORT,
                        help='The port to listen on')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Output debug-level logging')
    args = parser.parse_args()

    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    options.define('secret', appscale_info.get_secret())
    options.define('login_ip', appscale_info.get_login_ip())
    options.define('private_ip', appscale_info.get_private_ip())

    acc = appscale_info.get_appcontroller_client()
    ua_client = UAClient(appscale_info.get_db_master_ip(), options.secret)
    zk_client = KazooClient(hosts=','.join(appscale_info.get_zk_node_ips()),
                            connection_retry=ZK_PERSISTENT_RECONNECTS)
    zk_client.start()
    version_update_lock = zk_client.Lock(constants.VERSION_UPDATE_LOCK_NODE)
    thread_pool = ThreadPoolExecutor(4)
    monit_operator = MonitOperator()
    all_resources = {
        'acc': acc,
        'ua_client': ua_client,
        'zk_client': zk_client,
        'version_update_lock': version_update_lock,
        'thread_pool': thread_pool
    }

    if options.private_ip in appscale_info.get_taskqueue_nodes():
        logging.info('Starting push worker manager')
        GlobalPushWorkerManager(zk_client, monit_operator)

    app = web.Application([
        ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions',
         VersionsHandler, all_resources),
        ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions/([a-z0-9-]+)',
         VersionHandler, all_resources),
        ('/v1/apps/([a-z0-9-]+)/operations/([a-z0-9-]+)', OperationsHandler),
        ('/api/queue/update', UpdateQueuesHandler, {
            'zk_client': zk_client
        })
    ])
    logging.info('Starting AdminServer')
    app.listen(args.port)
    io_loop = IOLoop.current()
    io_loop.start()
Esempio n. 6
0
def get_cluster_stats():
    """ Collects platform stats from all deployment nodes.

  Returns:
    A dictionary containing all the monitoring stats, if all nodes are
    accessible. {"success": False, "error": message} otherwise.
  """
    acc = appscale_info.get_appcontroller_client()
    nodes_stats = acc.get_cluster_stats()
    return {node["public_ip"]: node for node in nodes_stats}
Esempio n. 7
0
def get_deployment_id():
  """ Retrieves the deployment ID for this AppScale deployment.

  Returns:
    A str, the secret key used for registering this deployment with the
    AppScale Portal. None if the deployment is not registered.
  """
  try:
    acc = appscale_info.get_appcontroller_client()
    if acc.deployment_id_exists():
      return acc.get_deployment_id()
  except AppControllerException:
    logging.exception("AppControllerException while querying for deployment "
      "ID.")
    return None
Esempio n. 8
0
    def deploy(self):
        """ Uploads the sensor app for registered deployments. """
        deployment_id = helper.get_deployment_id()
        # If deployment is not registered, then do nothing.
        if not deployment_id:
            return

        ua_client = UAClient(appscale_info.get_db_master_ip(), options.secret)

        # If the appscalesensor app is already running, then do nothing.
        version_node = '/appscale/projects/{}/services/{}/versions/{}'.format(
            constants.APPSCALE_SENSOR, DEFAULT_SERVICE, DEFAULT_VERSION)
        if self.zk_client.exists(version_node) is not None:
            return

        pwd = appscale_utils.encrypt_password(
            constants.USER_EMAIL, appscale_utils.random_password_generator())
        if create_appscale_user(pwd, ua_client) and create_xmpp_user(
                pwd, ua_client):
            logging.debug(
                "Created new user and now tarring app to be deployed.")
            file_path = os.path.join(os.path.dirname(__file__),
                                     '../Apps/sensor')
            app_dir_location = os.path.join(constants.APP_DIR_LOCATION,
                                            constants.APPSCALE_SENSOR)
            archive = tarfile.open(app_dir_location, "w|gz")
            archive.add(file_path, arcname=constants.APPSCALE_SENSOR)
            archive.close()

            try:
                logging.info(
                    "Deploying the sensor app for registered deployments.")
                acc = appscale_info.get_appcontroller_client()
                acc.upload_app(app_dir_location, constants.FILE_SUFFIX)
            except AppControllerException:
                logging.exception(
                    "AppControllerException while trying to deploy "
                    "appscalesensor app.")
        else:
            logging.error(
                "Error while creating or accessing the user to deploy "
                "appscalesensor app.")
Esempio n. 9
0
def deploy_sensor_app():
    """ Uploads the sensor app for registered deployments. """

    deployment_id = helper.get_deployment_id()
    #If deployment is not registered, then do nothing.
    if not deployment_id:
        return

    secret = appscale_info.get_secret()
    ua_client = UAClient(appscale_info.get_db_master_ip(), secret)

    # If the appscalesensor app is already running, then do nothing.
    if ua_client.is_app_enabled(hermes_constants.APPSCALE_SENSOR):
        return

    pwd = appscale_utils.encrypt_password(
        hermes_constants.USER_EMAIL,
        appscale_utils.random_password_generator())
    if create_appscale_user(pwd, ua_client) and create_xmpp_user(
            pwd, ua_client):
        logging.debug("Created new user and now tarring app to be deployed.")
        file_path = os.path.join(os.path.dirname(__file__), '../Apps/sensor')
        app_dir_location = os.path.join(hermes_constants.APP_DIR_LOCATION,
                                        hermes_constants.APPSCALE_SENSOR)
        archive = tarfile.open(app_dir_location, "w|gz")
        archive.add(file_path, arcname=hermes_constants.APPSCALE_SENSOR)
        archive.close()

        try:
            logging.info(
                "Deploying the sensor app for registered deployments.")
            acc = appscale_info.get_appcontroller_client()
            acc.upload_app(app_dir_location, hermes_constants.FILE_SUFFIX,
                           hermes_constants.USER_EMAIL)
        except AppControllerException:
            logging.exception("AppControllerException while trying to deploy "
                              "appscalesensor app.")
    else:
        logging.error("Error while creating or accessing the user to deploy "
                      "appscalesensor app.")
Esempio n. 10
0
  def deploy(self):
    """ Uploads the sensor app for registered deployments. """
    deployment_id = helper.get_deployment_id()
    # If deployment is not registered, then do nothing.
    if not deployment_id:
      return

    ua_client = UAClient(appscale_info.get_db_master_ip(), options.secret)

    # If the appscalesensor app is already running, then do nothing.
    version_node = '/appscale/projects/{}/services/{}/versions/{}'.format(
      constants.APPSCALE_SENSOR, DEFAULT_SERVICE, DEFAULT_VERSION)
    if self.zk_client.exists(version_node) is not None:
      return

    pwd = appscale_utils.encrypt_password(constants.USER_EMAIL,
                                          appscale_utils.random_password_generator())
    if create_appscale_user(pwd, ua_client) and create_xmpp_user(pwd,
                                                                 ua_client):
      logging.debug("Created new user and now tarring app to be deployed.")
      file_path = os.path.join(os.path.dirname(__file__), '../Apps/sensor')
      app_dir_location = os.path.join(constants.APP_DIR_LOCATION,
                                      constants.APPSCALE_SENSOR)
      archive = tarfile.open(app_dir_location, "w|gz")
      archive.add(file_path, arcname=constants.APPSCALE_SENSOR)
      archive.close()

      try:
        logging.info("Deploying the sensor app for registered deployments.")
        acc = appscale_info.get_appcontroller_client()
        acc.upload_app(app_dir_location, constants.FILE_SUFFIX)
      except AppControllerException:
        logging.exception("AppControllerException while trying to deploy "
                          "appscalesensor app.")
    else:
      logging.error("Error while creating or accessing the user to deploy "
                    "appscalesensor app.")
Esempio n. 11
0
def main():
  """ Starts the AdminServer. """
  logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)

  parser = argparse.ArgumentParser(
    prog='appscale-admin', description='Manages AppScale-related processes')
  subparsers = parser.add_subparsers(dest='command')
  subparsers.required = True

  serve_parser = subparsers.add_parser(
    'serve', description='Starts the server that manages AppScale processes')
  serve_parser.add_argument(
    '-p', '--port', type=int, default=constants.DEFAULT_PORT,
    help='The port to listen on')
  serve_parser.add_argument(
    '-v', '--verbose', action='store_true', help='Output debug-level logging')

  subparsers.add_parser(
    'summary', description='Lists AppScale processes running on this machine')
  restart_parser = subparsers.add_parser(
    'restart',
    description='Restart AppScale processes running on this machine')
  restart_parser.add_argument('service', nargs='+',
                              help='The process or service ID to restart')

  args = parser.parse_args()
  if args.command == 'summary':
    table = sorted(list(get_combined_services().items()))
    print(tabulate(table, headers=['Service', 'State']))
    sys.exit(0)

  if args.command == 'restart':
    socket_path = urlquote(ServiceManagerHandler.SOCKET_PATH, safe='')
    session = requests_unixsocket.Session()
    response = session.post(
      'http+unix://{}/'.format(socket_path),
      data={'command': 'restart', 'arg': [args.service]})
    response.raise_for_status()
    return

  if args.verbose:
    logger.setLevel(logging.DEBUG)

  options.define('secret', appscale_info.get_secret())
  options.define('login_ip', appscale_info.get_login_ip())
  options.define('private_ip', appscale_info.get_private_ip())
  options.define('load_balancers', appscale_info.get_load_balancer_ips())

  acc = appscale_info.get_appcontroller_client()
  ua_client = UAClient(appscale_info.get_db_master_ip(), options.secret)
  zk_client = KazooClient(
    hosts=','.join(appscale_info.get_zk_node_ips()),
    connection_retry=ZK_PERSISTENT_RECONNECTS)
  zk_client.start()
  version_update_lock = zk_client.Lock(constants.VERSION_UPDATE_LOCK_NODE)
  thread_pool = ThreadPoolExecutor(4)
  monit_operator = MonitOperator()
  all_resources = {
    'acc': acc,
    'ua_client': ua_client,
    'zk_client': zk_client,
    'version_update_lock': version_update_lock,
    'thread_pool': thread_pool
  }

  if options.private_ip in appscale_info.get_taskqueue_nodes():
    logger.info('Starting push worker manager')
    GlobalPushWorkerManager(zk_client, monit_operator)

  service_manager = ServiceManager(zk_client)
  service_manager.start()

  app = web.Application([
    ('/oauth/token', OAuthHandler, {'ua_client': ua_client}),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions', VersionsHandler,
     {'ua_client': ua_client, 'zk_client': zk_client,
      'version_update_lock': version_update_lock, 'thread_pool': thread_pool}),
    ('/v1/projects', ProjectsHandler, all_resources),
    ('/v1/projects/([a-z0-9-]+)', ProjectHandler, all_resources),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)', ServiceHandler,
     all_resources),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions/([a-z0-9-]+)',
     VersionHandler, all_resources),
    ('/v1/apps/([a-z0-9-]+)/operations/([a-z0-9-]+)', OperationsHandler,
     {'ua_client': ua_client}),
    ('/api/cron/update', UpdateCronHandler,
     {'acc': acc, 'zk_client': zk_client, 'ua_client': ua_client}),
    ('/api/datastore/index/add', UpdateIndexesHandler,
     {'zk_client': zk_client, 'ua_client': ua_client}),
    ('/api/queue/update', UpdateQueuesHandler,
     {'zk_client': zk_client, 'ua_client': ua_client})
  ])
  logger.info('Starting AdminServer')
  app.listen(args.port)

  management_app = web.Application([
    ('/', ServiceManagerHandler, {'service_manager': service_manager})])
  management_server = HTTPServer(management_app)
  management_socket = bind_unix_socket(ServiceManagerHandler.SOCKET_PATH)
  management_server.add_socket(management_socket)

  io_loop = IOLoop.current()
  io_loop.start()
Esempio n. 12
0
def main():
  """ Starts the AdminServer. """
  logging.basicConfig(format=LOG_FORMAT, level=logging.INFO)

  parser = argparse.ArgumentParser(
    prog='appscale-admin', description='Manages AppScale-related processes')
  subparsers = parser.add_subparsers(dest='command')
  subparsers.required = True

  serve_parser = subparsers.add_parser(
    'serve', description='Starts the server that manages AppScale processes')
  serve_parser.add_argument(
    '-p', '--port', type=int, default=constants.DEFAULT_PORT,
    help='The port to listen on')
  serve_parser.add_argument(
    '-v', '--verbose', action='store_true', help='Output debug-level logging')

  subparsers.add_parser(
    'summary', description='Lists AppScale processes running on this machine')

  args = parser.parse_args()
  if args.command == 'summary':
    table = sorted(list(get_combined_services().items()))
    print(tabulate(table, headers=['Service', 'State']))
    sys.exit(0)

  if args.verbose:
    logger.setLevel(logging.DEBUG)

  options.define('secret', appscale_info.get_secret())
  options.define('login_ip', appscale_info.get_login_ip())
  options.define('private_ip', appscale_info.get_private_ip())
  options.define('load_balancers', appscale_info.get_load_balancer_ips())

  acc = appscale_info.get_appcontroller_client()
  ua_client = UAClient(appscale_info.get_db_master_ip(), options.secret)
  zk_client = KazooClient(
    hosts=','.join(appscale_info.get_zk_node_ips()),
    connection_retry=ZK_PERSISTENT_RECONNECTS)
  zk_client.start()
  version_update_lock = zk_client.Lock(constants.VERSION_UPDATE_LOCK_NODE)
  thread_pool = ThreadPoolExecutor(4)
  monit_operator = MonitOperator()
  all_resources = {
    'acc': acc,
    'ua_client': ua_client,
    'zk_client': zk_client,
    'version_update_lock': version_update_lock,
    'thread_pool': thread_pool
  }

  if options.private_ip in appscale_info.get_taskqueue_nodes():
    logger.info('Starting push worker manager')
    GlobalPushWorkerManager(zk_client, monit_operator)

  service_manager = ServiceManager(zk_client)
  service_manager.start()

  app = web.Application([
    ('/oauth/token', OAuthHandler, {'ua_client': ua_client}),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions', VersionsHandler,
     all_resources),
    ('/v1/projects', ProjectsHandler, all_resources),
    ('/v1/projects/([a-z0-9-]+)', ProjectHandler, all_resources),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)', ServiceHandler,
     all_resources),
    ('/v1/apps/([a-z0-9-]+)/services/([a-z0-9-]+)/versions/([a-z0-9-]+)',
     VersionHandler, all_resources),
    ('/v1/apps/([a-z0-9-]+)/operations/([a-z0-9-]+)', OperationsHandler,
     {'ua_client': ua_client}),
    ('/api/cron/update', UpdateCronHandler,
     {'acc': acc, 'zk_client': zk_client, 'ua_client': ua_client}),
    ('/api/queue/update', UpdateQueuesHandler,
     {'zk_client': zk_client, 'ua_client': ua_client})
  ])
  logger.info('Starting AdminServer')
  app.listen(args.port)
  io_loop = IOLoop.current()
  io_loop.start()
Esempio n. 13
0
Args:
  A string containing 'on' or 'off'.
Returns:
  A string indicating whether or not the operation was a success.
"""

import sys

from appscale.common import appscale_info

if __name__ == '__main__':
    make_active = False
    if len(sys.argv) < 2 or sys.argv[1] not in ['on', 'off']:
        print('Please give a value of "on" or "off".')
        sys.exit(1)

    if sys.argv[1] == 'on':
        make_active = True

    acc = appscale_info.get_appcontroller_client()
    result = acc.set_read_only(str(make_active).lower())
    if result != 'OK':
        print(result)
        sys.exit(1)

    if make_active:
        print('Datastore writes are now disabled.')
    else:
        print('Datastore writes are now enabled.')
Esempio n. 14
0
Args:
  A string containing 'on' or 'off'.
Returns:
  A string indicating whether or not the operation was a success.
"""

import sys

from appscale.common import appscale_info


if __name__ == '__main__':
  make_active = False
  if len(sys.argv) < 2 or sys.argv[1] not in ['on', 'off']:
    print('Please give a value of "on" or "off".')
    sys.exit(1)

  if sys.argv[1] == 'on':
    make_active = True

  acc = appscale_info.get_appcontroller_client()
  result = acc.set_read_only(str(make_active).lower())
  if result != 'OK':
    print(result)
    sys.exit(1)

  if make_active:
    print('Datastore writes are now disabled.')
  else:
    print('Datastore writes are now enabled.')