<commit_before>#!/usr/bin/python
# coding=utf-8
# Copyright 2012-2014 MongoDB, Inc.
#
# Licensed 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 logging
import sys
import tempfile
import time
import traceback

from uuid import uuid4

import pymongo

from mongo_orchestration.common import (
    BaseModel, DEFAULT_SUBJECT, DEFAULT_CLIENT_CERT)
from mongo_orchestration.singleton import Singleton
from mongo_orchestration.container import Container
from mongo_orchestration.errors import ReplicaSetError
from mongo_orchestration.servers import Servers

logger = logging.getLogger(__name__)
Servers()


class ReplicaSet(BaseModel):
    """class represents ReplicaSet"""

    _servers = Servers()  # singleton to manage servers instances
    # replica set's default parameters
    default_params = {'arbiterOnly': False, 'hidden': False, 'slaveDelay': 0}

    def __init__(self, rs_params):
        """create replica set according members config
        Args:
            rs_params - replica set configuration
        """
        self.server_map = {}
        self.auth_key = rs_params.get('auth_key', None)
        self.login = rs_params.get('login', '')
        self.auth_source = rs_params.get('authSource', 'admin')
        self.password = rs_params.get('password', '')
        self.admin_added = False
        self.repl_id = rs_params.get('id', None) or str(uuid4())
        self._version = rs_params.get('version')

        self.sslParams = rs_params.get('sslParams', {})
        self.kwargs = {}
        self.restart_required = self.login or self.auth_key
        self.x509_extra_user = False

        if self.sslParams:
            self.kwargs['ssl'] = True
            self.kwargs['ssl_certfile'] = DEFAULT_CLIENT_CERT

        members = rs_params.get('members', {})
        config = {"_id": self.repl_id, "members": [
            self.member_create(member, index)
            for index, member in enumerate(members)
        ]}
        logger.debug("replica config: {config}".format(**locals()))
        if not self.repl_init(config):
            self.cleanup()
            raise ReplicaSetError("Could not create replica set.")

        if not self.waiting_config_state():
            raise ReplicaSetError(
                "Could not actualize replica set configuration.")

        if self.login:
            # If the only authentication mechanism enabled is MONGODB-X509,
            # we'll need to add our own user using SSL certificates we already
            # have. Otherwise, the user of MO would have to copy their own
            # certificates to wherever MO happens to be running so that MO
            # might authenticate.
            for member in members:
                proc_params = member.get('procParams', {})
                set_params = proc_params.get('setParameter', {})
                auth_mechs = set_params.get('authenticationMechanisms', '')
                auth_mechs = auth_mechs.split(',')
                if len(auth_mechs) == 1 and auth_mechs[0] == 'MONGODB-X509':
                    self.x509_extra_user = True
                    break

            self._add_users(self.connection()[self.auth_source])
        if self.restart_required:
            # Restart all the servers with auth flags and ssl.
            for idx, member in enumerate(members):
                server_id = self._servers.host_to_server_id(
                    self.member_id_to_host(idx))
                server = self._servers._storage[server_id]
                server.x509_extra_user = self.x509_extra_user
                server.auth_source = self.auth_source
                server.login = self.login
                server.password = <PASSWORD>.password

                def add_auth(config):
                    if self.auth_key:
                        config['keyFile'] = self.key_file
                    config.update(member.get('procParams', {}))
                    return config

                server.restart(config_callback=add_auth)
            self.restart_required = False

        if not self.waiting_config_state():<commit_msg>Don't set login/password on arbiters.<commit_after>#!/usr/bin/python
# coding=utf-8
# Copyright 2012-2014 MongoDB, Inc.
#
# Licensed 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 logging
import sys
import tempfile
import time
import traceback

from uuid import uuid4

import pymongo

from mongo_orchestration.common import (
    BaseModel, DEFAULT_SUBJECT, DEFAULT_CLIENT_CERT)
from mongo_orchestration.singleton import Singleton
from mongo_orchestration.container import Container
from mongo_orchestration.errors import ReplicaSetError
from mongo_orchestration.servers import Servers

logger = logging.getLogger(__name__)
Servers()


class ReplicaSet(BaseModel):
    """class represents ReplicaSet"""

    _servers = Servers()  # singleton to manage servers instances
    # replica set's default parameters
    default_params = {'arbiterOnly': False, 'hidden': False, 'slaveDelay': 0}

    def __init__(self, rs_params):
        """create replica set according members config
        Args:
            rs_params - replica set configuration
        """
        self.server_map = {}
        self.auth_key = rs_params.get('auth_key', None)
        self.login = rs_params.get('login', '')
        self.auth_source = rs_params.get('authSource', 'admin')
        self.password = rs_params.get('password', '')
        self.admin_added = False
        self.repl_id = rs_params.get('id', None) or str(uuid4())
        self._version = rs_params.get('version')

        self.sslParams = rs_params.get('sslParams', {})
        self.kwargs = {}
        self.restart_required = self.login or self.auth_key
        self.x509_extra_user = False

        if self.sslParams:
            self.kwargs['ssl'] = True
            self.kwargs['ssl_certfile'] = DEFAULT_CLIENT_CERT

        members = rs_params.get('members', {})
        config = {"_id": self.repl_id, "members": [
            self.member_create(member, index)
            for index, member in enumerate(members)
        ]}
        logger.debug("replica config: {config}".format(**locals()))
        if not self.repl_init(config):
            self.cleanup()
            raise ReplicaSetError("Could not create replica set.")

        if not self.waiting_config_state():
            raise ReplicaSetError(
                "Could not actualize replica set configuration.")

        if self.login:
            # If the only authentication mechanism enabled is MONGODB-X509,
            # we'll need to add our own user using SSL certificates we already
            # have. Otherwise, the user of MO would have to copy their own
            # certificates to wherever MO happens to be running so that MO
            # might authenticate.
            for member in members:
                proc_params = member.get('procParams', {})
                set_params = proc_params.get('setParameter', {})
                auth_mechs = set_params.get('authenticationMechanisms', '')
                auth_mechs = auth_mechs.split(',')
                if len(auth_mechs) == 1 and auth_mechs[0] == 'MONGODB-X509':
                    self.x509_extra_user = True
                    break

            self._add_users(self.connection()[self.auth_source])
        if self.restart_required:
            # Restart all the servers with auth flags and ssl.
            for idx, member in enumerate(members):
                server_id = self._servers.host_to_server_id(
                    self.member_id_to_host(idx))
                server = self._servers._storage[server_id]
                # If this is an arbiter, we can't authenticate as the user,
                # so don't set the login/password.
                if not member.get('rsParams', {}).get('arbiterOnly'):
                    server.x509_extra_user = self.x509_extra_user
                    server.auth_source = self.auth_source
                    server.login = self.login
                    server.password = <PASSWORD>

                def add_auth(config):
                    if self.auth_key:
                        config['keyFile'] = self.key_file
                    config.update(member.get('procParams', {}))
                    return config

                server.restart(config_callback=add_auth)
            self.restart_required = False

        if not self.waiting_config_state():
{'fraction_non_alphanumeric': 0.08977930147846583, 'fraction_numerical': 0.00771373473323334, 'mean_word_length': 2.3676046176046177, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6420514', 'n_tokens_mistral': 2595, 'n_tokens_neox': 2487, 'n_words': 717}