<commit_before>#
#

# Copyright (C) 2006, 2007 Google Inc.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Functions used by the node daemon"""


import os
import os.path
import shutil
import time
import stat
import errno
import re
import subprocess
import random
import logging
import tempfile

from ganeti import errors
from ganeti import utils
from ganeti import ssh
from ganeti import hypervisor
from ganeti import constants
from ganeti import bdev
from ganeti import objects
from ganeti import ssconf


def _GetSshRunner():
  return ssh.SshRunner()


def _GetMasterInfo():
  """Return the master ip and netdev.

  """
  try:
    ss = ssconf.SimpleStore()
    master_netdev = ss.GetMasterNetdev()
    master_ip = ss.GetMasterIP()
  except errors.ConfigurationError, err:
    logging.exception("Cluster configuration incomplete")
    return (None, None)
  return (master_netdev, master_ip)


def StartMaster(start_daemons):
  """Activate local node as master node.

  The function will always try activate the IP address of the master
  (if someone else has it, then it won't). Then, if the start_daemons
  parameter is True, it will also start the master daemons
  (ganet-masterd and ganeti-rapi).

  """
  ok = True
  master_netdev, master_ip = _GetMasterInfo()
  if not master_netdev:
    return False

  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
    if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT,
                     source=constants.LOCALHOST_IP_ADDRESS):
      # we already have the ip:
      logging.debug("Already started")
    else:
      logging.error("Someone else has the master ip, not activating")
      ok = False
  else:
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
                           "dev", master_netdev, "label",
                           "%s:0" % master_netdev])
    if result.failed:
      logging.error("Can't activate master IP: %s", result.output)
      ok = False

    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
                           "-s", master_ip, master_ip])
    # we'll ignore the exit code of arping

  # and now start the master and rapi daemons
  if start_daemons:
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
      result = utils.RunCmd([daemon])
      if result.failed:
        logging.error("Can't start daemon %s: %s", daemon, result.output)
        ok = False
  return ok


def StopMaster(stop_daemons):
  """Deactivate this node as master.

  The function will always try to deactivate the IP address of the
  master. Then, if the stop_daemons parameter is True, it will also
  stop the master daemons (ganet-masterd and ganeti-rapi).

  """
  master_netdev, master_ip = _GetMasterInfo()
  if not master_netdev:
    return False

  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
                         "dev", master_netdev])
  if result.failed:
    logging.error("Can't remove the master IP, error: %s", result.output)
    # but otherwise ignore the failure

  if stop_daemons:
    # stop/kill the rapi and the master daemon
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))

  return True


def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
  """Joins this node to the cluster.

  This does the following:
      - updates the hostkeys of the machine (rsa and dsa)
      - adds the ssh private key to the user
      - adds the ssh public key to the users' authorized_keys file

  """
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
  for name, content, mode in sshd_keys:
    utils.WriteFile(name, data=content, mode=mode)

  try:
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
                                                    mkdir=True)
  except errors.OpExecError, err:
    logging.exception("Error while processing user ssh files")
    return False

  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
    utils.WriteFile(name, data=content, mode=0600)

  utils.AddAuthorizedKey(auth_keys, sshpub)

  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])

  return True


def LeaveCluster():
  """Cleans up the current node and prepares it to be removed from the cluster.

  """
  if os.path.isdir(constants.DATA_DIR):
    for rel_name in utils.ListVisibleFiles(constants.DATA_DIR):
      full_name = os.path.join(constants.DATA_DIR, rel_name)
      if os.path.isfile(full_name) and not os.path.islink(full_name):
        utils.RemoveFile(full_name)
<commit_msg>Clean job queue directories when leaving cluster<commit_after>#
#

# Copyright (C) 2006, 2007 Google Inc.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Functions used by the node daemon"""


import os
import os.path
import shutil
import time
import stat
import errno
import re
import subprocess
import random
import logging
import tempfile

from ganeti import errors
from ganeti import utils
from ganeti import ssh
from ganeti import hypervisor
from ganeti import constants
from ganeti import bdev
from ganeti import objects
from ganeti import ssconf


def _GetSshRunner():
  return ssh.SshRunner()


def _GetMasterInfo():
  """Return the master ip and netdev.

  """
  try:
    ss = ssconf.SimpleStore()
    master_netdev = ss.GetMasterNetdev()
    master_ip = ss.GetMasterIP()
  except errors.ConfigurationError, err:
    logging.exception("Cluster configuration incomplete")
    return (None, None)
  return (master_netdev, master_ip)


def StartMaster(start_daemons):
  """Activate local node as master node.

  The function will always try activate the IP address of the master
  (if someone else has it, then it won't). Then, if the start_daemons
  parameter is True, it will also start the master daemons
  (ganet-masterd and ganeti-rapi).

  """
  ok = True
  master_netdev, master_ip = _GetMasterInfo()
  if not master_netdev:
    return False

  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
    if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT,
                     source=constants.LOCALHOST_IP_ADDRESS):
      # we already have the ip:
      logging.debug("Already started")
    else:
      logging.error("Someone else has the master ip, not activating")
      ok = False
  else:
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
                           "dev", master_netdev, "label",
                           "%s:0" % master_netdev])
    if result.failed:
      logging.error("Can't activate master IP: %s", result.output)
      ok = False

    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
                           "-s", master_ip, master_ip])
    # we'll ignore the exit code of arping

  # and now start the master and rapi daemons
  if start_daemons:
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
      result = utils.RunCmd([daemon])
      if result.failed:
        logging.error("Can't start daemon %s: %s", daemon, result.output)
        ok = False
  return ok


def StopMaster(stop_daemons):
  """Deactivate this node as master.

  The function will always try to deactivate the IP address of the
  master. Then, if the stop_daemons parameter is True, it will also
  stop the master daemons (ganet-masterd and ganeti-rapi).

  """
  master_netdev, master_ip = _GetMasterInfo()
  if not master_netdev:
    return False

  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
                         "dev", master_netdev])
  if result.failed:
    logging.error("Can't remove the master IP, error: %s", result.output)
    # but otherwise ignore the failure

  if stop_daemons:
    # stop/kill the rapi and the master daemon
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))

  return True


def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
  """Joins this node to the cluster.

  This does the following:
      - updates the hostkeys of the machine (rsa and dsa)
      - adds the ssh private key to the user
      - adds the ssh public key to the users' authorized_keys file

  """
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
  for name, content, mode in sshd_keys:
    utils.WriteFile(name, data=content, mode=mode)

  try:
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
                                                    mkdir=True)
  except errors.OpExecError, err:
    logging.exception("Error while processing user ssh files")
    return False

  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
    utils.WriteFile(name, data=content, mode=0600)

  utils.AddAuthorizedKey(auth_keys, sshpub)

  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])

  return True


def LeaveCluster():
  """Cleans up the current node and prepares it to be removed from the cluster.

  """
  def _CleanDirectory(path):
    if not os.path.isdir(path):
      return
    for rel_name in utils.ListVisibleFiles(path):
      full_name = os.path.join(path, rel_name)
      if os.path.isfile(full_name) and not os.path.islink(full_name):
        utils.RemoveFile(full_name)

  _CleanDirectory(constants.DATA_DIR)

  # Remove job queue files and archived jobs
  _CleanDirectory(constants.QUEUE_DIR)
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)

{'fraction_non_alphanumeric': 0.08941473988439307, 'fraction_numerical': 0.008309248554913294, 'mean_word_length': 3.2621247113163974, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3571494', 'n_tokens_mistral': 3516, 'n_tokens_neox': 3378, 'n_words': 1174}