<commit_before># Copyright 2009-2015 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
import string
from utils import *
from ovfenv import *

vmrunInstance = None

def initializeVmrunInstance():
    global vmrunInstance
    vmrunInstance = VmrunCommand("")
    
def getVmrunInstance():
    global vmrunInstance
    return vmrunInstance

class VmrunCommand:
    
    def __init__(self, toolsPath=""):
        self.toolsPath = toolsPath
        self.vmrunCmd = "vmrun"  # We assume it is in the path
        self.mkisofsCmd = "mkisofs"
        self.vdiskmanagerCmd = "vmware-vdiskmanager"
    
    def powerOn(self, vmxPath):
        guiOption = "nogui"
        if GetCmdOption("gui", False):
            guiOption = "gui"
        cmd = [ self.vmrunCmd, "start", vmxPath, guiOption ]
        self.subprocessCall(cmd)
    
    def powerOff(self, vmxPath, hard=False):
        if hard:
            action = "hard"
        else:
            action ="soft"
        cmd = [ self.vmrunCmd, "stop", vmxPath, action ]
        self.subprocessCall(cmd)                              
    
    def subprocessCall(self, cmd):
        try:
            subprocess.call(cmd)
        except:
            print "Error: Failed to execute " + cmd[0] + ". Is it in your path?"
            sys.exit(1)
            
    def readRuntimeVariable(self, vmxPath, name):
        cmd = [ self.vmrunCmd,
                "readVariable",
                vmxPath,
                "runtimeConfig",
                name]
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
        out = pipe.read().strip().lower()
        pipe.close()
        return out.strip()
    
    def readGuestInfoIp(self, vmxPath):
        return self.readRuntimeVariable(vmxPath, "guestinfo.ip")
    
    def getIP(self, vmxPath):
        out = self.readGuestInfoIp(vmxPath)
        if out.find("error") != -1:
            return "" # Not running
        return out.strip()
    
    def getPowerStateAndIp(self, vmxPath):
        out = self.readGuestInfoIp(vmxPath)
        if out.find("error") != -1:
            return ("Powered Off", "")
        if len(out) == 0:
            return ("Powered On", "")
        else:
            return ("Powered On", out)
    
    def getInstallDir(self):
        return os.path.dirname(sys.argv[0])
                    
    def createVm(self, vmxFile, name, memSize, diskSize):
        dir = os.path.dirname(vmxFile)
        cleanupList = OsMkdirs(dir)
                
        diskFile = os.path.join(dir, "disk.vmdk")
        success = self.createSparseVmdk(diskFile, diskSize)
        if not success:
            cleanupList.reverse()
            for dir in cleanupList:
                OsTryRmdir(dir)
                sys.exit(1)
        
        self.createVmxFile(vmxFile, name, memSize, diskFile)
        
    def createSparseVmdk(self, filename, diskSize):
        diskCreatePath = os.path.join(self.toolsPath, self.vdiskmanagerCmd)
        OsTryRemove(filename)
        cmd = [ diskCreatePath,
                "-c",
                "-t", "0",              # monoSparse
                "-s", diskSize + "GB",  # capacity
                "-a", "lsilogic",       # adapter type
                filename]
        try:
            subprocess.call(cmd)
        except:
            print "Error: Failed to execute " + cmd[0] + ". Is it in your path?"
            return False
        return True
        
    def createVmxFile(self, vmxPath, name, memSize, diskFile):
        vmxTemplatePath = os.path.join(self.getInstallDir(), "template.vmx")
        vmxTemplateFile = open(vmxTemplatePath, "r")
        vmxTemplate = Template(vmxTemplateFile.read())
        vmxTemplateFile.close()
        
        # Make diskFile relative to vmx file<commit_msg>Fix issues related to py2exe<commit_after># Copyright 2009-2015 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
import string
from utils import *
from ovfenv import *

vmrunInstance = None

# See http://www.py2exe.org/index.cgi/Py2ExeSubprocessInteractions
# This does not adversely affect vapprun behavior.
if sys.platform.startswith('win'):
    NUL_STDERR = file('nul', 'a')
else:
    NUL_STDERR = None

def initializeVmrunInstance():
    global vmrunInstance
    vmrunInstance = VmrunCommand("")
    
def getVmrunInstance():
    global vmrunInstance
    return vmrunInstance

class VmrunCommand:
    
    def __init__(self, toolsPath=""):
        self.toolsPath = toolsPath
        self.vmrunCmd = "vmrun"  # We assume it is in the path
        self.mkisofsCmd = "mkisofs"
        self.vdiskmanagerCmd = "vmware-vdiskmanager"
    
    def powerOn(self, vmxPath):
        guiOption = "nogui"
        if GetCmdOption("gui", False):
            guiOption = "gui"
        cmd = [ self.vmrunCmd, "start", vmxPath, guiOption ]
        self.subprocessCall(cmd)
    
    def powerOff(self, vmxPath, hard=False):
        if hard:
            action = "hard"
        else:
            action ="soft"
        cmd = [ self.vmrunCmd, "stop", vmxPath, action ]
        self.subprocessCall(cmd)                              
    
    def subprocessCall(self, cmd, exitOnFail=True):
        try:
            # On Windows, inhibit the console window that
            # pops up as a result of doing this.
            if sys.platform.startswith('win'):
                import win32process
                opts = {'creationflags': win32process.CREATE_NO_WINDOW}
            else:
                opts = {}
            subprocess.call(cmd, **opts)
        except:
            print "Error: Failed to execute " + cmd[0] + ". Is it in your path?"
            if exitOnFail:
                sys.exit(1)
            return False

        return True

    def readRuntimeVariable(self, vmxPath, name):
        cmd = [ self.vmrunCmd,
                "readVariable",
                vmxPath,
                "runtimeConfig",
                name]
        # We pipe stdin even though we don't write anything to it,
        # and use NUL_STDERR (on Windows, an explicit nul-pointing
        # file handle.) This is to work around issues with py2exe
        # and does not harm behavior on non-Windows platforms.
        # Furthermore, on Windows, inhibit the console window that
        # pops up as a result of doing this.
        if sys.platform.startswith('win'):
            import win32process
            opts = {'creationflags': win32process.CREATE_NO_WINDOW}
        else:
            opts = {}

        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=NUL_STDERR,
                             **opts)
        out = p.stdout.read().strip().lower()
        p.stdout.close()
        return out.strip()
    
    def readGuestInfoIp(self, vmxPath):
        return self.readRuntimeVariable(vmxPath, "guestinfo.ip")
    
    def getIP(self, vmxPath):
        out = self.readGuestInfoIp(vmxPath)
        if out.find("error") != -1:
            return "" # Not running
        return out.strip()
    
    def getPowerStateAndIp(self, vmxPath):
        out = self.readGuestInfoIp(vmxPath)
        if out.find("error") != -1:
            return ("Powered Off", "")
        if len(out) == 0:
            return ("Powered On", "")
        else:
            return ("Powered On", out)
    
    def getInstallDir(self):
        return os.path.dirname(sys.argv[0])
                    
    def createVm(self, vmxFile, name, memSize, diskSize):
        dir = os.path.dirname(vmxFile)
        cleanupList = OsMkdirs(dir)
                
        diskFile = os.path.join(dir, "disk.vmdk")
        success = self.createSparseVmdk(diskFile, diskSize)
        if not success:
            cleanupList.reverse()
            for dir in cleanupList:
                OsTryRmdir(dir)
                sys.exit(1)
        
        self.createVmxFile(vmxFile, name, memSize, diskFile)
        
    def createSparseVmdk(self, filename, diskSize):
        diskCreatePath = os.path.join(self.toolsPath, self.vdiskmanagerCmd)
        OsTryRemove(filename)
        cmd = [ diskCreatePath,
                "-c",
                "-t", "0",              # monoSparse
                "-s", diskSize + "GB",  # capacity
                "-a", "lsilogic",       # adapter type
                filename]

        return self.subprocessCall(cmd, exitOnFail=False)
        
    def createVmxFile(self, vmxPath, name, memSize, diskFile):
        vmxTemplatePath = os.path.join(self.getInstallDir(), "template.vmx")
        vmxTemplateFile = open(vmxTemplatePath, "r")
        vmxTemplate = Template(vmxTemplateFile.read())
        vmxTemplateFile.close()
        
        # Make diskFile relative to vmx file
{'fraction_non_alphanumeric': 0.09645649304497919, 'fraction_numerical': 0.005381256980404102, 'mean_word_length': 1.9535232383808097, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3042752', 'n_tokens_mistral': 2893, 'n_tokens_neox': 2809, 'n_words': 782}