class IxNetwork

Public Class Methods

new() click to toggle source
# File lib/ixnetwork.rb, line 34
def initialize()
    @_root = '::ixNet::OBJ-/'
    @_null = '::ixNet::OBJ-null'
    @_socket = nil
    @_proxySocket = nil
    @_connectTokens = ''
    @_evalError = '1'
    @_evalSuccess = '0'
    @_evalResult = '0'
    @_addContentSeparator = 0
    @_firstItem = true
    @_sendContent = Array.new
    @_buffer = false
    @_sendBuffer = Array.new
    @_decoratedResult = Array.new
    @_filename = nil
    @_debug = false
    @_async = false
    @_timeout = nil
    @_OK = '::ixNet::OK'
    @_version = '8.40.1124.8'
end

Public Instance Methods

_CheckClientVersion() click to toggle source
# File lib/ixnetwork.rb, line 555
def _CheckClientVersion ()
    if @_version != self.getVersion() then
        puts "WARNING: IxNetwork Ruby library version " + @_version + " is not matching the IxNetwork client version " + self.getVersion()
    end
end
__CheckObjRef(objRef) click to toggle source
# File lib/ixnetwork.rb, line 303
def __CheckObjRef(objRef)
    if (objRef.is_a? String) == false then
        raise IxNetError,'The objRef parameter must be String instead of ' + objRef.class.to_s
    else
        return objRef
    end
end
__Close() click to toggle source
# File lib/ixnetwork.rb, line 328
def __Close()
    begin
        if @_socket then
            @_socket.close()
        end
    rescue
        # clear exceptions
    end
    begin
        if @_proxySocket then
            @_proxySocket.close()
        end
    rescue
        # clear exceptions
    end
    @_socket = nil
    @_proxySocket = nil
end
__CreateFileOnServer(filename) click to toggle source
# File lib/ixnetwork.rb, line 322
def __CreateFileOnServer(filename)
    self.__Send("<001><006><007%s>%s<009>" % [filename.length, filename])
    remoteFilename = self.__Recv()
    return self.__SendRecv('ixNet', 'writeTo', remoteFilename,'-ixNetRelative', '-overwrite')
end
__Join(*args) click to toggle source
# File lib/ixnetwork.rb, line 347
def __Join(*args)
    for arg in args
        if arg.class == Array then
            if @_addContentSeparator == 0 then
                @_sendContent.push("\02")
            end
            if @_addContentSeparator > 0 then
                @_sendContent.push('{')
            end
            @_addContentSeparator += 1
            @_firstItem = true
            if arg.length == 0 then
                @_sendContent.push('{}')
            else
                for item in arg
                    self.__Join(item)
                end
            end
            if @_addContentSeparator > 1 then
                @_sendContent.push('}')
            end
            @_addContentSeparator -= 1
        else
            if @_addContentSeparator == 0 and @_sendContent.length > 0 then
                @_sendContent.push("\02")
            elsif @_addContentSeparator > 0
                if @_firstItem == false then
                    @_sendContent.push(' ')
                else
                    @_firstItem = false
                end
            end
            if arg.nil? then
                arg = ''
            elsif !(arg.is_a? String)
                arg = arg.to_s
            end
            if arg.length == 0 and @_sendContent.length > 0 then
                @_sendContent.push('{}')
            elsif arg.include?(' ') and @_addContentSeparator > 0
                @_sendContent.push('{'+arg+'}')
            else
                @_sendContent.push(arg)
            end
        end
    end
    return
end
__PutFileOnServer(filename) click to toggle source
# File lib/ixnetwork.rb, line 311
def __PutFileOnServer(filename)
    truncatedFilename = Pathname.new(filename).basename
    fid = File.open(filename, 'rb')
    self.__Send("<001><005><007%s>%s<009%s>" % [filename.length, filename,File.size(filename)])
    self.__SendBinary(fid.read())
    fid.close()
    remoteFilename = self.__Recv()

    return self.__SendRecv('ixNet', 'readFrom', remoteFilename,'-ixNetRelative')
end
__Recv() click to toggle source
# File lib/ixnetwork.rb, line 471
def __Recv()
    @_decoratedResult = Array.new
    responseBuffer = ''
    begin
        while true
            responseBuffer = ''
            commandId = nil
            contentLength = 0

            while true
                responseBuffer += @_socket.recv(1)
                startIndex = responseBuffer.index('<')
                stopIndex = responseBuffer.index('>')
                if !startIndex.nil? and !stopIndex.nil? then
                    @si = startIndex + 1
                    @ei = startIndex + 3
                    commandId = responseBuffer[@si..@ei].to_i
                    if (startIndex + 4) < stopIndex then
                        @si = startIndex + 4
                        @ei = stopIndex
                        contentLength = responseBuffer[@si..@ei].to_i
                    end
                    break
                end
            end
            if commandId == 1 then
                @_evalResult = @_evalError
                @_socket.recv(contentLength)
            elsif commandId == 3
                @_socket.recv(contentLength)
            elsif commandId == 4
                @_evalResult = @_socket.recv(contentLength)
            elsif commandId == 7
                @_filename = @_socket.recv(contentLength)
            elsif commandId == 8
                binaryFile = open(@_filename, 'w+b')
                chunk = ''
                bytesToRead = 32767
                while contentLength > 0
                    if contentLength < bytesToRead then
                        bytesToRead = contentLength
                    end
                    chunk = @_socket.recv(bytesToRead)
                    binaryFile.write(chunk)
                    contentLength -= chunk.length
                end
                binaryFile.close()
            elsif commandId == 9
                @_decoratedResult = Array.new
                chunk = ''
                bytesToRead = 32767
                while contentLength > 0
                    if contentLength < bytesToRead then
                        bytesToRead = contentLength
                    end
                    chunk = @_socket.recv(bytesToRead)
                    @_decoratedResult.push(chunk)
                    contentLength -= chunk.length
                end
                break
            end
        end

    rescue SocketError => e
        self.__Close()
        raise IxNetError,"Recv failed. Error:"+e.to_s
    end

    if @_debug then
        puts "Received: " + @_decoratedResult.join('')
    end

    if @_evalResult == @_evalError then
        raise IxNetError,@_decoratedResult.join('')
    end

    if @_decoratedResult.length > 0 and @_decoratedResult[0].start_with?("\01") then
        @_decoratedResult[0] = @_decoratedResult[0].sub("\01", '')
        return eval(@_decoratedResult.join(""))
    else
        return @_decoratedResult.join("")
    end
end
__Send(content) click to toggle source
# File lib/ixnetwork.rb, line 442
def __Send(content)
    if @_socket.nil? then
        raise IxNetError,'not connected'
    else
        begin
            if content.is_a? String then
                content = content
            end
            @_socket.send(content,0)
        rescue SocketError => e
            self.__Close()
            raise IxNetError,"Error:"+e
        end
    end
end
__SendBinary(content) click to toggle source
# File lib/ixnetwork.rb, line 458
def __SendBinary(content)
    if @_socket.nil? then
        raise IxNetError,"not connected"
    else
        begin
            @_socket.send(content,0)
        rescue SocketError => e
            self.__Close()
            raise IxNetError,"Error:"+e
        end
    end
end
__SendRecv(*args) click to toggle source
# File lib/ixnetwork.rb, line 396
def __SendRecv(*args)
    if @_socket.nil? then
        raise IxNetError,'not connected'
    end

    @_addContentSeparator = 0
    @_firstItem = true

    argList = args

    if @_async then
        argList.insert(1, '-async')
    end

    if !@_timeout.nil? then
        argList.insert(1, '-timeout')
        argList.insert(2, @_timeout)
    end

    for item in argList
        self.__Join(item)
    end

    @_sendContent.push("\03")
    @_sendBuffer.push(@_sendContent.join(''));
    if @_buffer == false then
        buffer = @_sendBuffer.join('')
        if @_debug then
            puts "Sending: " + buffer
        end
        self.__Send("<001><002><009%s>%s" % [buffer.length,buffer])
        @_sendBuffer = Array.new
    end

    @_async = false
    @_timeout = nil
    @_buffer = false
    @_sendContent = Array.new

    if @_sendBuffer.length > 0 then
        return @_OK
    else
        return self.__Recv()
    end
end
__initialConnect(address, port, options) click to toggle source
# File lib/ixnetwork.rb, line 80
def __initialConnect(address, port, options)
    # make an initial socket connection
    # this will keep trying as it could be connecting to the proxy
    # which may not have an available application instance at that time
    attempts = 0
    while true
        begin
                            sd = Socket.getaddrinfo(address,Socket::SOCK_STREAM,Socket::AF_INET)
            @_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
            @_socket.connect(Socket.pack_sockaddr_in(port, sd[0][2]))
            break
        rescue SocketError => e
            if @_proxySocket != nil and attempts < 120 then
                time.sleep(2)
                attempts += 1
            else
                self.__Close()
                raise IxNetError,e.to_s + e.backtrace.to_s
            end
        end
    end

    # a socket connection has been made now read the type of connection
    # setup to timeout if the remote endpoint is not valid
    optval = [30, 0].pack("l_2")
    @_socket.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval
    read, write, error = select([@_socket], [], [], 30)
    if read.length == 0 and write.length == 0 and error.length == 0 then
        self.__Close()
        raise IxNetError,'Connection handshake timed out after 30 seconds'
    end
    optval = [0, 0].pack("l_2")
    @_socket.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval

    # process the results from the endpoint
    connectString = self.__Recv()
    if connectString == 'proxy' then
        @_socket.send(options,0)
        @_connectTokens = self.__Recv().to_s
        connectTokensArray = @_connectTokens.split()
        connectTokens = Hash[connectTokensArray.values_at(* connectTokensArray.each_index.select {|i| i.even?}).zip \
        connectTokensArray.values_at(* connectTokensArray.each_index.select {|i| i.odd?})]
        @_proxySocket = @_socket
        @_socket = nil
        self.__initialConnect(address, connectTokens['-port'], '')
    end
end
add(objRef, child, *args) click to toggle source
# File lib/ixnetwork.rb, line 230
def add(objRef, child, *args)
    return self.__SendRecv('ixNet', 'add', self.__CheckObjRef(objRef), child, *args)
end
adjustIndexes(objRef, object) click to toggle source
# File lib/ixnetwork.rb, line 260
def adjustIndexes(objRef, object)
    return self.__SendRecv('ixNet', 'adjustIndexes', self.__CheckObjRef(objRef), object)
end
commit() click to toggle source
# File lib/ixnetwork.rb, line 218
def commit()
    return self.__SendRecv('ixNet', 'commit')
end
connect(address, *args) click to toggle source
# File lib/ixnetwork.rb, line 128
def connect(address, *args)
    begin
        if @_socket != nil then
            self.__SendRecv('ixNet', 'help')
        end
    rescue
        self.__Close()
    end

    begin
        nameValuePairs = {}
        name = nil
        for arg in args
            if arg.to_s.start_with?('-') then
                if name.nil? then
                    name = arg.to_s
                else
                    nameValuePairs[name] = ''
                end
            elsif !name.nil?
                nameValuePairs[name] = arg.to_s
                name = nil
            end
        end
        if  not nameValuePairs.include?('-port') then
            nameValuePairs['-port'] = 8009
        end

        options = '-clientusername ' + Etc.getlogin
        if  nameValuePairs.include?('-serverusername') then
            options += ' -serverusername ' + nameValuePairs['-serverusername']
        end
        if  nameValuePairs.include?('-connectTimeout') then
            options += ' -connectTimeout ' + nameValuePairs['-connectTimeout']
        end
        if  nameValuePairs.include?('-closeServerOnDisconnect') then
            options += ' -closeServerOnDisconnect ' + nameValuePairs[-closeServerOnDisconnect]
        else
            options += ' -closeServerOnDisconnect true'
        end

        if @_socket.nil? then
            self.__initialConnect(address, nameValuePairs['-port'].to_i, options)
            conRes = self.__SendRecv('ixNet', 'connect', address,'-clientType', 'ruby', *args)
            self._CheckClientVersion()
            return conRes
        else
            sockInfo = @_socket.getpeername()
            return "Cannot connect to #{address}:#{nameValuePairs['-port']} as a connection is already established to #{sockInfo[0]}:#{sockInfo[1]}. Please execute disconnect before trying this command again."
        end
    rescue SocketError => e
        self.__Close()
        raise IxNetError,"Unable to connect to host:"+address.to_s+" port:"+nameValuePairs['-port'].to_s+". Error:"+e.to_s
    end
end
disconnect() click to toggle source
# File lib/ixnetwork.rb, line 184
def disconnect()
    response = self.__SendRecv('ixNet', 'disconnect')
    self.__Close()
    return response
end
execute(*args) click to toggle source
# File lib/ixnetwork.rb, line 226
def execute(*args)
    return self.__SendRecv('ixNet', 'exec', *args)
end
exists(objRef) click to toggle source
# File lib/ixnetwork.rb, line 214
def exists(objRef)
    return self.__SendRecv('ixNet', 'exists', self.__CheckObjRef(objRef))
end
getAttribute(objRef, name) click to toggle source
# File lib/ixnetwork.rb, line 248
def getAttribute(objRef, name)
    return self.__SendRecv('ixNet', 'getAttribute', self.__CheckObjRef(objRef), name)
end
getFilteredList(objRef, child, name, value) click to toggle source
# File lib/ixnetwork.rb, line 256
def getFilteredList(objRef, child, name, value)
    return self.__SendRecv('ixNet', 'getFilteredList', self.__CheckObjRef(objRef), child, name, value)
end
getList(objRef, child) click to toggle source
# File lib/ixnetwork.rb, line 252
def getList(objRef, child)
    return self.__SendRecv('ixNet', 'getList', self.__CheckObjRef(objRef), child)
end
getNull() click to toggle source
# File lib/ixnetwork.rb, line 66
def getNull()
    return @_null
end
getParent(objRef) click to toggle source
# File lib/ixnetwork.rb, line 210
def getParent(objRef)
    return self.__SendRecv('ixNet', 'getParent', objRef)
end
getResult(resultId) click to toggle source
# File lib/ixnetwork.rb, line 271
def getResult(resultId)
    return self.__SendRecv('ixNet', 'getResult', resultId)
end
getRoot() click to toggle source
# File lib/ixnetwork.rb, line 62
def getRoot()
    return @_root
end
getVersion() click to toggle source
# File lib/ixnetwork.rb, line 202
def getVersion()
    if @_socket.nil? then
        return @_version
    else
        return self.__SendRecv('ixNet', 'getVersion')
    end
end
help(*args) click to toggle source
# File lib/ixnetwork.rb, line 190
def help(*args)
    return self.__SendRecv('ixNet', 'help', *args)
end
isDone(resultId) click to toggle source
# File lib/ixnetwork.rb, line 279
def isDone(resultId)
    return self.__SendRecv('ixNet', 'isDone', resultId)
end
isSuccess(resultId) click to toggle source
# File lib/ixnetwork.rb, line 283
def isSuccess(resultId)
    return self.__SendRecv('ixNet', 'isSuccess', resultId)
end
readFrom(filename, *args) click to toggle source
# File lib/ixnetwork.rb, line 295
def readFrom(filename, *args)
    if args.any? { |word| '-ixNetRelative'.include?(word)} then
        return self.__SendRecv('ixNet', 'readFrom', filename,args.join("\02"))
    else
        return self.__PutFileOnServer(filename)
    end
end
remapIds(localIdList) click to toggle source
# File lib/ixnetwork.rb, line 264
def remapIds(localIdList)
    #if type(localIdList) is tuple then
    #  localIdList = list(localIdList)
    #end
    return self.__SendRecv('ixNet', 'remapIds', localIdList)
end
remove(objRef) click to toggle source
# File lib/ixnetwork.rb, line 234
def remove(objRef)
    return self.__SendRecv('ixNet', 'remove', objRef)
end
rollback() click to toggle source
# File lib/ixnetwork.rb, line 222
def rollback()
    return self.__SendRecv('ixNet', 'rollback')
end
setAsync() click to toggle source
# File lib/ixnetwork.rb, line 70
def setAsync()
    @_async = true;
    return self
end
setAttribute(objRef, name, value) click to toggle source
# File lib/ixnetwork.rb, line 238
def setAttribute(objRef, name, value)
    @_buffer = true
    return self.__SendRecv('ixNet', 'setAttribute', self.__CheckObjRef(objRef), name, value)
end
setDebug(debug) click to toggle source
# File lib/ixnetwork.rb, line 57
def setDebug(debug)
    @_debug = debug
    return self
end
setMultiAttribute(objRef, *args) click to toggle source
# File lib/ixnetwork.rb, line 243
def setMultiAttribute(objRef, *args)
    @_buffer = true
    return self.__SendRecv('ixNet', 'setMultiAttribute', self.__CheckObjRef(objRef), *args)
end
setSessionParameter(*args) click to toggle source
# File lib/ixnetwork.rb, line 194
def setSessionParameter(*args)
    if args.length % 2 == 0 then
        return self.__SendRecv('ixNet', 'setSessionParameter', *args)
    else
        raise IxNetError,"setSessionParameter requires an even number of name/value pairs"
    end
end
setTimeout(timeout) click to toggle source
# File lib/ixnetwork.rb, line 75
def setTimeout(timeout)
    @_timeout = timeout
    return self
end
wait(resultId) click to toggle source
# File lib/ixnetwork.rb, line 275
def wait(resultId)
    return self.__SendRecv('ixNet', 'wait', resultId)
end
writeTo(filename, *args) click to toggle source
# File lib/ixnetwork.rb, line 287
def writeTo(filename, *args)
    if args.any? { |word| '-ixNetRelative'.include?(word)} then
        return self.__SendRecv('ixNet', 'writeTo', filename,args.join("\02"))
    else
        return self.__CreateFileOnServer(filename)
    end
end