Example #1
0
    def create(self):

        # Added special code for windows. Cant do start service and set_auth in same cms execution.

        mode = self.data['MODE']

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.initialize()
            return

        if platform.lower() == 'win32':
            Console.info("Starting mongo without authentication ... ")
            self.start(security=False)
            Console.info("Creating admin user ... ")

            self.set_auth()

            Console.info("Stopping the service ... ")
            self.stop()
        else:
            Console.info("Starting mongo without authentication ... ")
            self.start(security=False)
            Console.info("Creating admin user ... ")
            self.set_auth()
            Console.info("Stopping the service ... ")
            self.stop()
Example #2
0
    def start_if_not_running(self):
        """
        checks if mongo service is running
        :return:
        """

        mode = self.data['MODE']

        if mode == 'docker':

            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()

            result = mongo.ps()

            if 'cloudmesh-mongo' not in result:
                mongo.start()

            return

        if platform.lower() == 'linux':
            if not self.linux_process_is_running():
                self.start()
        elif platform.lower() == 'darwin':
            if not self.mac_process_is_running():
                self.start()
        elif platform.lower() == 'win32':  # Replaced windows with win32
            if not self.win_service_is_running():
                self.start()
        else:
            Console.error(f"platform {platform} not found")
Example #3
0
    def stop(self):
        """
        shutdown the MongoDB server
        linux and darwin have different way to shutdown the server, the common way is kill
        """
        mode = self.data['MODE']
        result = "Result unkown"

        if mode == 'docker':

            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.kill()
            result = "Container is down"

        elif platform.lower() == 'win32':
            '''
            MONGO = f"\"{self.mongo_home}\\bin\mongo\""
            script = f'{MONGO} --eval "db.getSiblingDB(\'admin\').shutdownServer()"'
            p1 = subprocess.Popen(script, shell=True, stdout=subprocess.PIPE,
                                  stderr=STDOUT)
            MONGO_USERNAME = self.data['MONGO_USERNAME']
            MONGO_PASSWORD = self.data['MONGO_PASSWORD']
            shutdown_with_auth1 = f"""{MONGO} -u {MONGO_USERNAME} -p {MONGO_PASSWORD} --eval "db.getSiblingDB(\'admin\').shutdownServer()" """
            # print(shutdown_with_auth1)
            # print(script)
            p2 = subprocess.Popen(shutdown_with_auth1, shell=True,
                                  stdout=subprocess.PIPE, stderr=STDOUT)
            shutdown_with_auth = f"""{MONGO} --eval "db.getSiblingDB(\'admin\').shutdownServer()" """
            # print(shutdown_with_auth)
            # print(script)
            p3 = subprocess.Popen(shutdown_with_auth, shell=True,
                                  stdout=subprocess.PIPE, stderr=STDOUT)
            r1 = p1.stdout.read().decode('utf-8')
            r2 = p2.stdout.read().decode('utf-8')
            if 'server should be down...' in r1 or 'connect failed' in r2:
                result = 'server should be down...'
            else:
                result = 'server is already down...'
            '''
            try:
                result = Shell.run("taskkill /IM mongod.exe /F")
            except Exception as e:
                result = str(e)

        else:
            try:
                pid = Script.run('pgrep mongo')
                script = f'kill -2 {pid}'
                result = Script.run(script)
                result = 'server should be down...'
            except subprocess.CalledProcessError:
                result = 'server is already down...'

        print(result)
Example #4
0
    def ssh(self):

        # Added special code for windows. Cant do start service and set_auth in same cms execution.

        mode = self.data['MODE']

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.ssh()
            return

        Console.error("The command is only supported for docker")
        raise NotImplementedError
Example #5
0
    def exit_if_not_running(self):

        status = False
        mode = self.data['MODE']

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()

            status = mongo.status()

        elif platform.lower() == 'linux':
            status = self.linux_process_is_running()
        elif platform.lower() == 'darwin':
            status = self.mac_process_is_running()
        elif platform.lower() == 'win32':  # Replaced windows with win32
            status = self.win_service_is_running()

        if not status:
            Console.error(f"Cloudmesh mongodb not found")
            sys.exit()
    def set_auth(self):
        """
        add admin account into the MongoDB admin database
        """

        mode = self.data['MODE']

        if mode == 'running':
            return

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.wait()
            mongo.create_admin()
            mongo.kill()
            return

        if platform.lower(
        ) == 'win32':  # don't remove this otherwise init won't work in windows, eval should start with double quote in windows
            self.data['MONGO'] = f"{self.mongo_home}\\bin\mongo"
            script = """ "{MONGO}" --eval "db.getSiblingDB('admin').createUser({{ user:'******',pwd:'{MONGO_PASSWORD}',roles:[{{role:'root',db:'admin'}}]}}) ; db.shutdownServer()" """.format(
                **self.data)
            # print(script)
            try:
                # result = Shell3.run2(script)
                p = subprocess.Popen(script,
                                     shell=True,
                                     stdout=subprocess.PIPE,
                                     stderr=STDOUT)
                result = p.stdout.read().decode('utf-8')
            except Exception as e:
                print(e)
                return

        else:
            script = """mongo --eval 'db.getSiblingDB("admin").createUser({{user:"******",pwd:"{MONGO_PASSWORD}",roles:[{{role:"root",db:"admin"}}]}})'""".format(
                **self.data)
            result = Script.run(script)
        if "Successfully added user" in result:
            Console.ok("Administrative user created.")
        elif "already exists" in result:
            Console.error('admin user already exists.')
        else:
            Console.error("Problem creating the administrative user. Check "
                          "the yaml file and make sure the password and "
                          "username are not TBD.")
Example #7
0
    def status(self):
        """
        check the MongoDB status
        returns a json object with status: and pid: command
        """

        mode = self.data['MODE']

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            state = mongo.status()

        if platform.lower() == 'win32':
            script = """
            tasklist /FO LIST /FI "IMAGENAME eq mongod.exe"
            """
            output = Script.run(script)
            if 'INFO: No tasks are running which match the specified criteria.' in output:
                result = None
            else:
                result = {}
                for row in output.split('\n'):
                    if ': ' in row:
                        key, value = row.split(': ')
                        result[key.strip()] = value.strip()

            if result is None:
                state = dotdict({
                    "status": "error",
                    "message": "No mongod running",
                    "output": None
                })
            else:
                state = dotdict({
                    "status": "ok",
                    "message": "running",
                    "output": None
                })
                process = {
                    "pid": str(result['PID']),
                    "command": result['Image Name']
                }
                output = {}
                #
                # TODO: there was a bug here, please check, it was only str()
                #
                output[str(result['PID'])] = process
                state["output"] = output

        else:
            result = find_process("mongod")
            if result is None:
                state = dotdict({
                    "status": "error",
                    "message": "No mongod running",
                    "output": None
                })
                output = None
            else:
                state = dotdict({
                    "status": "ok",
                    "message": "running",
                    "output": None
                })
                output = {}
                for p in result:
                    p = dotdict(p)
                    process = {"pid": str(p.pid), "command": p.command}
                    output[str(p.pid)] = process
                state["output"] = output
        return state
Example #8
0
    def install(self, sudo=True):
        """
        check where the MongoDB is installed in mongo location.
        if MongoDB is not installed, python help install it
        """
        if self.dryrun:
            print(self.mongo_path)
        # pprint(self.data)

        mode = self.data['MODE']

        Console.msg(f"Installing mongo in  mode: {mode}")

        if mode == 'docker':
            Console.ok(
                "Installing mongoDB in a docker container cloudmesh-mongo")

            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.kill()
            mongo.install(clean=True, pull=True)

            Console.ok("Shutting mongoDB down")
            Console.msg("")
            Console.ok("Start the mongodb service with")
            Console.msg("")
            Console.msg("   cms admin mongo create")
            Console.msg("   cms admin mongo start")
            Console.msg("")

            return ""

        if not self.data["MONGO_AUTOINSTALL"]:
            Console.error("Mongo auto install is off")
            print("You can set it with")
            print()
            Console.ok(
                "    cms config set cloudmesh.data.mongo.MONGO_AUTOINSTALL=True"
            )
            print()
            if self.machine == 'darwin':
                print("To install it with brew you need to set also")
                print()
                Console.ok(
                    "    cms config set cloudmesh.data.mongo.MONGO_BREWINSTALL=True"
                )
                print()

            return ""

        #
        # the path test may be wrong as we need to test for mongo and mongod
        #
        # print ('OOO', os.path.isdir(path), self.data["MONGO_AUTOINSTALL"] )
        if self.force or (not os.path.isdir(self.mongo_home)
                          and self.data["MONGO_AUTOINSTALL"]):
            print(f"MongoDB is not installed in {self.mongo_home}")
            #
            # ask if you like to install and give info where it is being installed
            #
            # use cloudmesh yes no question see cloudmesh 3
            #
            # print(f"Auto-install the MongoDB into {mongo_path}")

            self.local = self.data["LOCAL"]
            if self.machine == 'linux':
                self.linux()
            elif self.machine == 'darwin':
                self.darwin()
            elif self.machine == 'win32':  # Replaced windows with win32
                self.windows()
            else:
                print("platform not found", platform)
        elif os.path.isdir(self.mongo_home):
            Console.error(f"Folder {self.mongo_home} already exists")
Example #9
0
    def start(self, security=True):
        """
        start the MongoDB server
        """
        mode = self.data['MODE']
        if mode == "running":
            return

        if mode == 'docker':
            from cloudmesh.mongo.MongoDocker import MongoDocker
            mongo = MongoDocker()
            mongo.start(auth=security)
            # mongo.wait()
            # mongo.ps()
            return

        auth = ""
        if security:
            auth = "--auth"
        mongo_host = self.data['MONGO_HOST']
        if platform.lower() == 'win32':
            try:
                # command = 'where mongo'
                # proc = subprocess.Popen(command, shell=True,
                #                        stdin=subprocess.PIPE,
                #                        stdout=subprocess.PIPE)
                # out, err = proc.communicate()

                # print ("MMM", command)
                # print ("O", out)
                # print ("E", err)

                # if out == b'':
                #    Console.error("mongo command not found")
                #    sys.exit()

                mongo_runner = f"mongod {auth} " \
                               f"--bind_ip {mongo_host}" \
                               f" --dbpath \"{self.mongo_path}\" --logpath \"{self.mongo_log}\mongod.log\""

                #mongo_runner = f"\"{self.mongo_home}\\bin\mongod\" {auth} " \
                #               f"--bind_ip {mongo_host}" \
                #               f" --dbpath \"{self.mongo_path}\" --logpath \"{self.mongo_log}\mongod.log\""

                print(mongo_runner)

                if not os.path.isfile(f'{self.mongo_path}\\invisible.vbs'):
                    with open(f'{self.mongo_path}\\invisible.vbs', 'w') as f:
                        f.write(
                            'CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False'
                        )
                if not os.path.isfile(f'{self.mongo_path}\\mongo_starter.bat'):
                    with open(f'{self.mongo_path}\\mongo_starter.bat',
                              'w') as f:
                        f.write(mongo_runner)
                script = f'wscript.exe "{self.mongo_path}\\invisible.vbs" "{self.mongo_path}\\mongo_starter.bat"'

                print(script)
                p = subprocess.Popen(script,
                                     shell=True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
                result = "mongod child process should be started successfully."
            except Exception as e:
                result = "Mongo in windows could not be started: \n\n" + str(e)
        else:
            try:
                script = f"mongod {auth} --bind_ip {mongo_host}" \
                         f" --dbpath {self.mongo_path} --logpath {self.mongo_log}/mongod.log --fork"
                result = Script.run(script)

            except Exception as e:
                result = "Mongo could not be started." + str(e)

        if "successfully" in result:
            print(Console.ok(result))
        else:
            print(Console.error(result))