Ejemplo n.º 1
0
    def setUp(self):
        """
        Test initialisation.

        Returns
        -------
            No return value.

        Raises
        ------
        unittest.SkipTest
            If the ISCSI_CONFIG file does not exist.
        """
        super().setUp()
        self.iscsi_config_path = self.properties.get_property(
            'oci-iscsi-config')
        self.iscsiadm_path = '/sbin/iscsiadm'
        if not os.path.exists(self.iscsi_config_path):
            raise unittest.SkipTest("%s not present" % self.iscsi_config_path)
        try:
            self.vol_name_prefix = self.properties.get_property(
                'volume-name-prefix')
        except Exception:
            self.vol_name_prefix = 'auto-'
        self.volume_name = self.vol_name_prefix + uuid.uuid4().hex
        try:
            self.waittime = int(self.properties.get_property('waittime'))
        except Exception:
            self.waittime = 20
        try:
            self.volume_size = self.properties.get_property('volume-size')
        except Exception:
            self.volume_size = '53'
        try:
            self.compartment_name = self.properties.get_property(
                'compartment-name')
        except Exception as e:
            self.compartment_name = 'ImageDev'
        self._volumes_created = list()
        self.oci_session = oci_api.OCISession()
Ejemplo n.º 2
0
def main():
    """
    Main

    Returns
    -------
        int
            0 on success, 1 otherwise.
    """
    args = parse_args()

    if args.list_servers:
        # print the list of known STUN servers and exit
        for server in STUN_SERVERS:
            print server
        sys.exit(0)

    external_ip = None
    external_ips = []
    if args.instance_id is None and args.sourceip == '0.0.0.0' and \
       args.stun_server is None:
        try:
            _found = False
            if oci_api.HAVE_OCI_SDK:
                _this_instance = oci_api.OCISession().this_instance()
                _all_p_ips = _this_instance.all_public_ips()
                if len(_all_p_ips) > 0:
                    _found = True
                    external_ips.append(_all_p_ips[0])
            if not _found:
                # fall back to STUN if we did not find any
                _p_ip = get_ip_info(source_ip='0.0.0.0')[1]
                if _p_ip is not None:
                    external_ips.append(_p_ip)
        except Exception as e:
            stun_log.error("%s\n" % e)

    if (external_ip is None or args.all) \
            and (oci_api.HAVE_OCI_SDK or args.instance_id is not None):
        # try the OCI APIs first

        try:
            sess = oci_api.OCISession()
            if args.instance_id is not None:
                inst = sess.get_instance(args.instance_id)
            else:
                inst = sess.this_instance()

            if inst is None:
                stun_log.error("Instance not found: %s\n" % args.instance_id)
                sys.exit(1)
            for vnic in inst.all_vnics():
                external_ip = vnic.get_public_ip()
                if vnic.is_primary() and external_ip not in external_ips:
                    external_ips.insert(0, external_ip)
                else:
                    if external_ip is None:
                        continue
                    if args.all:
                        if external_ip in external_ips:
                            continue
                        external_ips.append(external_ip)
                    else:
                        break
        except OCISDKError:
            if args.instance_id is not None:
                stun_log.error(
                    "The OCI Python SDK must be installed and configured when "
                    "using the --instance-id option.\n")
                sys.exit(1)

    if external_ip is None or args.all:
        # fall back to pystun
        external_ip = get_ip_info(source_ip=args.sourceip,
                                  stun_host=args.stun_server)[1]

        if args.all and external_ip not in external_ips:
            external_ips.append(external_ip)

    if args.all:
        if args.json:
            print json.dumps({'publicIps': external_ips})
        elif args.get:
            print external_ips
        else:
            print "Public IP addresses: "
            print "  Primary public IP: %s " % external_ips[0]
            if len(external_ips) < 2:
                print "  Other public IP(s): None"
                return 0
            print "  Other public IP(s):"
            for ip in external_ips[1:]:
                print "    %s" % ip
        return 0
    elif external_ip is not None:
        if args.json:
            print json.dumps({'publicIp': external_ip})
        elif args.get:
            print external_ip
        else:
            print "Public IP address: %s" % external_ip

        return 0
    else:
        stun_log.info("No public IP address found.\n")
        return 1
def main():
    """
    Main

    Returns
    -------
        int
            0 on success, 1 otherwise.
    """
    args = parse_args()

    # needs the OCI SDK installed and configured
    try:
        sess = oci_api.OCISession()
        # sess = oci_utils.oci_api.OCISession()
    except OCISDKError as e:
        __logger.error("Need OCI Service to inspect the networks.\n"
                       "Make sure to install and configure "
                       "OCI Python SDK (python36-oci-sdk)\n %s" % str(e))
        return 1

    comps = []
    if args.compartment:
        comp = sess.get_compartment(ocid=args.compartment)
        if comp is None:
            __logger.error("Compartment [%s] not found\n" % args.compartment)
            return 1
        comps.append(comp)
    else:
        comp = sess.all_compartments()
        __logger.debug('no compartement specified, requesting all, got (%d)' %
                       len(comp))
        comps.extend(comp)

    if len(comps) == 0:
        __logger.error("No Compartment found\n")
        return 1

    vcns = []
    if args.vcn:
        if args.vcn.startswith('ocid1.vcn.oc1.'):
            vcn = sess.get_vcn(args.vcn)
            if vcn is not None:
                vcns.append(vcn)
        else:
            vcn = sess.find_vcns(args.vcn)
            if vcn is not None:
                vcns.extend(vcn)
        if len(vcns) == 0:
            __logger.error("VCN not found: %s\n" % args.vcn)
            return 1
    else:
        # get all vcns for the compartment.
        for comp in comps:
            comp_vcns = comp.all_vcns()
            if __logger.isEnabledFor(logging.DEBUG):
                __logger.debug('Requesting VCNs of [%s], got (%d)' %
                               (comp.get_display_name(), len(comp_vcns)))
            for vcn in comp_vcns:
                vcn.set_compartment_name(comp.get_display_name())
            vcns += comp_vcns

    if len(vcns) == 0:
        if args.vcn is not None:
            __logger.error("VCN not found: %s\n" % args.vcn)
        else:
            __logger.error("No VCN information found")
        return 1

    comp_ocid = None
    for vcn in vcns:
        _compartment = vcn.get_compartment()
        if _compartment is None:
            __logger.error("no compartment returned for VCN %s\n" % str(vcn))
            continue
        if _compartment.get_ocid() != comp_ocid:
            print("")
            print("Compartment: %s (%s)" %
                  (_compartment.get_display_name(), _compartment.get_ocid()))
            comp_ocid = _compartment.get_ocid()
        print("")
        print("  vcn: %s (%s)" % (vcn.get_display_name(), vcn.get_ocid()))
        sll = vcn.all_security_lists()
        for _, value in list(sll.items()):
            value.print_security_list("    ")

        for subnet in vcn.all_subnets():
            print("")
            print("     Subnet: %s (%s)" %
                  (subnet.get_display_name(), subnet.get_ocid()))
            print("                Availibility domain: %s" %
                  subnet.get_availability_domain())
            print("                Cidr_block: %s" % subnet.get_cidr_block())
            print("                DNS Domain Name: %s" %
                  subnet.get_domain_name())

            for sl_id in subnet.get_security_list_ids():
                try:
                    sll.get(sl_id).print_security_list("       ")
                except Exception as e:
                    __logger.error("The security list %s is not in the VCN's "
                                   "list. \nException:%s" % (sl_id, e))
            '''
            vnics = subnet.all_vnics()
            for vnic in vnics:
                primary = "sec"
                if vnic.is_primary():
                    primary = "primary"
                print "      Vnic: %s(%s)(%s)" % (vnic.data.display_name,
                    primary, vnic.get_ocid())
                if subnet.data.prohibit_public_ip_on_vnic == False:
                    print "        Public IP: %s" % vnic.get_public_ip()
                print "        Private IP: %s (primary)" % vnic.get_private_ip()
                for ip in vnic.all_private_ips():
                    print "        Private IP: %s" % ip
            '''
            for ip in subnet.all_private_ips_with_primary():
                primary = ""
                if ip.is_primary():
                    primary = "primary"
                print("       Private IP: %s(%s) Host: %s" %
                      (ip.get_address(), primary, ip.get_hostname()))
                vnic = ip.get_vnic()
                if vnic:
                    print("         Vnic: %s (%s)" %
                          (vnic.get_ocid(), vnic.get_state()))
                    if subnet.is_public_ip_on_vnic_allowed():
                        print("         Vnic PublicIP: %s" %
                              vnic.get_public_ip())
                    instance = vnic.get_instance()
                    print("         Instance: %s(%s)" %
                          (instance.get_hostname(), instance.get_state()))
                    print("         Instance ocid: %s" % (instance.get_ocid()))
                else:
                    vnic_id = ip.get_vnic_ocid()
                    print("         Vnic: %s(%s)" % (vnic_id, "NotFound"))
                    print("         Instance: (maybe)%s(%s)" %
                          (ip.get_display_name(), "NotFound"))
    return 0
Ejemplo n.º 4
0
def main():
    """
    Main

    Returns
    -------
        int
            0 on success, 1 otherwise.
    """
    args = parse_args()

    # deal with deprecated options
    if args.human_readable:
        args.output_mode = 'table'
    if args.get:
        args.output_mode = 'parsable'
    if args.json:
        args.output_mode = 'json'

    if args.list_servers:
        # print the list of known STUN servers and exit
        for server in STUN_SERVERS:
            print(server)
        return 0

    _instance = None
    try:
        sess = oci_api.OCISession()
        if args.instance_id is not None:
            _instance = sess.get_instance(args.instance_id)
        else:
            _instance = sess.this_instance()
    except Exception as e:
        if args.instance_id is not None:
            # user specified a remote instance, there is no fallback to stun
            # we treat this as an error now
            stun_log.error("Error getting information of instance [%s]: %s" %
                           (args.instance_id, str(e)))
            return 1
        # in that case, just issue a debug info
        stun_log.debug("Error getting information of current instance: %s",
                       str(e))

    _all_p_ips = []

    if _instance is None:
        if args.instance_id is not None:
            # user specified a remote instance, there is no fallback to stun
            stun_log.error("Instance not found: %s" % args.instance_id)
            return 1
        # can we really end up here ?
        stun_log.debug("current Instance not found")
        # fall back to pystun
        stun_log.debug('No ip found , fallback to STUN')
        _ip = get_ip_info(source_ip=args.sourceip,
                          stun_host=args.stun_server)[1]
        stun_log.debug('STUN gave us : %s' % _ip)
        if _ip:
            _all_p_ips.append({'ip': _ip})
    else:
        _all_p_ips = [{
            'ip': v.get_public_ip(),
            'vnic_name': v.get_display_name(),
            'vnic_ocid': v.get_ocid()
        } for v in _instance.all_vnics() if v.get_public_ip()]
        stun_log.debug('%s ips retreived from sdk information' %
                       len(_all_p_ips))

    if len(_all_p_ips) == 0:
        # none of the methods give us information
        stun_log.info("No public IP address found.\n")
        return 1

    _display_ip_list(_all_p_ips, args.all, args.output_mode, args.details)
    return 0
Ejemplo n.º 5
0
def main():
    """
    Main

    Returns
    -------
        int
            0 on success, 1 otherwise.
    """
    args = parse_args()

    if args.list_servers:
        # print the list of known STUN servers and exit
        for server in STUN_SERVERS:
            print(server)
        return(0)

    _instance = None
    try:
        sess = oci_api.OCISession()
        if args.instance_id is not None:
            _instance = sess.get_instance(args.instance_id)
        else:
            _instance = sess.this_instance()
    except Exception as e:
        if args.instance_id is not None:
            # user specified a remote instance, there is no fallback to stun
            # we treat this as an error now
            stun_log.error(
                "Error getting information of instance [%s]: %s" % (args.instance_id, str(e)))
            return(1)
        else:
            # in that case, just issue a debug info
            stun_log.debug(
                "Error getting information of current instance: %s" % str(e))

    _all_p_ips = []

    if _instance is None:
        if args.instance_id is not None:
            # user specified a remote instance, there is no fallback to stun
            stun_log.error(
                "Instance not found: %s" % args.instance_id)
            return(1)
        else:
            # can we really end up here ?
            stun_log.debug(
                "current Instance not found")
    else:
        _all_p_ips = _instance.all_public_ips()
        stun_log.debug('%s ips retreived from sdk information' % len(_all_p_ips))

    if len(_all_p_ips) == 0:
        # fall back to pystun
        stun_log.debug('No ip found , fallback to STUN')
        _ip = get_ip_info(source_ip=args.sourceip,
                          stun_host=args.stun_server)[1]
        stun_log.debug('STUN gave us : %s' % _ip)
        if _ip:
            _all_p_ips.append(_ip)

    if len(_all_p_ips) == 0:
        # none of the methods give us information
        stun_log.info("No public IP address found.\n")
        return 1
    else:
        _display_ip_list(_all_p_ips, args.all, args.json, args.get)
        return 0