Ejemplo n.º 1
0
	def EnqueueCommand(self, type, param):
		if self._commandQueue == None:
			return
		c = Command()
		c.Type = type
		c.Param = param
		# If this is Abort command -- we clean up all the queue (all old commands that still waiting
		# for processing) and add this Abort command, since it is a top priority command.
		if c.Type == CommandType.Abort:
			Monitor.Enter(self._commandQueue)
			try:
				self._commandQueue.Clear()
				self._commandQueue.Enqueue(c)
			finally:
				Monitor.Exit(self._commandQueue)
			return 
		# We check for old same command and use it instead of adding new one -- for optimization.
		# This way we make not more than only one command of same type to be in the queue.
		Monitor.Enter(self._commandQueue)
		try:
			for n in self._commandQueue:
				if n.Type == c.Type:
					n.Param = c.Param
					return 
		finally:
			Monitor.Exit(self._commandQueue)
		# We add new command to queue.
		Monitor.Enter(self._commandQueue)
		try:
			self._commandQueue.Enqueue(c)
		finally:
			Monitor.Exit(self._commandQueue)
Ejemplo n.º 2
0
 def execute(self, State):
     #init the variables.
     self.init(State)
     if self.logflag == True:
         self.logger.log(self.info)
     pass
         
     # 1.connect to Linux machine
     self = Command.getClient(self)
     if self.stat == self.FAILED:
         return self.FAILED
     
     # 2.clear system caches
     command = "echo 3 > /proc/sys/vm/drop_caches"
     result = Command.executeSsh(command, self.client)
     if result != "":
         self.stat = self.FAILED
         self.info ="clear system cache failed." +result+command
         if self.logflag == True:
             self.logger.log(self.info)
         Command.restoreFiles(self,smpath)
         return self.FAILED
     else:
         self.stat = self.PASS
         self.info = "clear system cache successfully."
         if self.logflag == True:
             self.logger.log(task.info)
         return self.PASS
Ejemplo n.º 3
0
    def checkServerStatus(self):
        buildpath = Command.checkPath(self.buildInstallPath)+self.buildno+"/"+self.buildversion+"/BIN/"+self.OS+"/bin/"   
        cmd = buildpath + "mstrctl -s IntelligenceServer gs"
        result = Command.executeSsh(cmd, self.client)
        serverStatus = re.search(r">\w+<\/state>", result)
        strStatus = serverStatus.group(0)

        return strStatus[1:-8]
Ejemplo n.º 4
0
    def execute(self,State):
        """
        install linux build
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)

        # 1.connect to Linux machine
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED
        
        #2. get official build path
        copyToPath = Command.checkPath(self.buildLocation)+self.buildNo+"/"+self.buildVersion+"/BIN/"
        print "version:"+self.buildVersion
        print "copyto path:" +copyToPath
        targetPath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/"     
        
        #3. check if copytopath and installpath exist
        if Command.checkPathExist(copyToPath,self.client) == False:
            self.stat = self.FAILED
            self.info = "can not open build folder, the test build may not be ready"
            if self.logflag == True:
                self.logger.log(self.info)
            return self.FAILED
        
        if Command.checkPathExist(self.buildInstallPath,self.client) == False:
            self.stat = self.FAILED
            self.info = "can not open build folder, please provide the right install path"
            if self.logflag == True:
                self.logger.log(self.info)
            return self.FAILED
        
        #4. Check if there are enough disk
        self = Command.getUnixOS(self) 
        buildsize = Command.getFolderSize(self.client,copyToPath+self.OS);
        diskspace = Command.getDiskSpace(self.client,self.buildInstallPath) 
        if int(diskspace) < int(buildsize):
            self.stat = self.FAILED
            self.info = "there is not enough disk space to install build, please clean the disk space"
            if self.logflag == True:
                self.logger.log(self.info)
            return self.FAILED
        
        #2. install build.
        cmd = "perl "+copyToPath+"copyto.pl "+targetPath
        result = Command.executeSsh(cmd, self.client)
        if result.lower().find("command not found") != -1:
            self.stat = self.FAILED
            self.info = "target build not found, please check if the build ready is ready"
            if self.logflag == True:
                self.logger.log(self.info)
            return self.FAILED
        else:
            self.stat = self.PASS
            self.info ="build install success: "+targetPath
            if self.logflag == True:
                self.logger.log(self.info)
            return self.PASS
Ejemplo n.º 5
0
 def stopServer(self):
     """
     stop iserver
     """
     buildpath = Command.checkPath(self.buildInstallPath)+self.buildno+"/"+self.buildversion+"/BIN/"+self.OS+"/bin/"   
     cmd = buildpath + "mstrctl -s IntelligenceServer stop"
     result = Command.executeSsh(cmd, self.client)
     #operation not permitted. need check user privilege
     if "Error" in result:
         self.info = "Error in stopServer. StopServerTask failed."
         self.stat = self.FAILED
     pass
Ejemplo n.º 6
0
 def __init__(self, id, name):
     self.riskCards = []
     self.freeArmies = 0
     self.id = id
     self.name = name
     self.hasMoved = False
     self.commandBuilder = Command.CommandBuilder()
Ejemplo n.º 7
0
    def generate(self, system, rom, playersControllers):
        # Find rom path
        if os.path.isdir(rom):
            # rom is a directory: must contains a <game name>.residualvm file
            romPath = rom
            romFile = glob.glob(romPath + "/*.residualvm")[0]
            romName = os.path.splitext(os.path.basename(romFile))[0]
        else:
            # rom is a file: split in directory and file name
            romPath = os.path.dirname(rom)
            romName = os.path.splitext(os.path.basename(rom))[0]
        commandArray = [
            rhgamestationFiles.rhgamestationBins[system.config['emulator']],
            "--fullscreen",
            "--joystick=0",
            #                       "--screenshotpath="+rhgamestationFiles.screenshotsDir,
            "--extrapath=/usr/share/residualvm",
            "--savepath=" + rhgamestationFiles.residualvmSaves,
            "--path="
            "{}"
            "".format(romPath)
        ]
        if 'args' in system.config and system.config['args'] is not None:
            commandArray.extend(system.config['args'])
        commandArray.append("""{}""".format(romName))

        return Command.Command(videomode='default',
                               array=commandArray,
                               env={
                                   "SDL_VIDEO_GL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "SDL_VIDEO_EGL_DRIVER":
                                   "/usr/lib/libGLESv2.so"
                               })
Ejemplo n.º 8
0
    def generate(self, system, rom, playersControllers, gameResolution):

        # Read the configuration file
        iniConfig = configparser.ConfigParser(interpolation=None)
        # To prevent ConfigParser from converting to lower case
        iniConfig.optionxform = str
        if os.path.exists(batoceraFiles.mupenCustom):
            iniConfig.read(batoceraFiles.mupenCustom)
        else:
            if not os.path.exists(os.path.dirname(batoceraFiles.mupenCustom)):
                os.makedirs(os.path.dirname(batoceraFiles.mupenCustom))
            iniConfig.read(batoceraFiles.mupenCustom)

        mupenConfig.setMupenConfig(iniConfig, system, playersControllers, gameResolution)
        mupenControllers.setControllersConfig(iniConfig, playersControllers, system.config)

        # Save the ini file
        if not os.path.exists(os.path.dirname(batoceraFiles.mupenCustom)):
            os.makedirs(os.path.dirname(batoceraFiles.mupenCustom))
        with open(batoceraFiles.mupenCustom, 'w') as configfile:
            iniConfig.write(configfile)

        # Command
        commandArray = [batoceraFiles.batoceraBins[system.config['emulator']], "--corelib", "/usr/lib/libmupen64plus.so.2.0.0", "--gfx", "/usr/lib/mupen64plus/mupen64plus-video-{}.so".format(system.config['core']), "--configdir", batoceraFiles.mupenConf, "--datadir", batoceraFiles.mupenConf]

        # state_slot option
        if system.isOptSet('state_filename'):
            commandArray.extend(["--savestate", "/userdata/saves/n64/{}".format(system.config['state_filename'])])

        commandArray.append(rom)

        return Command.Command(array=commandArray)
Ejemplo n.º 9
0
    def generate(self, system, rom, playersControllers, gameResolution):
        commandArray = ["SDLPoP"]

        # create sdlpop config directory
        if not os.path.exists(batoceraFiles.sdlpopConfigDir):
            os.makedirs(batoceraFiles.sdlpopConfigDir)
        if not os.path.exists(batoceraFiles.sdlpopSrcCfg):
            shutil.copyfile('/usr/share/sdlpop/cfg/SDLPoP.cfg', batoceraFiles.sdlpopSrcCfg)
        if not os.path.exists(batoceraFiles.sdlpopSrcIni):
            shutil.copyfile('/usr/share/sdlpop/cfg/SDLPoP.ini', batoceraFiles.sdlpopSrcIni)       
        # symbolic link cfg files
        if not os.path.exists(batoceraFiles.sdlpopDestCfg):
            os.symlink(batoceraFiles.sdlpopSrcCfg, batoceraFiles.sdlpopDestCfg)
        if not os.path.exists(batoceraFiles.sdlpopDestIni):
            os.symlink(batoceraFiles.sdlpopSrcIni, batoceraFiles.sdlpopDestIni)
        # symbolic link screenshot folder too
        if not os.path.exists('/userdata/screenshots/sdlpop'):
            os.makedirs('/userdata/screenshots/sdlpop')
            os.symlink('/userdata/screenshots/sdlpop', '/usr/share/sdlpop/screenshots', target_is_directory = True)
        
        # pad number
        nplayer = 1
        for playercontroller, pad in sorted(playersControllers.items()):
            if nplayer == 1:
                commandArray.append("joynum={}".format(pad.index))
            nplayer += 1

        return Command.Command(
            array=commandArray,
            env={
                'SDL_GAMECONTROLLERCONFIG': controllersConfig.generateSdlGameControllerConfig(playersControllers)
        })
Ejemplo n.º 10
0
    def generate(self, system, rom, playersControllers, gameResolution):
        commandArray = ["doomretro"]

        if (rom.__contains__(".uwad")):
            f = open(rom)
            content = f.readlines()
            for line in content:
                if 'IWAD=/' in line:
                    commandArray.append("-iwad")
                    commandArray.append(
                        line.replace("IWAD=", "").replace("\n", ""))
                elif 'PWAD=/' in line:
                    commandArray.append("-file")
                    commandArray.append(
                        line.replace("PWAD=", "").replace("\n", ""))

        else:
            commandArray.append("-iwad")
            commandArray.append(rom)

        return Command.Command(
            array=commandArray,
            env={
                'SDL_GAMECONTROLLERCONFIG':
                controllersConfig.generateSdlGameControllerConfig(
                    playersControllers)
            })
    def generate(self, system, rom, playersControllers):
        # Settings rhgamestation default config file if no user defined one
        if not system.config['configfile']:
            # Using rhgamestation config file
            system.config['configfile'] = rhgamestationFiles.mupenCustom
            # Write configuration file
            mupenConfig.writeMupenConfig(system, playersControllers, rom)
            #  Write controllers configuration files
            mupenControllers.writeControllersConfig(playersControllers)

        commandArray = [
            rhgamestationFiles.rhgamestationBins[system.config['emulator']],
            "--corelib", "/usr/lib/libmupen64plus.so.2.0.0", "--gfx",
            "/usr/lib/mupen64plus/mupen64plus-video-{}.so".format(
                system.config['core']), "--configdir",
            rhgamestationFiles.mupenConf, "--datadir",
            rhgamestationFiles.mupenConf
        ]
        if 'args' in system.config and system.config['args'] is not None:
            commandArray.extend(system.config['args'])
        commandArray.append(rom)

        return Command.Command(
            videomode=system.config['videomode'],
            array=commandArray,
            env={"SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"})
Ejemplo n.º 12
0
    def generate(self, system, rom, playersControllers, gameResolution):
        commandArray = [
            "quakespasm", "-basedir", "/userdata/roms/tyrquake", "-sndspeed",
            "44100"
        ]

        if (rom.lower().__contains__("hipnotic")):
            commandArray = [
                "quakespasm", "-basedir", "/userdata/roms/tyrquake",
                "-sndspeed", "44100", "-hipnotic"
            ]

        if (rom.lower().__contains__("rogue")):
            commandArray = [
                "quakespasm", "-basedir", "/userdata/roms/tyrquake",
                "-sndspeed", "44100", "-rogue"
            ]

        if (rom.lower().__contains__("dopa")):
            commandArray = [
                "quakespasm", "-basedir", "/userdata/roms/tyrquake",
                "-sndspeed", "44100", "-game", "dopa"
            ]

        return Command.Command(
            array=commandArray,
            env={
                'SDL_GAMECONTROLLERCONFIG':
                controllersConfig.generateSdlGameControllerConfig(
                    playersControllers)
            })
Ejemplo n.º 13
0
    def generate(self, system, rom, playersControllers, gameResolution):

        # read the configuration file
        iniConfig = ConfigParser.ConfigParser()
        # To prevent ConfigParser from converting to lower case
        iniConfig.optionxform = str
        if os.path.exists(batoceraFiles.mupenCustom):
            iniConfig.read(batoceraFiles.mupenCustom)

        mupenConfig.setMupenConfig(iniConfig, system, playersControllers,
                                   gameResolution)
        mupenControllers.setControllersConfig(iniConfig, playersControllers,
                                              system.config)

        # save the ini file
        if not os.path.exists(os.path.dirname(batoceraFiles.mupenCustom)):
            os.makedirs(os.path.dirname(batoceraFiles.mupenCustom))
        with open(batoceraFiles.mupenCustom, 'w') as configfile:
            iniConfig.write(configfile)

        # command
        commandArray = [
            batoceraFiles.batoceraBins[system.config['emulator']], "--corelib",
            "/usr/lib/libmupen64plus.so.2.0.0", "--gfx",
            "/usr/lib/mupen64plus/mupen64plus-video-{}.so".format(
                system.config['core']), "--configdir", batoceraFiles.mupenConf,
            "--datadir", batoceraFiles.mupenConf
        ]
        commandArray.append(rom)

        return Command.Command(
            array=commandArray,
            env={"SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"})
Ejemplo n.º 14
0
    def generate(self, system, rom, playersControllers, gameResolution):
        commandArray = ["easyrpg-player"]

        # FPS
        if system.isOptSet("showFPS") and system.getOptBoolean("showFPS"):
            commandArray.append("--show-fps")

        # Test Play (Debug Mode)
        if system.isOptSet('testplay') and system.getOptBoolean("testplay"):
            commandArray.append("--test-play")

        # Game Region (Encoding)
        if system.isOptSet('encoding') and system.config["encoding"] != 'autodetect':
            commandArray.extend(["--encoding", system.config["encoding"]])
        else:
            commandArray.extend(["--encoding", "auto"])

        # Save directory
        savePath = "/userdata/saves/easyrpg/{}".format(os.path.basename(rom))
        if not os.path.exists(savePath):
            os.makedirs(savePath)
        commandArray.extend(["--save-path", savePath])

        # Dir for logs and conf
        configdir = "/userdata/system/configs/easyrpg"
        if not os.path.exists(configdir):
            os.makedirs(configdir)

        commandArray.extend(["--project-path", rom])

        EasyRPGGenerator.padConfig(configdir, playersControllers)

        return Command.Command(array=commandArray)
Ejemplo n.º 15
0
    def generate(self, system, rom, playersControllers, gameResolution):
        if not path.isdir(batoceraFiles.BIOS + "/cemu"):
            os.mkdir(batoceraFiles.BIOS + "/cemu")
        if not path.isdir(batoceraFiles.CONF + "/cemu"):
            os.mkdir(batoceraFiles.CONF + "/cemu")

        for folder in ["shaderCache", "controllerProfiles", "gameProfiles", "graphicPacks"]:
            if not path.isdir(batoceraFiles.CONF + "/cemu/" + folder):
                os.mkdir(batoceraFiles.CONF + "/cemu/" + folder)

        if not path.isdir(batoceraFiles.SAVES + "/cemu"):
            os.mkdir(batoceraFiles.SAVES + "/cemu")

        CemuGenerator.CemuConfig(batoceraFiles.CONF + "/cemu/settings.xml", system)
        # copy the file from where cemu reads it
        copyfile(batoceraFiles.CONF + "/cemu/settings.xml", "/usr/cemu/settings.xml")

        cemuControllers.generateControllerConfig(system, playersControllers, rom)

        commandArray = ["/usr/wine/lutris/bin/wine64", "/usr/cemu/Cemu.exe", "-g", "z:" + rom, "-m", "z:" + batoceraFiles.SAVES + "/cemu", "-f"]
        return Command.Command(
            array=commandArray,
            env={
                "WINEPREFIX": batoceraFiles.SAVES + "/cemu",
                "vblank_mode": "0",
                "mesa_glthread": "true",
                "SDL_GAMECONTROLLERCONFIG": controllersConfig.generateSdlGameControllerConfig(playersControllers),
                "WINEDLLOVERRIDES": "mscoree=;mshtml=;dbghelp.dll=n,b",
                "__GL_THREADED_OPTIMIZATIONS": "1"
            })
Ejemplo n.º 16
0
        def createScheduleDataStructure(scheduleJson: json) -> list:
            """
            reads the JSON string of schedule into a data structure (list of dictionaries). 
            
            Arguments:
            ----------
                (1) JSON string of the schedule
            
            Returns:
            --------
                The list of dictionaries. Each dictionary contains an individiual command.
            """

            scheduleDataStructure = []
            for command in scheduleJson:
                if command["commandType"] == "call_veh":
                    commandType = Command.CALL_VEH_PHASES
                elif command["commandType"] == "call_ped":
                    commandType = Command.CALL_PED_PHASES
                elif command["commandType"] == "forceoff":
                    commandType = Command.FORCEOFF_PHASES
                elif command["commandType"] == "hold":
                    commandType = Command.HOLD_VEH_PHASES
                elif command["commandType"] == "omit_veh":
                    commandType = Command.OMIT_VEH_PHASES
                elif command["commandType"] == "omit_ped":
                    commandType = Command.OMIT_PED_PHASES

                commandObject = Command.Command(command["commandPhase"],
                                                commandType,
                                                command["commandStartTime"],
                                                command["commandEndTime"])
                scheduleDataStructure = scheduleDataStructure + [commandObject]

            return scheduleDataStructure
Ejemplo n.º 17
0
    def generate(self, system, rom, playersControllers, gameResolution):

        settings = ConfigParser.ConfigParser()
        # To prevent ConfigParser from converting to lower case
        settings.optionxform = str
        settings_path = rom + "/data/mugen.cfg"
        if os.path.exists(settings_path):
            MugenGenerator.cleanMugenCfg(settings_path)
            settings.read(settings_path)

        if not settings.has_section("Video"):
            settings.add_section("Video")
        settings.set("Video", "FullScreen", "1")
        settings.set("Video", "Width",  gameResolution["width"])
        settings.set("Video", "Height", gameResolution["height"])

        if not settings.has_section("Config"):
            settings.add_section("Config")
        settings.set("Config", "GameWidth",  gameResolution["width"])
        settings.set("Config", "GameHeight", gameResolution["height"])
        settings.set("Config", "Language", "en")

        # Save config
        if not os.path.exists(os.path.dirname(settings_path)):
            os.makedirs(os.path.dirname(settings_path))

        with open(settings_path, 'w') as configfile:
            settings.write(configfile)

        commandArray = ["batocera-wine", "mugen", "play", rom]
        return Command.Command(array=commandArray, env={ "SDL_GAMECONTROLLERCONFIG": controllersConfig.generateSdlGameControllerConfig(playersControllers) })
Ejemplo n.º 18
0
    def generate(self, system, rom, playersControllers, gameResolution):
        if not os.path.exists(os.path.dirname(batoceraFiles.daphneConfig)):
            os.makedirs(os.path.dirname(batoceraFiles.daphneConfig))

        # controllers
        daphneControllers.generateControllerConfig(batoceraFiles.daphneConfig, playersControllers)

        # extension used .daphne and the file to start the game is in the folder .daphne with the extension .txt
        romName = os.path.splitext(os.path.basename(rom))[0]
        frameFile = rom + "/" + romName + ".txt"
        commandsFile = rom + "/" + romName + ".commands"
        
        if system.config["ratio"] == "16/9":
            commandArray = [batoceraFiles.batoceraBins[system.config['emulator']],
                            romName, "vldp", "-framefile", frameFile, "-useoverlaysb", "2", "-ignore_aspect_ratio",
                            "-x", str(gameResolution["width"]), "-y", str(gameResolution["height"]), "-fullscreen",
                            "-fastboot", "-datadir", batoceraFiles.daphneDatadir, "-homedir", batoceraFiles.daphneHomedir]
        else:
            commandArray = [batoceraFiles.batoceraBins[system.config['emulator']],
                            romName, "vldp", "-framefile", frameFile, "-useoverlaysb", "2", "-fullscreen",
                            "-fastboot", "-datadir", batoceraFiles.daphneDatadir, "-homedir", batoceraFiles.daphneHomedir]

        # The folder may have a file with the game name and .commands with extra arguments to run the game.
        if os.path.isfile(commandsFile):
            commandArray.extend(open(commandsFile,'r').read().split())
        
        return Command.Command(array=commandArray)
Ejemplo n.º 19
0
    def send_request(self,
                     command,
                     key,
                     value_length,
                     value,
                     timeout=.1,
                     retrials=2):  # by default retrials 2
        fmt = self.fmtRequest

        if command == Command.PUT or command == Command.PUBLISH or command == Command.SUBSCRIBE:
            fmt += "H" + str(value_length) + 's'

            msg = struct.pack(fmt, command, key, value_length, value)
        else:  # other commands like get
            msg = struct.pack(fmt, command, key)

        #  Get the IP Port from the key
        ip_port = NodeList.look_up_node_id(hash(key) % self.numberOfNodes)

        port = ip_port.split(':')[1]
        self.RequestReplyClient_obj = RequestReplyClient.RequestReplyClient(
            ip_port.split(':')[0], port, msg, timeout, retrials)

        self.RequestReplyClient_obj.send()
        Print.print_("send_request$ command:" + Command.print_command(command) \
                     + ", key: " + key \
                     + ", value_length: " \
                     + str(value_length) \
                     + ", value: " + str(value) \
                     , self.hashedKeyModN)
Ejemplo n.º 20
0
def socket_java(str,type='bestconfig'):
    ziplist = ['none', 'gzip', 'snappy', 'lz4']
    param = json.loads(str)
    # param = json.loads('{"socket.request.max.bytes":6.690755,"compression.type":0.871446,"performance":null,'
    #                    '"num.network.threads":19.055355,"num.io.threads":12.78569,"socket.receive.buffer.bytes":8.650538,'
    #                    '"batch.size":21.0,"queued.max.requests":4.0,"num.replica.fetchers":2.082252,"buffer.memory":44.0,'
    #                    '"socket.send.buffer.bytes":8.855171,"linger.ms":17.0}')
    p = []
    p.append(math.floor(param['num.network.threads']))
    p.append(math.floor(param['num.io.threads']))
    p.append(math.floor(param['queued.max.requests']))
    p.append(math.floor(param['num.replica.fetchers']))
    p.append(math.floor(param['socket.receive.buffer.bytes']))
    p.append(math.floor(param['socket.send.buffer.bytes']))
    p.append(math.floor(param['socket.request.max.bytes']))
    p.append(math.floor(param['buffer.memory']))
    p.append(math.floor(param['batch.size']))
    p.append(math.floor(param['linger.ms']))
    if type =='bestconfig':
        p.append(ziplist[math.floor(param['compression.type'] * 4)])
    else:#oals
        p.append(param['compression.type'])
    p.append(1)
    print(p)
    return Command.getThrought(p)
Ejemplo n.º 21
0
    def test_func_to_dict_for_good_case_no_deps(self):
        """ Test for making a dict for good case no dependencies. """

        # Make command
        str_command = "This is a command"
        str_path_one = os.path.join(os.path.sep + "This", "is", "a", "path1")
        str_path_two = os.path.join(os.path.sep + "This", "is", "a", "path2")
        str_path_three = os.path.join(os.path.sep + "This", "is", "a", "path3")
        str_path_four = os.path.join(os.path.sep + "This", "is", "a", "path4")
        str_path_five = os.path.join(os.path.sep + "This", "is", "a", "path5")
        str_path_six = os.path.join(os.path.sep + "This", "is", "a", "path6")
        str_path_seven = os.path.join(os.path.sep + "This", "is", "a", "path7")
        str_path_eight = os.path.join(os.path.sep + "This", "is", "a", "path8")

        # Answer
        str_answer = "".join([
            "{COMMAND : ", str_command, ",MAKES:[u'{CLEAN:TEMP,PATH:",
            str_path_two, "}', u'{CLEAN:TEMP,PATH:", str_path_four, "}']}"
        ])

        # Make command
        lstr_prods = [str_path_two, str_path_four]
        cmd_test = Command.Command(str_command, [], lstr_prods)

        cmd_test.func_set_resource_clean_level(str_path_one,
                                               Resource.CLEAN_NEVER)
        cmd_test.func_set_resource_clean_level([str_path_three, str_path_five],
                                               Resource.CLEAN_AS_TEMP)
        cmd_test.func_set_resource_clean_level([str_path_six],
                                               Resource.CLEAN_ALWAYS)
        str_result = self.func_command_dict_to_string(cmd_test.func_to_dict())
        self.func_test_equals(str_answer, str_result)
Ejemplo n.º 22
0
 def generate(self, system, rom, playersControllers, gameResolution):
     commandArray = ["vanillara"]
     return Command.Command(
         array=commandArray,
         env={
             'SDL_AUTO_UPDATE_JOYSTICKS': '0'
         })
Ejemplo n.º 23
0
    def generate(self, system, rom, playersControllers, gameResolution):
        if not path.isdir(batoceraFiles.BIOS + "/cemu"):
            os.mkdir(batoceraFiles.BIOS + "/cemu")
        if not path.isdir(batoceraFiles.CONF + "/cemu"):
            os.mkdir(batoceraFiles.CONF + "/cemu")

        for folder in [
                "shaderCache", "controllerProfiles", "gameProfiles",
                "graphicPacks"
        ]:
            if not path.isdir(batoceraFiles.CONF + "/cemu/" + folder):
                os.mkdir(batoceraFiles.CONF + "/cemu/" + folder)

        if not path.isdir(batoceraFiles.SAVES + "/cemu"):
            os.mkdir(batoceraFiles.SAVES + "/cemu")

        CemuGenerator.CemuConfig(batoceraFiles.CONF + "/cemu/settings.xml")
        # TODO
        #CemuGenerator.CemuConfig("/usr/cemu/settings.xml")

        sdlstring = cemuControllers.generateControllerConfig(
            system, playersControllers, rom)

        commandArray = [
            "wine64", "/usr/cemu/Cemu.exe", "-g", "z:" + rom, "-m",
            "z:" + batoceraFiles.SAVES + "/cemu", "-f"
        ]
        return Command.Command(array=commandArray,
                               env={
                                   "WINEPREFIX": batoceraFiles.SAVES + "/cemu",
                                   "vblank_mode": "0",
                                   "mesa_glthread": "true",
                                   "SDL_GAMECONTROLLERCONFIG": sdlstring
                               })
Ejemplo n.º 24
0
    def generate(self, system, rom, controllers):
        if not system.config['configfile']:
            daphneControllers.generateControllerConfig(system, controllers)

        romName = os.path.splitext(os.path.basename(rom))[0]
        frameFile = rom + "/" + romName + ".txt"
        commandsFile = rom + "/" + romName + ".commands"
        # the command to run
        commandArray = [
            rhgamestationFiles.rhgamestationBins[system.config['emulator']],
            romName, "vldp", "-framefile", frameFile, "-fullscreen",
            "-useoverlaysb", "2", "-datadir", rhgamestationFiles.daphneDatadir,
            "-homedir", rhgamestationFiles.daphneHomedir
        ]
        if 'args' in system.config and system.config['args'] is not None:
            commandArray.extend(system.config['args'])
        if os.path.isfile(commandsFile):
            commandArray.extend(open(commandsFile, 'r').read().split())
        return Command.Command(videomode=system.config['videomode'],
                               array=commandArray,
                               env={
                                   "SDL_VIDEO_GL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "SDL_VIDEO_EGL_DRIVER":
                                   "/usr/lib/libGLESv2.so"
                               })
Ejemplo n.º 25
0
    def generate(self, system, rom, playersControllers, gameResolution):
        ppssppConfig.writePPSSPPConfig(system)
        # For each pad detected
        for index in playersControllers:
            controller = playersControllers[index]
            # we only care about player 1
            if controller.player != "1":
                continue
            ppssppControllers.generateControllerConfig(controller)
            # TODO: python 3 - workawround to encode files in utf-8
            cfgFile = codecs.open(batoceraFiles.ppssppControls, "w", "utf-8")
            cfgFile.write(controller.generateSDLGameDBLine())
            cfgFile.close()
            break

        # the command to run
        commandArray = [batoceraFiles.batoceraBins[system.config['emulator']]]
        commandArray.append(rom)
        commandArray.append("--fullscreen")
        # The next line is a reminder on how to quit PPSSPP with just the HK
        #commandArray = [batoceraFiles.batoceraBins[system.config['emulator']], rom, "--escape-exit"]
        return Command.Command(array=commandArray,
                               env={
                                   "XDG_CONFIG_HOME":
                                   batoceraFiles.CONF,
                                   "SDL_VIDEO_GL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "SDL_VIDEO_EGL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "PPSSPP_GAME_CONTROLLER_DB_PATH":
                                   batoceraFiles.ppssppControls
                               })
Ejemplo n.º 26
0
    def generate(self, system, rom, playersControllers, gameResolution):
        iniConfig = ConfigParser.ConfigParser()
        # To prevent ConfigParser from converting to lower case
        iniConfig.optionxform = str
        if os.path.exists(batoceraFiles.fbaCustom):
            with io.open(batoceraFiles.fbaCustom, 'r',
                         encoding='utf_8_sig') as fp:
                iniConfig.readfp(fp)

        fba2xConfig.updateFBAConfig(iniConfig, system)
        fba2xControllers.updateControllersConfig(iniConfig, system, rom,
                                                 playersControllers)

        # save the ini file
        if not os.path.exists(os.path.dirname(batoceraFiles.fbaCustom)):
            os.makedirs(os.path.dirname(batoceraFiles.fbaCustom))
        with open(batoceraFiles.fbaCustom, 'w') as configfile:
            iniConfig.write(configfile)

        commandArray = [
            batoceraFiles.batoceraBins[system.config['emulator']],
            "--configfile", batoceraFiles.fbaCustom, '--logfile',
            batoceraFiles.logdir + "/fba2x.log"
        ]
        commandArray.append(rom)
        return Command.Command(array=commandArray)
Ejemplo n.º 27
0
    def sendAfter(self, originator, level, msgName, after, *args, **kwargs):        
        import Timer        
        # this is mapped from an M3 SEND statement
        if not Global.raw_python:
            args = [ arg.dupe() for arg in args ]
            for key in kwargs: kwargs[key] = kwargs[key].dupe()
        cmd = Command.ModelMsgCommand(target=self,
                                      msgName=msgName,
                                      source=Command.userSrc,
                                      level=level,
                                      args=args,
                                      kwargs=kwargs)
        #print "SENDING",level
        #import pdb; pdb.set_trace()
        cmdList = cmd.redirect(self)
        DbgStub.ping("send") # this is not right for send after's

        for cmd in cmdList:
            # calculate the link overhead if present
            linkCost = Processors.getLinkCost(self.M3ProcessorName,cmd.target.M3ProcessorName)
            if after or linkCost:
                # divide by performance factor if present, then add link cost
                speed = Processors.getSpeed(self.M3ProcessorName)
                Timer.insertAfter((after / speed) + linkCost, cmd)
            else:
                CommandQueue.insert(cmd)
Ejemplo n.º 28
0
    def test_init_for_two_relative_paths(self):
        """ Testing init for updating 2 relative paths. """

        str_command = "This is a command"
        str_path_one = os.path.join("This", "is", "a", "path1")
        str_path_two = os.path.join("This", "is", "a", "path2")
        str_path_three = os.path.join("This", "is", "a", "path3")
        str_path_four = os.path.join("This", "is", "a", "path4")
        lstr_deps = [str_path_one, str_path_three]
        lstr_prods = [str_path_two, str_path_four]
        lstr_deps_answer = sorted([
            os.path.join(os.getcwd(), str_path_one),
            os.path.join(os.getcwd(), str_path_three)
        ])
        lstr_prods_answer = sorted([
            os.path.join(os.getcwd(), str_path_two),
            os.path.join(os.getcwd(), str_path_four)
        ])
        cmd_test = Command.Command(str_command, lstr_deps, lstr_prods)
        str_result = str(
            sorted([str(str_dep) for str_dep in cmd_test.lstr_dependencies] +
                   [str(str_prod) for str_prod in cmd_test.lstr_products]))
        str_answer = "".join([
            "[\"PATH: " + os.getcwd() + "/This/is/a/path1,",
            " CLEAN: 2, Dependency PARENTS: [] CHILDREN: ['This is a command']\", ",
            "\"PATH: " + os.getcwd() + "/This/is/a/path2, ",
            "CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []\", ",
            "\"PATH: " + os.getcwd() + "/This/is/a/path3, ",
            "CLEAN: 2, Dependency PARENTS: [] CHILDREN: ['This is a command']\", ",
            "\"PATH: " + os.getcwd() + "/This/is/a/path4, ",
            "CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []\"]"
        ])
        self.func_test_equals(str_answer, str_result)
Ejemplo n.º 29
0
    def generate(self, system, rom, playersControllers, gameResolution):
        if not system.config['configfile']:
            ppssppConfig.writePPSSPPConfig(system)
            # For each pad detected
            for index in playersControllers:
                controller = playersControllers[index]
                # we only care about player 1
                if controller.player != "1":
                    continue
                ppssppControllers.generateControllerConfig(controller)
                cfgFile = open(recalboxFiles.ppssppControls, "w")
                cfgFile.write(controller.generateSDLGameDBLine())
                cfgFile.close()
                break

        # the command to run
        commandArray = [recalboxFiles.recalboxBins[system.config['emulator']]]
        if 'args' in system.config and system.config['args'] is not None:
            commandArray.extend(system.config['args'])
        commandArray.append(rom)
        # The next line is a reminder on how to quit PPSSPP with just the HK
        #commandArray = [recalboxFiles.recalboxBins[system.config['emulator']], rom, "--escape-exit"]
        return Command.Command(array=commandArray,
                               env={
                                   "XDG_CONFIG_HOME":
                                   recalboxFiles.CONF,
                                   "SDL_VIDEO_GL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "SDL_VIDEO_EGL_DRIVER":
                                   "/usr/lib/libGLESv2.so",
                                   "PPSSPP_GAME_CONTROLLER_DB_PATH":
                                   recalboxFiles.ppssppControls
                               })
Ejemplo n.º 30
0
    def test_func_get_dependencies_to_clean_level_for_good_case_mult_levels_always(
            self):
        """
        Testing for getting dependencies to a clean level. All clean levels present. Level = Always
        """

        str_command = "This is a command"
        str_path_one = os.path.join("This", "is", "a", "path1")
        str_path_two = os.path.join("This", "is", "a", "path2")
        str_path_three = os.path.join("This", "is", "a", "path3")
        str_path_four = os.path.join("This", "is", "a", "path4")
        str_path_five = os.path.sep + os.path.join("This", "is", "a", "path5")
        str_path_six = os.path.sep + os.path.join("This", "is", "a", "path6")
        lstr_deps = [str_path_one, str_path_three, str_path_five, str_path_six]
        lstr_prods = [str_path_two, str_path_four]
        cmd_test = Command.Command(str_command, lstr_deps, lstr_prods)
        cmd_test.func_set_resource_clean_level(str_path_one,
                                               Resource.CLEAN_NEVER)
        cmd_test.func_set_resource_clean_level([str_path_three, str_path_five],
                                               Resource.CLEAN_AS_TEMP)
        cmd_test.func_set_resource_clean_level([str_path_six],
                                               Resource.CLEAN_ALWAYS)
        lstr_result = cmd_test.func_get_dependencies_to_clean_level(
            Resource.CLEAN_ALWAYS)
        lstr_answer = Resource.Resource.func_make_paths_absolute(
            [str_path_six])
        lstr_result = [rsc_cur.str_id for rsc_cur in lstr_result]
        self.func_test_equals(sorted(lstr_answer), sorted(lstr_result))
Ejemplo n.º 31
0
    def generate(self, system, rom, playersControllers, gameResolution):

        # basis
        commandArray = [
            "solarus-run", "-fullscreen=yes", "-cursor-visible=no",
            "-lua-console=no"
        ]

        # hotkey to exit
        nplayer = 1
        for playercontroller, pad in sorted(playersControllers.items()):
            if nplayer == 1:
                if "hotkey" in pad.inputs and "start" in pad.inputs:
                    commandArray.append("-quit-combo={}+{}".format(
                        pad.inputs["hotkey"].id, pad.inputs["start"].id))
                    commandArray.append("-joypad-num={}".format(pad.index))
            nplayer += 1

        # player pad
        SolarusGenerator.padConfig(system, playersControllers)

        # rom
        commandArray.append(rom)

        return Command.Command(array=commandArray,
                               env={'SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS': '0'})
Ejemplo n.º 32
0
    def test_func_get_dependencies_to_clean_level_for_bad_case_invalid_level_10(
            self):
        """
        Testing for getting dependencies to a clean level. Using invalid level 10
        """

        str_command = "This is a command"
        str_path_one = os.path.join("This", "is", "a", "path1")
        str_path_two = os.path.join("This", "is", "a", "path2")
        str_path_three = os.path.join("This", "is", "a", "path3")
        str_path_four = os.path.join("This", "is", "a", "path4")
        str_path_five = os.path.sep + os.path.join("This", "is", "a", "path5")
        str_path_six = os.path.sep + os.path.join("This", "is", "a", "path6")
        lstr_deps = [str_path_one, str_path_three, str_path_five, str_path_six]
        lstr_prods = [str_path_two, str_path_four]
        cmd_test = Command.Command(str_command, lstr_deps, lstr_prods)
        cmd_test.func_set_resource_clean_level(str_path_one,
                                               Resource.CLEAN_NEVER)
        cmd_test.func_set_resource_clean_level([str_path_three, str_path_five],
                                               Resource.CLEAN_AS_TEMP)
        cmd_test.func_set_resource_clean_level([str_path_six],
                                               Resource.CLEAN_ALWAYS)
        lstr_result = cmd_test.func_get_dependencies_to_clean_level(10)
        lstr_answer = []
        self.func_test_equals(str(lstr_answer), str(lstr_result))
Ejemplo n.º 33
0
    def test_func_set_resource_clean_level_for_good_case_mult_files2(self):
        """ Testing for adding a clean level in a good case with multiple files, both absolute and relative. """

        str_command = "This is a command"
        str_path_one = os.path.join("This", "is", "a", "path1")
        str_path_two = os.path.join("This", "is", "a", "path2")
        str_path_three = os.path.join("This", "is", "a", "path3")
        str_path_four = os.path.join("This", "is", "a", "path4")
        str_path_five = os.path.sep + os.path.join("This", "is", "a", "path5")
        str_path_six = os.path.sep + os.path.join("This", "is", "a", "path6")
        lstr_deps = [str_path_one, str_path_three, str_path_five, str_path_six]
        lstr_prods = [str_path_two, str_path_four]
        cmd_test = Command.Command(str_command, lstr_deps, lstr_prods)
        cmd_test.func_set_resource_clean_level(lstr_deps, Resource.CLEAN_NEVER)
        str_result = cmd_test.func_detail()
        str_answer = "".join([
            "Command: This is a command; ",
            "Dependencies: PATH: /This/is/a/path5, CLEAN: 1, Dependency ",
            "PARENTS: [] CHILDREN: ['This is a command'],PATH: /This/is/a/path6, ",
            "CLEAN: 1, Dependency PARENTS: [] CHILDREN: ['This is a command'],",
            "PATH: " + os.getcwd() + os.path.sep + "This" + os.path.sep +
            "is" + os.path.sep + "a" + os.path.sep + "path1, ",
            "CLEAN: 1, Dependency PARENTS: [] CHILDREN: ['This is a command'],",
            "PATH: " + os.getcwd() + os.path.sep + "This" + os.path.sep +
            "is" + os.path.sep + "a" + os.path.sep + "path3, ",
            "CLEAN: 1, Dependency PARENTS: [] CHILDREN: ['This is a command']; ",
            "Products: PATH: " + os.getcwd() + os.path.sep + "This" +
            os.path.sep + "is" + os.path.sep + "a" + os.path.sep + "path2, ",
            "CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: [],",
            "PATH: " + os.getcwd() + os.path.sep + "This" + os.path.sep +
            "is" + os.path.sep + "a" + os.path.sep + "path4, ",
            "CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []"
        ])

        self.func_test_equals(str_answer, str_result)
Ejemplo n.º 34
0
    def test_init_for_three_mixed_paths(self):
        """ Testing init for updating three mixed paths of absolute and relative. """

        str_command = "This is a command"
        str_path_one = os.path.sep + os.path.join("This", "is", "a", "path1")
        str_path_two = os.path.join("This", "is", "a", "path2")
        str_path_three = os.path.join("This", "is", "a", "path3")
        str_path_four = os.path.sep + os.path.join("This", "is", "a", "path4")
        str_path_five = os.path.sep + os.path.join("This", "is", "a", "path5")
        str_path_six = os.path.sep + os.path.join("This", "is", "a", "path6")
        lstr_deps = [str_path_one, str_path_three, str_path_five]
        lstr_prods = [str_path_two, str_path_four, str_path_six]
        lstr_deps_answer = [
            str_path_one,
            os.path.join(os.getcwd(), str_path_three), str_path_five
        ]
        lstr_prods_answer = [
            os.path.join(os.getcwd(), str_path_two), str_path_four,
            str_path_six
        ]
        cmd_test = Command.Command(str_command, lstr_deps, lstr_prods)
        str_result = str(
            sorted([str(str_dep) for str_dep in cmd_test.lstr_dependencies] +
                   [str(str_prod) for str_prod in cmd_test.lstr_products]))
        str_answer = "".join([
            "[\"PATH: /This/is/a/path1, CLEAN: 2, Dependency PARENTS: [] CHILDREN: ['This is a command']\", ",
            "\"PATH: /This/is/a/path4, CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []\", ",
            "\"PATH: /This/is/a/path5, CLEAN: 2, Dependency PARENTS: [] CHILDREN: ['This is a command']\", ",
            "\"PATH: /This/is/a/path6, CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []\", ",
            "\"PATH: " + os.getcwd() + "/This/is/a/path2, ",
            "CLEAN: 2, Product PARENTS: ['This is a command'] CHILDREN: []\", ",
            "\"PATH: " + os.getcwd() + "/This/is/a/path3, ",
            "CLEAN: 2, Dependency PARENTS: [] CHILDREN: ['This is a command']\"]"
        ])
        self.func_test_equals(str_answer, str_result)
Ejemplo n.º 35
0
    def generate(self, system, rom, playersControllers):
        # Settings recalbox default config file if no user defined one
        if not system.config['configfile']:
            # Using recalbox config file
            #system.config['configfile'] = recalboxFiles.mupenCustom
            pass

        # Find rom path
        romPath = os.path.dirname(rom)
        romName = os.path.splitext(os.path.basename(rom))[0]
        # Get rom name without extension
        commandArray = [
            recalboxFiles.recalboxBins[system.config['emulator']],
            "--fullscreen", "--joystick=0",
            "--screenshotspath=" + recalboxFiles.screenshotsDir,
            "--extrapath=/usr/share/scummvm",
            "--savepath=" + recalboxFiles.scummvmSaves, "--path="
            "{}"
            "".format(romPath)
        ]
        if 'args' in system.config and system.config['args'] is not None:
            commandArray.extend(system.config['args'])
        commandArray.append("""{}""".format(romName))

        return Command.Command(
            videomode='default',
            array=commandArray,
            env={"SDL_VIDEO_GL_DRIVER": "/usr/lib/libGLESv2.so"})
Ejemplo n.º 36
0
 def checkCoreDiskSpace(self):
     """
     check if there are enough diskspace of the build path, if core_pattern are default.
     """
     coredumppath = Command.checkPath(self.coredumppath)
     #get coredump disk space
     diskspace = Command.getDiskSpace(self.client,coredumppath)
     #get system RSS
     mem = Command.executeSsh("free -m | awk \'NR==2{print $2}\'", self.client)
     if int(mem) > int(diskspace):
         self.stat = self.ABORT
         self.info = "not enough disk space for coredump"
         if self.logflag == True:
             self.logger.log(self.info)
         return self.ABORT
     else:
         return self.RUNNING
Ejemplo n.º 37
0
def command_sw(devid):
  command_url = "http://php-easyhome.rhcloud.com/gitphp/showcomdata.php?devid=@devid".replace("@devid",devid)
  command_start = ""
  while True:
    command_re = GetJson.get_json_url_array(0,command_url,"com")
    #print command_re
    if None == command_re:
      sys.exit(1)
    else:
      if command_start != command_re:
        command_start = command_re
        if command_start == "on":
          Command.blink(8,True)
        else:
          Command.blink(8,False)
        time.sleep(1)
    time.sleep(0.5)
Ejemplo n.º 38
0
 def execute(self,State,cmd=""):
     """
     Simulate Linux server
     """
     self.init(State)
     if self.logflag== True:
         self.logger.log(self.info)
          
     # 1.connect to Linux machine
     self = Command.getClient(self)
     if self.stat == self.FAILED:
         return self.FAILED
     
     # record time
     starttime = time.time()
     duration = 0
     binpath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/bin/"
     getStatusCommnad = binpath+"mstrctl -s IntelligenceServer gs"
     statusInfo = Command.executeSshNull(getStatusCommnad,self.client)
     xmlInfo = xml.dom.minidom.parseString(statusInfo)
     root=xmlInfo.documentElement   
     state = ""
     node= root.getElementsByTagName('state')[0]
     for node in node.childNodes:
         state = node.data
         
     if state.lower().find("running") == -1:
         self.stat = self.FAILED
         self.info ="iserver is not started, please start iserver before running"
         if self.logflag == True:
             self.logger.log(self.info)
         return self.FAILED
     
     Command.executeScreenSshNull(cmd,self.client, self.server)
     time.sleep(5)
     print self.getScreenInfo()
     
     self.stat=self.PASS
     self.info="Simulate Linux iserver task has completed!"
     if self.logflag == True:
         self.logger.log(self.info)
     return self.PASS  
     
     
     
Ejemplo n.º 39
0
 def __init__(self):
     self.pc = PC()
     items.pc = self.pc
     ti.addTime(0,self.pc)
     self.pc.location = Room((10,10,9),True,"bedroom")
     self.pc.location.ceiling.descriptors.append("written on")
     self.pc.location.ceiling.hidden.append("writing")
     self.pc.location.ceiling.writing.append("\"pssst go North and look inside the purple bird\"")
     self.pc.location.ceiling.writing.append("\"gullible\"")
     self.pc.inventory.addItems([WritingUtensil()],self.pc)
     self.pc.location.addItems([Nightstand(["white"]),Dresser(),Wardrobe(),Bed()],self.pc)
     self.pc.location.items[0].spaces[2].door.lock()
     self.pc.location.items[0].spaces[2].door.examined = False
     c = Closet()
     self.pc.location.addDoor("north",c,True)
     b = Bathroom()
     self.pc.location.addDoor("east",b,True)
     hap = Room(self.pc.location.dimensions,True,"way out! Congratulations, you won")
     self.pc.location.addDoor("south",hap,True)
     com.findSearch("door",["south"],self.pc)[0].lock()
     com.findSearch("door",["south"],self.pc)[0].examined = False
     sh = Bookcase(4)
     book = Book("The Violet Canary")
     book.descriptors.append("hollow")
     book.hidden.append("bird")
     sp = Space("book","in the",book.dimensions,book.weight,True)
     sp.door.name = "cover"
     sp.addItems([Key(com.findSearch("door",["south"],self.pc)[0].ID)],self.pc)
     book.spaces.append(sp)
     def newOpen():
         return Item.openUp(book)
     def newClose():
         return Item.close(book)
     book.openUp = newOpen
     book.close = newClose
     c.addItems([sh],self.pc)
     while (sh.spaces[1].items[1].spaces[1].addItems([book],self.pc)=="capErr"):
         sh.spaces[1].items[1].spaces[1].items.pop()
     x = Book()
     def newRead():
         return Book.read(x) + "\nIn a margin, someone has scrawled \"It says gullible on the ceiling!!\""
     x.read = newRead
     self.pc.location.items[0].spaces[2].addItems([x],self.pc)
     self.pc.location.items[0].spaces[3].addItems([Compass()],self.pc)
     self.pc.location.items[1].spaces[4].addItems([Key(self.pc.location.items[0].spaces[2].door.ID)],self.pc)
Ejemplo n.º 40
0
def _main (cmd) :
    scope = Command.scope (cmd)
    if cmd.Break :
        TFL.Environment.py_shell ()
    c = Convert (cmd, scope)
    #c.dump ()
    c.create ()
    scope.commit ()
    scope.ems.compact ()
    scope.destroy ()
Ejemplo n.º 41
0
 def execute(self, State):
     '''
     this method write smart heap variables to mstrexec-iserver.
     '''
     #init the variables.
     self.init(State)
     if self.logflag == True:
         self.logger.log(self.info)
     pass
         
     # 1.connect to Linux machine
     self = Command.getClient(self)
     if self.stat == self.FAILED:
         return self.FAILED
     
     #2. backup the files
     smpath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/bin/mstrexec-iserver"
     self = Command.backupFiles(self,smpath)
     if self.stat == self.FAILED:
         return self.FAILED
     
     # 3.read smart heap variables from config.ini
     configlocation = "Config\config.ini"
     cf = ConfigParser.ConfigParser()
     cf.read(configlocation)
     parameters=cf.items("SmartHeap")
     smstr = ""
     for item in parameters:
         smstr = smstr+"export "+item[0].upper()+"="+item[1]+"\\n"
     
     # 4.write smart heap variables to mstrexec-iserver
     smpos = "mstr_check_max_semaphore"
     command = "sed -i '/"+smpos+"/a "+smstr+"' "+smpath
     result = Command.executeSsh(command, self.client)
     if result != "":
         self.stat = self.FAILED
         self.info ="modify mstrexec-iserver failed." +result+command
         if self.logflag == True:
             self.logger.log(self.info)
         Command.restoreFiles(self,smpath)
         return self.FAILED
     
     if self.stat == self.FAILED:
         Command.restoreFiles(self,smpath)
         return self.FAILED
     else:
         self.stat = self.PASS
         self.info = "tune smart heap successfully."
         if self.logflag == True:
             self.logger.log(task.info)
         return self.PASS
Ejemplo n.º 42
0
 def startServer(self):
     """
     start iserver
     """
     buildpath = Command.checkPath(self.buildInstallPath)+self.buildno+"/"+self.buildversion+"/BIN/"+self.OS+"/bin/"  
     Command.executeScreenSsh("", self.client, self.server) 
     Command.executeScreenSsh("cd " + buildpath, self.client, self.server)
     Command.executeScreenSsh("", self.client, self.server)
     Command.executeScreenSsh("./mstrsvr", self.client, self.server)
     if self.getScreenInfo().lower().find("command not found") == -1:
         return self.RUNNING
     else:
         self.stat = self.FAILED
         self.info = "the build install path "+buildpath+" is wrong,can not find mstrsver"
         if self.logflag == True:
             self.logger.log(self.info)
         return self.FAILED
Ejemplo n.º 43
0
    def execute(self,State):
        """
        load state
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)

        # 1.connect to Linux machine
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED
Ejemplo n.º 44
0
 def runCommand(self, user, channel, msg):
     """ Runs a command. """
     try:
         tokens = []
         parser = Command.getEbnfParser(tokens)
         parser.parseString(msg, True)
         print tokens
         for s in self._interpreter.interpret(tokens):
             if s != None:
                 self.msg(channel, "> " + s.replace("\n", "\\"))
     except:
         self.msg(user, "Oops, seems like something went wrong...")
         raise           
Ejemplo n.º 45
0
def direct(pc,location,locationPrep,locationMod,do,doMod,verb,f,number = -1):
    number = int(number)
    if do=="" and number==-1:
        do="it"
        if len(com.recentItems)==0:
            return "You must specify an object to " + verb + "."
    space = com.findLocation(pc,location,locationPrep,locationMod)
    if space=="WallErr":
        return "There's a wall there."
    if space=="LockedErr":
        return "There's a locked door in your way."
    if space=="ItemErr":
        return "You can't find " + aan(location) + "."
    if space=="PrepErr":
        return "You can't " + verb + " anything " + locationPrep + " the " + location + "."
    if isPlural(do) and number==-1:
        number = 1000
    if number>1:
        if do=="" and location=="":
            space = pc.location
        x = 0
        done = None
        final = ""
        while x<number:
            if not "other" in doMod:
                doMod.append("other")
            #print pc,do,doMod,space
            new= f(pc,do,doMod,space)
            #print "test",new
            if "don't see" in new:
                if final=="":
                    return new
                else:
                    return final
            x+=1
            #print done,com.recentItems[len(com.recentItems)-x:len(com.recentItems)]
            if done==com.recentItems[-1]:
                break
            done = com.recentItems[-1]
            #print x,len(com.recentItems[len(com.recentItems)-x:len(com.recentItems)])
            if not repeats(com.recentItems[len(com.recentItems)-x:len(com.recentItems)]):
                break
            if not final=="":
                midPrin(final)
            final=new
        return final
    return f(pc,do,doMod,space)
Ejemplo n.º 46
0
    def execute(self,State):
        """
        Cluster Linux machine 
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)
                        
        # 1.connect to Linux machine
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED
         
        clusterNodesList = self.clusterNodes.split(";")

        if len(clusterNodesList)>1:
            for index in range(len(clusterNodesList)):
                if index != 0:
                    if clusterNodesList[index] != self.server:
                        state = self.cluserTwoNodes(self.server, clusterNodesList[index])
                        if state == TaskStatus.FAILED:
                            self.stat = self.FAILED
                            return self.FAILED
                         
#       check if clustered 
        Tasks.Command.executeScreenSsh("x",self.client,self.server)
        if self.checkresult("Cluster Command")== False:
            self.info = self.server+" is hang"
            self.stat = self.FAILED
            return self.FAILED
        Tasks.Command.executeScreenSsh("m",self.client,self.server)
        if self.checkresult("Enter contact server")== False:
            self.info = self.server+" is hang"
            self.stat = self.FAILED
            return self.FAILED
        Tasks.Command.executeScreenSsh("",self.client,self.server)
        if self.checkresult(str(len(clusterNodesList))+" members")== False:
            self.info = "can not cluster"
            self.stat = self.FAILED
            return self.FAILED

        self.stat = self.PASS
        self.info ="Cluster success"
        if self.logflag == True:
            self.logger.log(self.info)
        return self.PASS
Ejemplo n.º 47
0
 def createScreenPath(self):
     """
     set the screen path, change the screenrc files
     """
     # get the current screenrc info
     screenrc = Command.executeSsh("tail -5 /etc/screenrc", self.client)
     # check if screen log setted.
     path = Command.checkPath(self.screenlogpath)
     if screenrc.find("logfile") == -1:
         Command.executeSsh("echo \"logfile " + path + "screen_%t.log\" >> /etc/screenrc", self.client)
     #create folder.
     Command.createFolder(path,self.client)
Ejemplo n.º 48
0
 def createScreen(self):
     """
     create screen 
     """
     output = Command.executeSsh("screen -ls", self.client)
     if output.find(self.server) == -1: 
             # create screen with name=server
             # record screen log to [default path set in /etc/screenrc]/screen_server-date.log, use date to separate the log
             # -L: use the log
             # -t: set the screen title
             # -d:detach the screen after create the screen
             # -m:force to create screen
             # -S:create screen with name
         path = Command.checkPath(self.screenlogpath)
         
         #[TODO][@Yanhong]need add file existence check here, to avoid error output of rm command in case no target files to remove.
         Command.executeSsh(" \\rm " + path + "screen_*.log", self.client)
         Command.executeSsh("screen -L -t " + self.server + " -dmS " + self.server, self.client)
     else:
         path = Command.checkPath(self.screenlogpath)
         #[TODO][@Yanhong]need add file existence check here, to avoid error output of rm command in case no target files to remove.
         Command.executeSsh(" \\rm " + path + "screen_*.log", self.client)
         print "screen exist"
Ejemplo n.º 49
0
 def execute(self, state):
     """
     this method will create config.ini file after ssh. and use it to configure iServer through mstrsvr-configuration.
     """
     
     self.init(state)
     if self.logflag ==True:
         self.logger.log(self.info)
     
     try:
         client = Command.getConnect(self.server, self.serverLogin, self.serverPwd, self.serverloginKey)
     except Exception, e:
         #print "connect fialed"
         self.stat = TaskStatus.FAILED
         self.info = "cannot connect to remote Linux machine." + str(e)
         self.info = self.info+"machine:"+self.server+ "\nlogin:"******"\npwd:"+self.serverPwd
         if self.logflag ==True:
             self.logger.log(self.info)
         return TaskStatus.FAILED
Ejemplo n.º 50
0
    def execute(self,State):
        """
        download log file.
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)
        
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED
        #get process id
        self = Command.getUnixOS(self)
        binpath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/bin/" 
        getStatusCommnad = binpath+"mstrctl -s IntelligenceServer gs"
        statusInfo = Command.executeSsh(getStatusCommnad,self.client)
        xmlInfo = xml.dom.minidom.parseString(statusInfo)
        root=xmlInfo.documentElement
        process_id = ""
        node= root.getElementsByTagName('process_id')[0]
        for node in node.childNodes:
            process_id = node.data

        try: 
            t=paramiko.Transport((self.server,22))          
            t.connect(username=self.serverLogin,password=self.serverPwd)          
            sftp=paramiko.SFTPClient.from_transport(t)
            
            DSSErrorsFilesPath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/DSSErrors.log"
            DSSPerformanceFilesPath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/DSSPerformanceMonitor"+process_id+".csv"
            
            os.makedirs(self.localLogPath+self.buildNo+"/"+self.server)
            sftp.get(DSSErrorsFilesPath,self.localLogPath+self.buildNo+"/"+self.server+"/"+"DSSError.log")
            sftp.get(DSSPerformanceFilesPath,self.localLogPath+self.buildNo+"/"+self.server+"/"+"DSSPerformanceMonitor"+process_id+".csv")              
            t.close() 
        except Exception as e:
            self.stat = self.FAILED
            self.info ="log download failed"+str(e)+DSSErrorsFilesPath+DSSPerformanceFilesPath
            if self.logflag == True:
                self.logger.log(self.info)
            return self.FAILED
        
        self.stat=self.PASS
        self.info="download log file task has completed!"
        if self.logflag == True:
            self.logger.log(self.info)
        return self.PASS
Ejemplo n.º 51
0
 def getProjectIDList(self, sourcetype):       
     proj_ID = []
     if sourcetype == "Cache":
         if not Command.checkPathExist(self.sourcepath+"Caches/", self.client):
             return proj_ID
         res = Command.executeSsh("ls "+self.sourcepath+"Caches/", self.client)
     elif sourcetype == "Cube":
         if not Command.checkPathExist(self.sourcepath+"Cube/", self.client):
             return proj_ID
         res = Command.executeSsh("ls "+self.sourcepath+"Cube/", self.client)
     elif sourcetype == "Inbox":
         if not Command.checkPathExist(self.sourcepath+"Inbox/", self.client):
             return proj_ID
         res = Command.executeSsh("ls "+self.sourcepath+"Inbox/", self.client)
     else:
         return proj_ID
     
     proj_ID = res.split(" ")
     return proj_ID
Ejemplo n.º 52
0
 def execute(self,State):
     """
     Create DSN
     """
     self.init(State)
     if self.logflag == True:
         self.logger.log(self.info)
     # 1.connect to Linux machine
     self = Command.getClient(self)
     if self.stat == self.FAILED:
         return self.FAILED
     
     #2.get odbc info
     self = Command.getOdbcInfo(self)
     if self.stat == self.FAILED:
         return self.FAILED
     
     #3.config dsn
     self = Command.getUnixOS(self)
     binpath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/bin/"
     for oif in self.odbcinfo["DSN"]:
         if oif["type"] == "SQLSERVER":
             self = Command.configSqlServerDSN(self,oif,binpath)
             if self.stat == self.FAILED:
                 return self.FAILED
         elif oif["type"] == "ORCLW":
             self = Command.configOracleDSN(self,oif,binpath)
             if self.stat == self.FAILED:
                 return self.FAILED
     
     self.stat = self.PASS
     self.info ="DSN created successfully"
     if self.logflag == True:
         self.logger.log(self.info)
     return self.PASS
     
Ejemplo n.º 53
0
    def load(self, filename):
        start_room = None
        first_room = None
        new_room = None
        new_command = None
        cur_room_name = None

        file_stream = file(filename)

        for line in file_stream:
            line = string.translate(string.strip(line), \
                                    string.maketrans('\\', '\n'))

            if line.find("=") != -1:
                keyword, params = line.split("=", 1)
            else:
                keyword = line
                params = None

            if keyword == "TITLE":
                self.title = params[:]

            elif keyword == "START_ROOM":
                start_room = params[:]

            elif keyword == "INVENTORY_LIMIT":
                self.player.item_limit = string.atoi(params)

            elif keyword == "ROOM":
                new_room = Room()
                new_room.name = params[:]
                self.rooms[new_room.name] = new_room
                if first_room == None:
                    first_room = new_room

                cur_room_name = new_room.name

                new_command = None

            elif keyword == "LOCAL":
                cur_room_name = params[:]

                new_room = None
                new_command = None

            elif keyword == "GLOBAL":
                cur_room_name = None

                new_room = None
                new_command = None

            elif keyword == "COMMAND":
                new_command = Command()
                self.commands.append(new_command)

                if cur_room_name != None:
                    new_command.location = cur_room_name[:]

                if params[0] == "+":
                    new_command.condition = params[1:]
                elif params[0] == "-":
                    new_command.condition = params[:]
                else:
                    pos = params.find(":")
                    if pos != -1:
                        if params[pos + 1] == "+":
                            new_command.condition = params[pos + 2:]
                        else:
                            new_command.condition = params[pos + 1:]

                        new_command.commands = params[:pos].split(",")
                    else:
                        new_command.commands = params.split(",")

            elif keyword == "ACTION":
                # If there is no current command, make one.
                if new_command == None:
                    new_command = Command()
                    self.commands.append(new_command)

                    if cur_room_name != None:
                        new_command.location = cur_room_name[:]

                for action in params.split(";"):
                    new_command.add_action(action)
                    #new_command.actions.append(action)

            elif keyword == "DESC":
                if new_room != None:
                    new_room.desc = params[:]

            elif keyword == "ALT_DESC":
                if new_room != None:
                   new_room.desc_alt = params[:]

            elif keyword == "DESC_CONTROL":
                if new_room != None:
                   new_room.desc_ctrl = params[:]

            elif keyword == "CONTENTS":
                if new_room != None:
                   new_room.items = params.split(",")

            elif keyword == "NORTH":
                if new_room != None:
                   new_room.init_neighbor("N", params[:])

            elif keyword == "SOUTH":
                if new_room != None:
                   new_room.init_neighbor("S", params[:])

            elif keyword == "EAST":
                if new_room != None:
                   new_room.init_neighbor("E", params[:])

            elif keyword == "WEST":
                if new_room != None:
                   new_room.init_neighbor("W", params[:])

            elif keyword == "UP":
                if new_room != None:
                   new_room.init_neighbor("U", params[:])

            elif keyword == "DOWN":
                if new_room != None:
                   new_room.init_neighbor("D", params[:])

        if self.rooms.has_key(start_room):
            self.player.current_room = self.rooms[start_room]
        elif first_room != None:
            self.player.current_room = first_room
        else:
            self.player.current_room = Room()
            self.player.current_room.name = "limbo"
            self.player.current_room.desc = \
                "This adventure has no rooms.  You are in limbo!"

        file_stream.close()
Ejemplo n.º 54
0
    def execute(self, State):
        """
        configure the performance counter and log size
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)
        # 1.connect to Linux machine
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED

        #         regpath = "/build/MSITEST/Test_MSIReg.reg"
        self = Command.getUnixOS(self)
        regpath = (
            Command.checkPath(self.buildInstallPath)
            + self.buildNo
            + "/"
            + self.buildVersion
            + "/BIN/"
            + self.OS
            + "/MSIReg.reg"
        )

        # 2. backup the files
        self = Command.backupFiles(self, regpath)
        if self.stat == self.FAILED:
            return self.FAILED

        # 3. add missed counters
        self = Command.getMsiregInfo(self)
        for modi in self.msiModifyInfo["Reg"]:
            if modi["type"] == "append":
                self = Command.sedAppend(self, modi["oldstr"], modi["newstr"], regpath)
                if self.stat == self.FAILED:
                    Command.restoreFiles(self, regpath)
                    return self.FAILED
            elif modi["type"] == "replace":
                self = Command.sedReplace(self, modi["oldstr"], modi["newstr"], regpath)
                if self.stat == self.FAILED:
                    Command.restoreFiles(self, regpath)
                    return self.FAILED
            elif modi["type"] == "insert":
                self = Command.sedInsert(self, modi["oldstr"], modi["newstr"], regpath)
                if self.stat == self.FAILED:
                    Command.restoreFiles(self, regpath)
                    return self.FAILED
            elif modi["type"] == "update":
                self = Command.sedDelete(self, modi["oldstr"], modi["endstr"], regpath)
                self = Command.sedInsert(self, modi["nextstr"], modi["newstr"], regpath)
                if self.stat == self.FAILED:
                    Command.restoreFiles(self, regpath)
                    return self.FAILED
        # 4.set output log to null:sed 's/"DebugOutput"=""//g' MSIReg.reg > MSIReg.tmp
        self = Command.sedReplace(self, '"DebugOutput"=""', "", regpath)
        if self.stat == self.FAILED:
            Command.restoreFiles(self, regpath)
            return self.FAILED
        # 5.change size of DSSError.log:sed 's/"MaxSize"=dword:00000800/"MaxSize"=dword:00032000/g'
        self = Command.sedReplace(self, '"MaxSize"=dword:00000800', '"MaxSize"=dword:00032000', regpath)
        if self.stat == self.FAILED:
            Command.restoreFiles(self, regpath)
            return self.FAILED
        # 6.change size of DSSPerformance.log;sed 's/"MaxSize"=dword:000007d0/"MaxSize"=dword:00032000/g'
        self = Command.sedReplace(self, '"MaxSize"=dword:000007d0', '"MaxSize"=dword:00032000', regpath)
        if self.stat == self.FAILED:
            Command.restoreFiles(self, regpath)
            return self.FAILED
        # 8.set DSSPerformance counters:sed 's/"Persist"=dword:00000000/"Persist"=dword:00000001/g'
        for modi in self.msiModifyInfo["Perf"]:
            if modi["AllPerfOn"] == "true":
                self = Command.sedReplace(self, '"Persist"=dword:00000000', '"Persist"=dword:00000001', regpath)
                if self.stat == self.FAILED:
                    Command.restoreFiles(self, regpath)
                    return self.FAILED

        self.stat = self.PASS
        self.info = "Linux diag configure successfully"
        if self.logflag == True:
            self.logger.log(self.info)
        return self.PASS
Ejemplo n.º 55
0
	def buildCommandList(self):
		import os
		import json
		import Command
		from Command.Emote import Emote
		
		cmdList = self.attributes['commandList']
		
		cmdList['go']			= Command.loadCommand('Go')
		cmdList['look']			= Command.loadCommand('Look')
		cmdList['l']			= cmdList['look']
		cmdList['ls']			= cmdList['look']
		cmdList['say']			= Command.loadCommand('Say')
		cmdList['cast']			= Command.loadCommand('Cast')
		cmdList['c']			= cmdList['cast']
		cmdList['inventory']	= Command.loadCommand('Inventory')
		cmdList['i']			= cmdList['inventory']
		cmdList['inven']		= cmdList['inventory']
		cmdList['inv']			= cmdList['inventory']
		cmdList['drop']			= Command.loadCommand('Drop')
		cmdList['grab']			= Command.loadCommand('Grab')
		cmdList['get']			= cmdList['grab']
		cmdList['equip']		= Command.loadCommand('Equip')
		cmdList['eq']			= cmdList['equip']
		cmdList['equipment']	= cmdList['equip']
		cmdList['wear']			= Command.loadCommand('Wear')
		cmdList['wield']		= Command.loadCommand('Wield')
		cmdList['remove']		= Command.loadCommand('Remove')
		cmdList['rem']			= cmdList['remove']
		cmdList['who']			= Command.loadCommand('Who')
		cmdList['who']			= Command.loadCommand('Who')
		cmdList['select']		= Command.loadCommand('Select')
		cmdList['sel']			= cmdList['select']
		
		
		# EMOTES
		currentDir	= os.getcwd()
		emoteDir	= currentDir + '/Content/commands/emotes' 
		fileList	= os.listdir(emoteDir)

		for fname in fileList:			
			if fname.endswith('.txt'):
				filePath		= '{}/{}'.format(emoteDir, fname)
				emoteFile		= open(filePath, 'r')
				jsonString		= emoteFile.read()
				jsonObj			= json.loads(jsonString)
				emote			= Emote(jsonObj['template'])

				emoteFile.close()

				for cmdName in jsonObj['commandNames']:
					cmdList[cmdName] = emote
					
				self.attributes['emoteList'].append(emote)
Ejemplo n.º 56
0
 def getScreenInfo(self):
     """
     get screenlog info   
     """
     screenlog = Command.executeSshNull("tail -50 " + Command.checkPath(self.screenlogpath) + "screen_" + self.server+".log", self.client)
     return screenlog
Ejemplo n.º 57
0
 def execute(self, State):
     """
     this method stop the iserver
     """
     #init the variables.
     self.init(State)
     if self.logflag == True:
         self.logger.log(self.info)
     pass
 
     # stop Linux iserver.
     if self.OS == "Linux":
         # 1.connect to Linux machine
         self = Command.getClient(self)
         if self.stat == self.FAILED:
             return self.FAILED
         
         # 2.check server status.
         status = self.checkServerStatus()
         if status == "stopped":
             self.info = 'The target IServer is already stopped. StopServerTask aborted.'
             self.stat = self.ABORT
             return self.ABORT
         elif status == "terminated":
             self.info = 'The target IServer is terminated due to other actions. StopServerTask aborted.'
             self.stat = self.ABORT
             return self.ABORT
         elif status == "stopping":
             self.info = 'The target IServer is stopping. Please wait for its completion. StopServerTask aborted.'
             self.stat = self.ABORT
             return self.ABORT
         elif status == "unloading":
             self.info = 'The target IServer is unloading. Please wait for its completion. StopServerTask aborted.'
             self.stat = self.ABORT
             return self.ABORT
         elif status == "running":
             self.stopServer()
             if self.stat == self.FAILED:
                 return self.FAILED
         else:
             self.info = 'The target IServer is neither running nor stopped. Please check its status. StopServerTask aborted.'
             self.stat = self.ABORT
             return self.ABORT
         
         # 3.check server status after stop command is sent.
         status = self.checkServerStatus()
         while(status == "stopping" or status == "unloading"):
             time.sleep(30)
             status = self.checkServerStatus()
             
         if status == "stopped":
             self.info = "StopServerTask successfully completed."
             self.stat = self.PASS
             return self.PASS
         else:
             self.info = "StopServerTask failed."
             self.stat = self.FAILED
             return self.FAILED 
     else:
         # if os is windows.
         c = rpyc.classic.connect(State.get("server"))  
         rsub = c.modules.subprocess
         #rsub.system("\"" + State.get("buildpath") + "MSTRSvr2_64.exe\"")
Ejemplo n.º 58
0
                    self.stat = self.PASS
            else:
                self.info = "Cannot delete build when IServer is not stopped."
                self.stat = self.FAILED
                
        else:
            # if os is windows.
            c = rpyc.classic.connect(State.get("server"))
            # TO BE IMPLEMENTED

if __name__ == "__main__":
    
    print "Clear up IServer build is running..."
    
    configlocation = sys.argv[1]
    cf = ConfigParser.ConfigParser()
    cf.read(configlocation)
    
    parameters=cf.items("Config")
    
    s = State()
    for item in parameters:
        s.put(item[0], item[1])
    
    t = ClearupTask()
    Command.displayTaskState(t.getStat())
    try:
        state = t.execute(s)
    except Exception as e:
        print "task failed."+str(e)
    Command.displayTaskState(t.getStat())
Ejemplo n.º 59
0
 def execute(self, State):
     #init the variables.
     self.init(State)
     if self.logflag == True:
         self.logger.log(self.info)
     pass
     
     if self.OS == "Linux":
         # 1.connect to Linux machine
         self = Command.getClient(self)
         if self.stat == self.FAILED:
             return self.FAILED
         
         # 2.check Iserver path
         buildpath = Command.checkPath(self.buildInstallPath)+self.buildno+"/"+self.buildversion+"/"
         if not Command.checkPathExist(buildpath, self.client):
             self.info = "directory "+buildpath+" does not exist."
             self.stat = self.ABORT
             return self.ABORT
         
         # 3.stop Iserver if it is running
         cmd = buildpath+"BIN/Linux/bin/mstrctl -s IntelligenceServer gs"
         result = Command.executeSsh(cmd, self.client)
         serverStatus = re.search(r">\w+<\/state>", result).group(0)
         if serverStatus[1:-8] == "running":
             cmd = buildpath + "BIN/Linux/bin/mstrctl -s IntelligenceServer stop"
             Command.executeSsh(cmd, self.client)
             time.sleep(120)
                     
         # 4.delete Iserver build
         cmd = buildpath+"BIN/Linux/bin/mstrctl -s IntelligenceServer gs"
         result = Command.executeSsh(cmd, self.client)
         serverStatus = re.search(r">\w+<\/state>", result).group(0)
         if (serverStatus[1:-8] == "stopped" or serverStatus[1:-8] == "terminated"):
             cmd = "rm -rf "+Command.checkPath(self.buildInstallPath)+self.buildno
             result = Command.executeSsh(cmd, self.client)
             if result != "":
                 self.info = "Error in delete directory "+Command.checkPath(self.buildInstallPath)+self.buildno
                 self.stat = self.FAILED
             else:
                 self.info = "Successfully delete directory "+Command.checkPath(self.buildInstallPath)+self.buildno
                 self.stat = self.PASS
         else:
             self.info = "Cannot delete build when IServer is not stopped."
             self.stat = self.FAILED
             
     else:
         # if os is windows.
         c = rpyc.classic.connect(State.get("server"))
Ejemplo n.º 60
0
    def execute(self,State):
        """
        monitor Linux server
        """
        self.init(State)
        if self.logflag == True:
            self.logger.log(self.info)     
        # 1.connect to Linux machine
        self = Command.getClient(self)
        if self.stat == self.FAILED:
            return self.FAILED
        
        # record time
        starttime = time.time()
        duration = 0
        self = Command.getUnixOS(self)
        binpath = Command.checkPath(self.buildInstallPath)+self.buildNo+"/"+self.buildVersion+"/BIN/"+self.OS+"/bin/"
        getStatusCommnad = binpath+"mstrctl -s IntelligenceServer gs"
        
        # 2.monitor
        #check state :./mstrctl -s IntelligenceServer gs
        while duration < int(self.testTimeLimit)*60:
            #1. check if server crash
            #get server status
            statusInfo = Command.executeSsh(getStatusCommnad,self.client)
            xmlInfo = xml.dom.minidom.parseString(statusInfo)
            root=xmlInfo.documentElement
            process_id = ""
            node= root.getElementsByTagName('process_id')[0]
            for node in node.childNodes:
                process_id = node.data
            state = ""
            node= root.getElementsByTagName('state')[0]
            for node in node.childNodes:
                state = node.data
            
            if state.lower().find("stopped") != -1 :
                self.stat = self.FAILED
                self.info ="iserver is stopped, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
            elif state.lower().find("starting")!= -1:
                self.info ="iserver is starting"
            elif state.lower().find("running")!= -1:
                self.info ="iserver is running fine."
            elif state.lower().find("stopping")!= -1:
                self.stat = self.FAILED
                self.info ="iserver is stopping, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
            elif state.lower().find("terminated")!= -1:
                self.stat = self.FAILED
                self.info ="iserver is terminated, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
            elif state.lower().find("pausing")!= -1:
                self.stat = self.FAILED
                self.info ="iserver is pausing, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
            elif state.lower().find("paused")!= -1:
                self.stat = self.FAILED
                self.info ="iserver is paused, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
            elif state.lower().find("resuming")!= -1:
                self.info ="iserver is resuming, please check if server crashed" 
            elif state.lower().find("hanging")!= -1:
                self.stat = self.FAILED
                self.info ="iserver is hanging, please check if server crashed"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+": "+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
               
            #2. check if server hit assertion
            screeninfo = self.getScreenInfo()
            if screeninfo.lower().find("assertion") != -1:
                self.stat = self.FAILED
                self.info = "iserver hit assertion"
                if self.logflag == True:
                    self.logger.log(self.info)
                if self.emailflag == True:
                    es = EmailSender(self.emailSender, self.server+"hit assertion:"+screeninfo, self.server+": "+self.info,self.emailToList, "","", attachment=None)
                    es.send()
                return self.FAILED
#             print duration
#             print self.info
#             print state
            time.sleep(int(self.testCheckTime)*60)
            currenttime = time.time()
            duration = int(currenttime-starttime)

        self.stat=self.PASS
        self.info="monitor Linux iserver task has completed!"
        if self.logflag == True:
            self.logger.log(self.info)
        if self.emailflag == True:
            es = EmailSender(self.emailSender, self.server+self.info, self.server+": "+self.info,self.emailToList, "","", attachment=None)
            es.send()
        return self.PASS