Exemple #1
0
def main():
    # Read the command-line arguments. The args object will contain
    # 4 properties, args.nsx_host, args.tcp_port, args.user, and
    # args.password.
    args = getargs.getargs()

    # Create a session using the requests library. For more information on
    # requests, see http://docs.python-requests.org/en/master/
    session = requests.session()

    # If your NSX API server is using its default self-signed certificate,
    # you will need the following line, otherwise the python ssl layer
    # will reject the server certificate. THIS IS UNSAFE and you should
    # normally verify the server certificate.
    session.verify = False

    # Set up the API connector and security context
    nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port)
    connector = connect.get_requests_connector(
        session=session, msg_protocol='rest', url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    security_context = create_user_password_security_context(
        args.user, args.password)
    connector.set_security_context(security_context)

    # Now any API calls we make should authenticate to NSX using
    # HTTP Basic Authentication. Let's get a list of all Transport Zones.
    transportzones_svc = TransportZones(stub_config)
    tzs = transportzones_svc.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(tzs)
def main():
    args = getargs.getargs()
    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Find all fabric nodes and print a summary of each node's
    # operational state
    all_raw_fns = api_client.fabric.Nodes.list()
    print("***** Showing summaries for %d fabric nodes" %
          all_raw_fns.result_count)
    all_fns = []
    for raw_fn in all_raw_fns.results:
        # Fabric Nodes are polymorphic, so convert to a concrete class
        node_type = raw_fn.convert_to(Node).resource_type
        if node_type == "HostNode":
            all_fns.append(raw_fn.convert_to(HostNode))
        elif node_type == "EdgeNode":
            all_fns.append(raw_fn.convert_to(EdgeNode))
    for fn in all_fns:
        print_node(fn)
        print_node_status(
            fn, api_client.fabric.nodes.Status.get(fn.id, source="realtime"))
        interfaces = api_client.fabric.nodes.network.Interfaces.list(fn.id)
        print("    Interfaces:")
        for interface in interfaces.results:
            if_stats = api_client.fabric.nodes.network.interfaces.Stats.get(
                fn.id, interface.interface_id)
            print_interface_and_stats(fn, interface, if_stats)
        print("")
Exemple #3
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # Create a transport zone, but intentionally pass an incorrect
    # overlay type, so we cause an error.
    new_tz = TransportZone(
        transport_type="zappa",  # invalid overlay type
        display_name="My transport zone",
        description="Transport zone for error handling demo",
        host_switch_name="hostswitch1")
    try:
        result_tz = api_client.TransportZones.create(new_tz)
    except Error as ex:
        print ex
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)
        # You can also extract the HTTP response code
        print("HTTP response code %d" %
              api_client._stub_config._response_extractor.get_http_status())
Exemple #4
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)
    # Instantiate all the services we'll need.
    fn_svc = fabric_client.Nodes(stub_config)
    fnstatus_svc = nodes_client.Status(stub_config)
    interfaces_svc = network_client.Interfaces(stub_config)
    interface_stats_svc = interfaces_client.Stats(stub_config)

    # Find all fabric nodes and print a summary of each node's
    # operational state
    all_raw_fns = fn_svc.list()
    print("***** Showing summaries for %d fabric nodes" %
          all_raw_fns.result_count)
    all_fns = []
    for raw_fn in all_raw_fns.results:
        # Fabric Nodes are polymorphic, so convert to a concrete class
        node_type = raw_fn.convert_to(Node).resource_type
        if node_type == "HostNode":
            all_fns.append(raw_fn.convert_to(HostNode))
        elif node_type == "EdgeNode":
            all_fns.append(raw_fn.convert_to(EdgeNode))
    for fn in all_fns:
        print_node(fn)
        print_node_status(fn, fnstatus_svc.get(fn.id, source="realtime"))
        interfaces = interfaces_svc.list(fn.id)
        print("    Interfaces:")
        for interface in interfaces.results:
            if_stats = interface_stats_svc.get(fn.id, interface.interface_id)
            print_interface_and_stats(fn, interface, if_stats)
        print("")
Exemple #5
0
def main():
    args = getargs.getargs()
    api_client = auth.create_nsx_policy_api_client(args.user,
                                                   args.password,
                                                   args.nsx_host,
                                                   args.tcp_port,
                                                   auth_type=auth.SESSION_AUTH)

    while True:
        n = 0
        last = time.time()
        while time.time() - last < 1.0:
            call_api_with_retry(api_client.Infra.get)
            n += 1
            # API calls that take arguments:
            #
            # Since we use the python apply() method, you need
            # to pass the callable and its arguments as a list.
            # The usual way to call this API would be:
            # api_client.infra.Domains.get("default")
            #
            call_api_with_retry(api_client.infra.Domains.get, "default")
            n += 1

        print("%d calls/sec" % n)
Exemple #6
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # Create the service we'll need.
    transportzones_svc = TransportZones(stub_config)

    # Create a transport zone, but intentionally pass an incorrect
    # overlay type, so we cause an error.
    new_tz = TransportZone(
        transport_type="zappa",  # invalid overlay type
        display_name="My transport zone",
        description="Transport zone for error handling demo",
        host_switch_name="hostswitch1"
    )
    try:
        result_tz = transportzones_svc.create(new_tz)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)
def main():
    args = getargs.getargs()
    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)
    pp = PrettyPrinter()

    # Find all logical switches and show statistics for each.
    all_ls = api_client.LogicalSwitches.list()
    print("***** Showing statistics for %d logical switches" %
          all_ls.result_count)
    for ls in all_ls.results:
        print("Logical switch %s (id %s)" % (ls.display_name, ls.id))
        # Retrieve the statistics for the switch
        stats = api_client.logical_switches.Statistics.get(ls.id)
        print_l2_stats(stats)
        print("")

    # Find all logical ports and show statistics for each.
    all_lps = api_client.LogicalPorts.list()
    print("***** Showing statistics for %d logical ports" %
          all_lps.result_count)
    for lp in all_lps.results:
        # Show the port's name and id, the logical switch it's on,
        # and what it's attached to, if anything.
        print("Logical port %s (id %s)" % (lp.display_name, lp.id))
        print(" On switch %s" % lp.logical_switch_id)
        attachment = ("None" if lp.attachment is None else "%s %s" %
                      (lp.attachment.attachment_type, lp.attachment.id))
        print(" Attached to: %s" % attachment)

        # Retrieve the statistics for the port.
        if lp.attachment and lp.attachment.attachment_type == "VIF":
            stats = api_client.logical_ports.Statistics.get(lp.id,
                                                            source="cached")
        else:
            stats = api_client.logical_ports.Statistice.get(lp.id)
        print_l2_stats(stats)
        print("")

    # Find all logical router ports and show statistics for each.
    all_lrps = api_client.LogicalRouterPorts.list()
    print("***** Showing statistics for %d logical router ports" %
          all_lrps.result_count)
    for lrp in all_lrps.results:
        # Show the port's type, name and id and what it's attached to,
        # if anything.
        # Since logical router ports are polymorphic, convert to the
        # base class so we can retrieve the type information.
        lrp = lrp.convert_to(LogicalRouterPort)
        print("%s %s (id %s)" % (lrp.resource_type, lrp.display_name, lrp.id))
        stats = api_client.logical_router_ports.Statistics.get(lrp.id,
                                                               source="cached")
        print_lrp_stats(stats)
Exemple #8
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    t = api_client.telemetry.Config.get()
    pp.pprint(t)
Exemple #9
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # First, list all switching profiles.
    swps = api_client.SwitchingProfiles.list()
    print("Initial list of switching profiles - %d profiles" %
          swps.result_count)
    # Since switching profiles are polymorphic, we need to convert
    # each profile to its concrete class
    for raw_profile in swps.results:
        concrete_type_name = raw_profile.to_dict()["resource_type"]
        concrete_type = getattr(model_client, concrete_type_name)
        profile = raw_profile.convert_to(concrete_type)
        pp.pprint(profile)

    # Create a new QOS switching profile
    new_profile = QosSwitchingProfile(class_of_service=None,
                                      dscp=None,
                                      shaper_configuration=None,
                                      description="",
                                      display_name="My QoS Policy",
                                      tags=[])
    result_profile = api_client.SwitchingProfiles.create(
        new_profile).convert_to(QosSwitchingProfile)
    print("Switching profile created. id is %s" % result_profile.id)

    # Save the id, which uniquely identifies the resource we created.
    profile_id = result_profile.id

    # Read that switching profile.
    read_profile = api_client.SwitchingProfiles.get(profile_id).convert_to(
        QosSwitchingProfile)
    print("Re-read the QOS switching profile")
    pp.pprint(read_profile)

    # Delete the switching profile
    api_client.SwitchingProfiles.delete(profile_id)
    print("After deleting QOS switching profile")
Exemple #10
0
def main():
    # Read the command-line arguments. The args object will contain
    # 3 properties, args.nsx_host, args.tcp_port, and args.refresh_token.
    args = getargs.getargs()
    if args.refresh_token is None:
        sys.stderr.write(
            "Error: you must provide a refresh token for this example\n")
        sys.exit(1)

    # Obtain a token to use for authenticating to the NSX Manager. We
    # just use the python requests library directly.
    params = {"refresh_token", args.refresh_token}
    resp = requests.post("%s?refresh_token=%s" %
                         (VMC_AUTH_URL, args.refresh_token))
    resp.raise_for_status()  # Will raise exception if error
    resp_json = resp.json()
    # This is the access token you will pass with all NSX Manager API requests
    access_token = resp_json["access_token"]

    # Create a session using the requests library. For more information on
    # requests, see http://docs.python-requests.org/en/master/
    session = requests.session()
    # Arrange for the requests library to send the bearer token header
    # with each request.
    session.headers["Authorization"] = "Bearer %s" % access_token

    # If your NSX API server is using its default self-signed certificate,
    # you will need the following line, otherwise the python ssl layer
    # will reject the server certificate. THIS IS UNSAFE and you should
    # normally verify the server certificate.
    session.verify = False

    # Set up the API connector
    nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port)
    resp = session.get("%s/api/v1/cluster" % nsx_url)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)

    # Let's get a list of all Domains
    domains_svc = Domains(stub_config)
    domains = domains_svc.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(domains)
Exemple #11
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)
    # List all of the fabric nodes
    result = api_client.fabric.Nodes.list()

    # Iterate over the results
    for vs in result.results:
        fn = vs.convert_to(Node)
        print("Type: %s, Name: %s, id: %s" %
              (fn.resource_type, fn.display_name, fn.id))
        fn_status = status_svc.get(fn.id)
        print("    mp conn: %s, cp conn: %s" %
              (fn_status.mpa_connectivity_status,
               fn_status.lcp_connectivity_status))
Exemple #12
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # Create an IP Pool
    new_pool = IpPool(display_name="My IP Pool",
                      description="IP Pool for IP Pool demo",
                      subnets=[
                          IpPoolSubnet(cidr="192.168.1.0/24",
                                       allocation_ranges=[
                                           IpPoolRange(start="192.168.1.10",
                                                       end="192.168.1.20")
                                       ])
                      ])
    result_pool = api_client.pools.IpPools.create(new_pool)
    print("IP Pool created. id is %s" % result_pool.id)

    # Allocate an IP address
    alloc = AllocationIpAddress(allocation_id="192.168.1.11")
    api_client.pools.IpPools.allocateorrelease(
        pool_id=result_pool.id,
        allocation_ip_address=alloc,
        action=api_client.pools.IpPools.ALLOCATEORRELEASE_ACTION_ALLOCATE)

    # Show the allocations
    allocs = api_client.pools.ip_pools.Allocations.list(result_pool.id)
    pp.pprint(allocs)

    # Deallocate the IP address
    api_client.pools.IpPools.allocateorrelease(
        pool_id=result_pool.id,
        allocation_ip_address=alloc,
        action=api_client.pools.IpPools.ALLOCATEORRELEASE_ACTION_RELEASE)
Exemple #13
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    # Create the services we'll need.
    fabricnodes_svc = Nodes(stub_config)
    status_svc = Status(stub_config)

    # List all of the fabric nodes
    result = fabricnodes_svc.list()

    # Iterate over the results
    for vs in result.results:
        fn = vs.convert_to(Node)
        print("Type: %s, Name: %s, id: %s" %
              (fn.resource_type, fn.display_name, fn.id))
        fn_status = status_svc.get(fn.id)
        print("    mp conn: %s, cp conn: %s" %
              (fn_status.mpa_connectivity_status,
               fn_status.lcp_connectivity_status))
def main():
    # Read the command-line arguments. The args object will contain
    # 4 properties, args.nsx_host, args.tcp_port, args.user, and
    # args.password.
    args = getargs.getargs()

    # Create a session using the requests library. For more information on
    # requests, see http://docs.python-requests.org/en/master/
    session = requests.session()

    # If your NSX API server is using its default self-signed certificate,
    # you will need the following line, otherwise the python ssl layer
    # will reject the server certificate. THIS IS UNSAFE and you should
    # normally verify the server certificate.
    session.verify = False

    # Set up the API connector and security context
    nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port)
    connector = connect.get_requests_connector(session=session,
                                               msg_protocol='rest',
                                               url=nsx_url)
    stub_config = StubConfigurationFactory.new_std_configuration(connector)
    # Arrange for the Authorization header to be sent with every request.
    # We do this because the vapi libraries do not currently directly
    # support authentication with this header payload.
    auth_str = base64.b64encode("%s:%s" % (args.user, args.password))
    session.headers["Authorization"] = "Remote %s" % auth_str
    stub_factory = nsx_client.StubFactory(stub_config)
    api_client = ApiClient(stub_factory)

    # Now any API calls we make should authenticate to NSX by
    # providing an Authorization header with the correct value.
    # Let's get a list of all Transport Zones.
    tzs = api_client.TransportZones.list()
    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()
    pp.pprint(tzs)
Exemple #15
0
def main():
    args = getargs.getargs()

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    api_client = auth.create_nsx_api_client(args.user,
                                            args.password,
                                            args.nsx_host,
                                            args.tcp_port,
                                            auth_type=auth.SESSION_AUTH)

    # First, list all transport zones. If your NSX installation has
    # just been installed, this should return an empty list.
    tzs = api_client.TransportZones.list()
    print("Initial list of transport zones - %d zones" % tzs.result_count)
    pp.pprint(tzs)

    # Create a transport zone.
    new_tz = TransportZone(
        transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
        display_name="My transport zone",
        description="Transport zone for basic create/read/update/delete demo",
        host_switch_name="hostswitch1")
    result_tz = api_client.TransportZones.create(new_tz)
    print("Transport zone created. id is %s" % result_tz.id)

    # Save the id, which uniquely identifies the resource we created.
    tz_id = result_tz.id

    # Read that transport zone.
    read_tz = api_client.TransportZones.get(tz_id)
    print("Re-read the transport zone")
    pp.pprint(read_tz)

    # List all transport zones again. The newly created transport
    # zone will be in the list.
    tzs = api_client.TransportZones.list()
    print("Updated list of transport zones - %d zones" % tzs.result_count)
    pp.pprint(tzs)

    print("You can now examine the list of transport zones in the")
    print("NSX manager if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Update the transport zone.
    read_tz.description = "Updated description for transport zone"
    updated_tz = api_client.TransportZones.update(tz_id, read_tz)
    print("After updating description. Note that the revision property is "
          "automatically updated.")
    pp.pprint(updated_tz)

    # Update the transport zone again.
    #
    # Note that NSX insists that clients always operate on up-to-date
    # data. To enforce this, every resource in NSX has a "revision"
    # property that is automatically maintained by NSX and is
    # incremented each time the resource is updated. If a client
    # submits an update operation, and the revision property in the
    # payload provided by the client does not match the revision
    # stored on the server, another update must have happened since
    # the client last read the resource, and the client's copy is
    # therefore stale.  In this case, the server will return a 412
    # Precondition Failed error. This is intended to prevent clients
    # from clobbering each other's updates. To recover from this
    # error, the client must re-read the resource, apply any desired
    # updates, and perform another update operation.
    updated_tz.description = "Updated description again for transport zone"
    updated_tz = api_client.TransportZones.update(tz_id, updated_tz)
    print("After updating description again.")
    pp.pprint(updated_tz)

    # Delete the transport zone.
    api_client.TransportZones.delete(tz_id)
    print("After deleting transport zone")

    # Now if we try to read the transport zone, we should get a
    # 404 Not Found error. This example also shows how you can
    # check for and handle specific errors from the NSX API.
    try:
        read_tz = api_client.TransportZones.get(tz_id)
    except NotFound:
        print("Transport zone is gone, as expected")
Exemple #16
0
def main():
    args = getargs.getargs()

    api_client = auth.create_nsx_policy_api_client(
        args.user, args.password, args.nsx_host, args.tcp_port,
        auth_type=auth.SESSION_AUTH)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # First, retrieve /infra and the domains in /infra. If your NSX
    # policy service has just been installed, there will be no domains.
    infra = api_client.Infra.get()
    print("Initial state of /infra")
    pp.pprint(infra)
    domains = api_client.infra.Domains.list()
    print("All domains: total of %d domains" % domains.result_count)

    # Create a domain with a random id
    domain_id = "Domain_%d" % random.choice(range(10000))
    domain = Domain(
        id=domain_id,
        display_name=domain_id,
    )
    try:
        api_client.infra.Domains.update(domain_id, domain)
        print("Domain %s created." % domain_id)
    except Error as ex:
        api_error = ex.data.convert_to(ApiError)
        print("An error occurred: %s" % api_error.error_message)

    # Read that domain
    read_domain = api_client.infra.Domains.get(domain_id)
    print("Re-read the domain")
    pp.pprint(read_domain)

    # List all domains again. The newly created domain
    # will be in the list.
    domains = api_client.infra.Domains.list()
    print("All domains: total of %d domains" % domains.result_count)

    print("You can now examine the infra and domains in the")
    print("NSX policy service if you wish. Press enter to continue.")
    sys.stdin.readline()

    # Update the domain. The NSX policy API only supports a create API,
    # so to update an existing resource, just call the create method
    # again, passing the properties you wish to update.
    read_domain.description = "Updated description for transport zone"
    api_client.infra.Domains.update(domain_id, read_domain)

    # Re-read the domain
    read_domain = api_client.infra.Domains.get(domain_id)
    print("Domain after updating")
    pp.pprint(read_domain)

    # Delete the domain
    api_client.infra.Domains.delete(domain_id)
    print("After deleting domain")

    # Now if we try to read the domain, we should get a
    # 404 Not Found error. This example also shows how you can
    # check for and handle specific errors from the NSX Policy API.
    try:
        read_domain = api_client.infra.Domains.get(domain_id)
    except NotFound:
        print("Domain is gone, as expected")
Exemple #17
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    # Create a pretty printer to make the output look nice.
    pp = PrettyPrinter()

    # Create the services we'll need.
    transportzones_svc = TransportZones(stub_config)
    logicalswitches_svc = LogicalSwitches(stub_config)
    logicalports_svc = LogicalPorts(stub_config)
    nsgroups_svc = NsGroups(stub_config)
    efflports_svc = EffectiveLogicalPortMembers(stub_config)

    # Create a transport zone and logical switch. We only
    # need these so we can create logical ports. They aren't
    # part of the demo.
    tz = TransportZone(transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
                       display_name="Tagging Demo Transport Zone",
                       description="Transport zone for tagging demo",
                       host_switch_name="hostswitch")
    tz = transportzones_svc.create(tz)
    ls = LogicalSwitch(
        transport_zone_id=tz.id,
        admin_state=LogicalSwitch.ADMIN_STATE_UP,
        replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
        display_name="ls-tag-demo",
    )
    ls = logicalswitches_svc.create(ls)

    # First, create a new group whose members are any logical
    # ports with a tag scope of "color" and tag value of "green"
    group = NSGroup(
        display_name="Green Logical Ports",
        description="All logical ports with scope=color and tag=green",
        membership_criteria=[
            NSGroupTagExpression(resource_type="NSGroupTagExpression",
                                 target_type="LogicalPort",
                                 scope_op="EQUALS",
                                 scope="color",
                                 tag_op="EQUALS",
                                 tag="green")
        ])
    green_group = nsgroups_svc.create(group)

    # Now create another group for color:yellow logical ports.
    group = NSGroup(
        display_name="Yellow Logical Ports",
        description="All logical ports with scope=color and tag=yellow",
        membership_criteria=[
            NSGroupTagExpression(resource_type="NSGroupTagExpression",
                                 target_type="LogicalPort",
                                 scope_op="EQUALS",
                                 scope="color",
                                 tag_op="EQUALS",
                                 tag="yellow")
        ])
    yellow_group = nsgroups_svc.create(group)

    # Now get the list of effective members (that is, logical ports
    # with color:green). There should be no effective members yet.
    print("Before creating any lports:")
    print_group_effective_members("green group",
                                  efflports_svc.list(green_group.id))
    print_group_effective_members("yellow group",
                                  efflports_svc.list(yellow_group.id))
    print("")

    # Create a logical port with color:green
    lport = LogicalPort(display_name="tagging-demo-lp1",
                        admin_state=LogicalPort.ADMIN_STATE_UP,
                        logical_switch_id=ls.id,
                        tags=[Tag(scope="color", tag="green")])
    lport = logicalports_svc.create(lport)
    print("Logical port for this test has id %s" % lport.id)
    print("")

    # Group membership is computed asynchronously in the NSX
    # manager. Wait a bit.
    time.sleep(2.0)

    # Find the effective members of the green and yellow groups.
    # Notice that the logical port is in the green group.
    print("After creating green lport:")
    print_group_effective_members("green group",
                                  efflports_svc.list(green_group.id))
    print_group_effective_members("yellow group",
                                  efflports_svc.list(yellow_group.id))
    print("")

    # Now modify the logical port's color to yellow.
    lport = logicalports_svc.get(lport.id)
    lport.tags = [Tag(scope="color", tag="yellow")]
    logicalports_svc.update(lport.id, lport)

    # Wait for group recalculation
    time.sleep(2.0)

    # Find the effective members of the green and yellow groups.
    # Notice that the logical port is now in the yellow group
    # and no longer in the green group.
    print("After changing lport color to yellow:")
    print_group_effective_members("green group",
                                  efflports_svc.list(green_group.id))
    print_group_effective_members("yellow group",
                                  efflports_svc.list(yellow_group.id))
    print("")

    # Now clear the tag
    lport = logicalports_svc.get(lport.id)
    lport.tags = []
    logicalports_svc.update(lport.id, lport)

    # Wait for group recalculation
    time.sleep(2.0)

    # The port should be in neither group
    print("After removing lport color tag:")
    print_group_effective_members("green group",
                                  efflports_svc.list(green_group.id))
    print_group_effective_members("yellow group",
                                  efflports_svc.list(yellow_group.id))
    print("")

    print("Press enter to delete all resources created for this example.")
    sys.stdin.readline()

    # Delete all resources we created.
    logicalports_svc.delete(lport.id)
    nsgroups_svc.delete(green_group.id)
    nsgroups_svc.delete(yellow_group.id)
    logicalswitches_svc.delete(ls.id)
    transportzones_svc.delete(tz.id)
Exemple #18
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    pp = PrettyPrinter()

    # Instantiate all the services we'll need.
    ls_svc = LogicalSwitches(stub_config)
    ls_statistics_svc = logical_switches_client.Statistics(stub_config)
    lp_svc = LogicalPorts(stub_config)
    lp_statistics_svc = logical_ports_client.Statistics(stub_config)
    lrp_svc = LogicalRouterPorts(stub_config)
    lrp_statistics_svc = statistics_client.Summary(stub_config)

    # Find all logical switches and show statistics for each.
    all_ls = ls_svc.list()
    print("***** Showing statistics for %d logical switches" %
          all_ls.result_count)
    for ls in all_ls.results:
        print("Logical switch %s (id %s)" % (ls.display_name, ls.id))
        # Retrieve the statistics for the switch
        stats = ls_statistics_svc.get(ls.id)
        print_l2_stats(stats)
        print("")

    # Find all logical ports and show statistics for each.
    all_lps = lp_svc.list()
    print("***** Showing statistics for %d logical ports" %
          all_lps.result_count)
    for lp in all_lps.results:
        # Show the port's name and id, the logical switch it's on,
        # and what it's attached to, if anything.
        print("Logical port %s (id %s)" % (lp.display_name, lp.id))
        print(" On switch %s" % lp.logical_switch_id)
        attachment = ("None" if lp.attachment is None else
                      "%s %s" % (lp.attachment.attachment_type,
                                 lp.attachment.id))
        print(" Attached to: %s" % attachment)

        # Retrieve the statistics for the port.
        if lp.attachment and lp.attachment.attachment_type == "VIF":
            stats = lp_statistics_svc.get(lp.id, source="realtime")
        else:
            stats = lp_statistics_svc.get(lp.id)
        print_l2_stats(stats)
        print("")

    # Find all logical router ports and show statistics for each.
    all_lrps = lrp_svc.list()
    print("***** Showing statistics for %d logical router ports" %
          all_lrps.result_count)
    for lrp in all_lrps.results:
        # Show the port's type, name and id and what it's attached to,
        # if anything.
        # Since logical router ports are polymorphic, convert to the
        # base class so we can retrieve the type information.
        lrp = lrp.convert_to(LogicalRouterPort)
        print("%s %s (id %s)" % (lrp.resource_type, lrp.display_name, lrp.id))
        stats = lrp_statistics_svc.get(lrp.id, source="cached")
        print_lrp_stats(stats)
Exemple #19
0
def main():
    args = getargs.getargs()
    stub_config = auth.get_session_auth_stub_config(args.user, args.password,
                                                    args.nsx_host,
                                                    args.tcp_port)

    pp = PrettyPrinter()

    # Instantiate all the services we'll need.
    transportzones_svc = TransportZones(stub_config)
    logicalswitches_svc = LogicalSwitches(stub_config)
    logicalrouters_svc = LogicalRouters(stub_config)
    logicalrouterports_svc = LogicalRouterPorts(stub_config)
    logicalports_svc = LogicalPorts(stub_config)
    fwsections_svc = Sections(stub_config)

    # Create a transport zone
    new_tz = TransportZone(
        transport_type=TransportZone.TRANSPORT_TYPE_OVERLAY,
        display_name="Two Tier App Demo Transport Zone",
        description="Transport zone for two-tier app demo",
        host_switch_name="hostswitch"
    )
    demo_tz = transportzones_svc.create(new_tz)

    # Create a logical switch for the db tier
    new_ls = LogicalSwitch(
        transport_zone_id=demo_tz.id,
        admin_state=LogicalSwitch.ADMIN_STATE_UP,
        replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
        display_name="ls-db",
    )
    db_ls = logicalswitches_svc.create(new_ls)

    # Create a logical switch for the web tier
    new_ls = LogicalSwitch(
        transport_zone_id=demo_tz.id,
        admin_state=LogicalSwitch.ADMIN_STATE_UP,
        replication_mode=LogicalSwitch.REPLICATION_MODE_MTEP,
        display_name="ls-web",
    )
    web_ls = logicalswitches_svc.create(new_ls)

    # Create a logical router that will route traffic between
    # the web and db tiers
    new_lr = LogicalRouter(
        router_type=LogicalRouter.ROUTER_TYPE_TIER1,
        display_name="lr-demo",
        failover_mode=LogicalRouter.FAILOVER_MODE_PREEMPTIVE
    )
    lr = logicalrouters_svc.create(new_lr)

    # Create a logical port on the db and web logical switches. We
    # will attach the logical router to those ports so that it can
    # route between the logical switches.
    # Logical port on the db logical switch
    new_lp = LogicalPort(
        admin_state=LogicalPort.ADMIN_STATE_UP,
        logical_switch_id=db_ls.id,
        display_name="dbTierUplinkToRouter"
    )
    db_port_on_ls = logicalports_svc.create(new_lp)

    # Logical port on the web logical switch
    new_lp = LogicalPort(
        admin_state=LogicalPort.ADMIN_STATE_UP,
        logical_switch_id=web_ls.id,
        display_name="webTierUplinkToRouter"
    )
    web_port_on_ls = logicalports_svc.create(new_lp)

    # Populate a logical router downlink port payload and configure
    # the port with the CIDR 192.168.1.1/24. We will attach this
    # port to the db tier's logical switch.
    new_lr_port = LogicalRouterDownLinkPort(
        subnets=[IPSubnet(ip_addresses=["192.168.1.1"], prefix_length=24)],
        linked_logical_switch_port_id=ResourceReference(
            target_id=db_port_on_ls.id),
        resource_type="LogicalRouterDownLinkPort",
        logical_router_id=lr.id
    )
    # Create the downlink port
    lr_port_for_db_tier = logicalrouterports_svc.create(new_lr_port)
    # Convert to concrete type
    lr_port_for_db_tier = lr_port_for_db_tier.convert_to(
        LogicalRouterDownLinkPort)

    # Populate a logical router downlink port payload and configure
    # the port with the CIDR 192.168.2.1/24. We will attach this
    # port to the web tier's logical switch.
    new_lr_port = LogicalRouterDownLinkPort(
        subnets=[IPSubnet(ip_addresses=["192.168.2.1"], prefix_length=24)],
        linked_logical_switch_port_id=ResourceReference(
            target_id=web_port_on_ls.id),
        resource_type="LogicalRouterDownLinkPort",
        logical_router_id=lr.id
    )
    # Create the downlink port
    lr_port_for_web_tier = logicalrouterports_svc.create(new_lr_port)
    lr_port_for_web_tier = lr_port_for_web_tier.convert_to(
        LogicalRouterDownLinkPort)

    # Now establish a firewall policy that only allows MSSQL
    # server traffic and ICMP traffic in and out of the db tier's
    # logical switch.

    # Create 3 firewall rules. The first will allow traffic used
    # by MS SQL Server to pass. This rule references a built-in
    # ns service group that includes all the common ports used by
    # the MSSQL Server. The ID is common to all NSX installations.
    MSSQL_SERVER_NS_GROUP_ID = "5a6d380a-6d28-4e3f-b705-489f463ae6ad"
    ms_sql_rule = FirewallRule(
        action=FirewallRule.ACTION_ALLOW,
        display_name="Allow MSSQL Server",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6,
        services=[
            FirewallService(
                target_type="NSServiceGroup",
                target_id=MSSQL_SERVER_NS_GROUP_ID
            )
        ]
    )

    # The second rule will allow ICMP echo requests and responses.
    ICMP_ECHO_REQUEST_NS_SVC_ID = "5531a880-61aa-42cc-ba4b-13b9ea611e2f"
    ICMP_ECHO_REPLY_NS_SVC_ID = "c54b2d86-6327-41ff-a3fc-c67171b6ba63"
    icmp_rule = FirewallRule(
        action=FirewallRule.ACTION_ALLOW,
        display_name="Allow ICMP Echo",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6,
        services=[
            FirewallService(
                target_type="NSService",
                target_id=ICMP_ECHO_REQUEST_NS_SVC_ID
            ),
            FirewallService(
                target_type="NSService",
                target_id=ICMP_ECHO_REPLY_NS_SVC_ID
            )
        ]
    )

    # The third rule will drop all traffic not passed by the previous
    # rules.
    block_all_rule = FirewallRule(
        action=FirewallRule.ACTION_DROP,
        display_name="Drop all",
        ip_protocol=FirewallRule.IP_PROTOCOL_IPV4_IPV6
    )

    # Add all rules to a new firewall section and create the section.
    rule_list = FirewallSectionRuleList(
        rules=[ms_sql_rule, icmp_rule, block_all_rule],
        section_type=FirewallSection.SECTION_TYPE_LAYER3,
        stateful=True,
        display_name="MSSQL Server",
        description="Only allow MSSQL server traffic"
    )
    demo_section = fwsections_svc.createwithrules(
        rule_list, None, operation="insert_top")

    # Re-read the firewall section so that we are operating on up-to-date
    # data.
    section = fwsections_svc.get(demo_section.id)

    # Make the firewall section apply to the db tier logical
    # switch. This enables the firewall policy on all logical
    # ports attached to the db tier logical switch.
    section.applied_tos = [
        ResourceReference(target_id=db_ls.id,
                          target_type="LogicalSwitch")
    ]
    fwsections_svc.update(section.id, section)

    print("At this point you may attach VMs for the db tier to the db")
    print("logical switch and VMs for the web tier to the web logical")
    print("switch. The network interfaces should be configured as")
    print("follows:")
    print("db tier:")
    print("    IP address: in the range 192.168.1.2-254")
    print("    Netmask: 255.255.255.0")
    print("    Default route: 192.168.1.1")
    print("web tier:")
    print("    IP address: in the range 192.168.2.2-254")
    print("    Netmask: 255.255.255.0")
    print("    Default route: 192.168.2.1")
    print("Logical switch IDs:")
    print("    %s: %s" % (db_ls.display_name, db_ls.id))
    print("    %s: %s" % (web_ls.display_name, web_ls.id))
    print("Transport zone: %s: %s" % (demo_tz.display_name, demo_tz.id))

    print("Press enter to delete all resources created for this example.")
    sys.stdin.readline()

    fwsections_svc.delete(section.id, cascade=True)
    logicalrouterports_svc.delete(lr_port_for_web_tier.id)
    logicalrouterports_svc.delete(lr_port_for_db_tier.id)
    logicalports_svc.delete(web_port_on_ls.id)
    logicalports_svc.delete(db_port_on_ls.id)
    logicalrouters_svc.delete(lr.id)
    logicalswitches_svc.delete(web_ls.id)
    logicalswitches_svc.delete(db_ls.id)
    transportzones_svc.delete(demo_tz.id)