Execute provided configuration in class constructor to the DNS records
967370
def execute(self):
        """"""
        self.provider.authenticate()
        identifier = self.config.resolve('lexicon:identifier')
        record_type = self.config.resolve('lexicon:type')
        name = self.config.resolve('lexicon:name')
        content = self.config.resolve('lexicon:content')

        if self.action == 'create':
            return self.provider.create_record(record_type, name, content)

        if self.action == 'list':
            return self.provider.list_records(record_type, name, content)

        if self.action == 'update':
            return self.provider.update_record(identifier, record_type, name, content)

        if self.action == 'delete':
            return self.provider.delete_record(identifier, record_type, name, content)

        raise ValueError('Invalid action statement: {0}'.format(self.action))
951983
def cli(env, zonefile, dry_run):
    """"""

    manager = SoftLayer.DNSManager(env.client)
    with open(zonefile) as zone_f:
        zone_contents = zone_f.read()

    zone, records, bad_lines = parse_zone_details(zone_contents)

    env.out("Parsed: zone=%s" % zone)
    for record in records:
        env.out("Parsed: %s" % RECORD_FMT.format(**record))

    for line in bad_lines:
        env.out("Unparsed: %s" % line)

    if dry_run:
        return

    # Find zone id or create the zone if it doesn't exist
    try:
        zone_id = helpers.resolve_id(manager.resolve_ids, zone,
                                     name='zone')
    except exceptions.CLIAbort:
        zone_id = manager.create_zone(zone)['id']
        env.out(click.style("Created: %s" % zone, fg='green'))

    # Attempt to create each record
    for record in records:
        try:
            manager.create_record(zone_id,
                                  record['record'],
                                  record['type'],
                                  record['data'],
                                  record['ttl'])

            env.out(click.style("Created: %s" % RECORD_FMT.format(**record),
                                fg='green'))
        except SoftLayer.SoftLayerAPIError as ex:
            env.out(click.style("Failed: %s" % RECORD_FMT.format(**record),
                                fg='red'))
            env.out(click.style(str(ex), fg='red'))

    env.out(click.style("Finished", fg='green'))
409987
def ConfigureDatastore(config):
  """"""
  print("\n\n-=GRR Datastore=-\n"
        "For GRR to work each GRR server has to be able to communicate with\n"
        "the datastore. To do this we need to configure a datastore.\n")

  existing_datastore = grr_config.CONFIG.Get("Datastore.implementation")

  if not existing_datastore or existing_datastore == "FakeDataStore":
    ConfigureMySQLDatastore(config)
    return

  print("Found existing settings:\n  Datastore: %s" % existing_datastore)
  if existing_datastore == "SqliteDataStore":
    set_up_mysql = RetryBoolQuestion(
        "The SQLite datastore is no longer supported. Would you like to\n"
        "set up a MySQL datastore? Answering 'no' will abort config "
        "initialization.", True)
    if set_up_mysql:
      print("\nPlease note that no data will be migrated from SQLite to "
            "MySQL.\n")
      ConfigureMySQLDatastore(config)
    else:
      raise ConfigInitError()
  elif existing_datastore == "MySQLAdvancedDataStore":
    print("  MySQL Host: %s\n  MySQL Port: %s\n  MySQL Database: %s\n"
          "  MySQL Username: %s\n" %
          (grr_config.CONFIG.Get("Mysql.host"),
           grr_config.CONFIG.Get("Mysql.port"),
           grr_config.CONFIG.Get("Mysql.database_name"),
           grr_config.CONFIG.Get("Mysql.database_username")))
    if grr_config.CONFIG.Get("Mysql.client_key_path"):
      print("  MySQL client key file: %s\n"
            "  MySQL client cert file: %s\n"
            "  MySQL ca cert file: %s\n" %
            (grr_config.CONFIG.Get("Mysql.client_key_path"),
             grr_config.CONFIG.Get("Mysql.client_cert_path"),
             grr_config.CONFIG.Get("Mysql.ca_cert_path")))

    if not RetryBoolQuestion("Do you want to keep this configuration?", True):
      ConfigureMySQLDatastore(config)
1013925
public void configure(Object configuration) {

        if (!(configuration instanceof Properties) && !(configuration.toString() instanceof String))
            throw new IllegalArgumentException("Configuration for DAR must be of type Properties or String; "
                    + configuration.getClass().getName() + " was received");

        Properties properties = new Properties();
        if (configuration instanceof String) {
            try {
                properties.load(new StringReader((String) configuration));
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        } else if (configuration instanceof Properties) {
            properties = (Properties) configuration;
        }
        try {
            defaultSipApplicationRouterInfos = this.defaultApplicationRouterParser.parse(properties);
        } catch (ParseException e1) {
            throw new IllegalArgumentException("Failed to parse the new DAR properties", e1);
        }

        String configFileLocation = defaultApplicationRouterParser.getDarConfigurationFileLocation();

        if (configFileLocation.startsWith("file:/")) {
            int i = 5;
            while (configFileLocation.charAt(i) == '/')
                i++;
            configFileLocation = configFileLocation.substring(i - 1);
        } else {
            log.warn("Can not write persist DAR configuration to "
                    + configFileLocation
                    + ". Make sure you have write permissions and make sure it's a local file. NOTE THAT THE NEW DAR CONFIGURATION IS LOADED AND EFFECTIVE.");
            return;
        }

        if (configFileLocation == null || configFileLocation.length() < 1)
            throw new IllegalStateException("Configuration file name is empty.");

        File configFile = new File(configFileLocation);
        FileOutputStream fis = null;
        try {
            fis = new FileOutputStream(configFile);
            properties.store(fis, "Application Router Configuration");
        } catch (Exception e) {
            throw new IllegalStateException("Failed to store configuration file.", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("fail to close the following file " + configFile.getAbsolutePath(), e);
                }
            }
        }

        log.info("Stored DAR configuration in " + configFile.getAbsolutePath());
    }
201365
def _init_record(self, record_type_idstr):
        """"""
        record_type_data = self._all_supported_record_type_data_sets[Id(record_type_idstr).get_identifier()]
        module = importlib.import_module(record_type_data['module_path'])
        record = getattr(module, record_type_data['query_record_class_name'])
        self._records[record_type_idstr] = record(self)
537800
function init(){
    self.type = config.type || 'redis';
    if(config.redisMock){
      self.db = config.redisMock;
    }
    else{
      if(config.redisUrl){
        self.redisData = config.redisUrl || null;
      }
      else if(config.redisEnv){
        self.redisData = process.env[config.redisEnv] || null;
      }
      else if(config.redisData){
        self.redisData = config.redisData;
      }
      self.readOnly = (typeof config.readOnly === 'boolean') ? config.readOnly : false;
      try {
        if (self.redisData) {
          if(typeof self.redisData === 'string'){
            self.db = redis.createClient(self.redisData,
              {'no_ready_check': true,
              retry_strategy: retryStrategy});
          } else {
            self.db = redis.createClient(self.redisData.port,
              self.redisData.hostname, {'no_ready_check': true,
              retry_strategy: retryStrategy});

            // don't call redis auth method if no auth info passed
            if (self.redisData.auth) {
              self.db.auth(self.redisData.auth);
            }
          }
          self.db.on('error', function(err) {
            console.log('Error ' + err);
          });
          process.on('SIGTERM', function() {
            self.db.quit();
          });
          log(false, 'Redis client created with the following defaults:', {expiration: self.defaultExpiration, verbose: self.verbose, readOnly: self.readOnly});
        } else {
          self.db = false;
          log(false, 'Redis client not created: no redis config provided');
        }
      } catch (err) {
        self.db = false;
        log(true, 'Redis client not created:', err);
      }
    }
  }
986543
def CreateRecord(record_type, host, results):
        
        record_class = dns_tag_lookup[record_type]
        record = etree.Element("a")
        record.set("host", host)
        for params in results:
            result = etree.Element("result")
            for k,v in params.iteritems():
                result.set(k, v)
            record.append(result)

        return record_class(record)
691828
def _create_record(self, rtype, name, content):
        
        with self._session(self.domain, self.domain_id) as ddata:
            # Validate method parameters
            if not rtype or not name or not content:
                LOGGER.warning('Hetzner => Record has no rtype|name|content specified')
                return False

            # Add record to zone
            name = ddata['cname'] if ddata['cname'] else self._fqdn_name(name)
            rrset = ddata['zone']['data'].get_rdataset(name, rdtype=rtype, create=True)
            for rdata in rrset:
                if self._convert_content(rtype, content) == rdata.to_text():
                    LOGGER.info('Hetzner => Record with content \'%s\' already exists',
                                content)
                    return True

            ttl = (rrset.ttl if 0 < rrset.ttl < self._get_lexicon_option('ttl')
                   else self._get_lexicon_option('ttl'))
            rdataset = dns.rdataset.from_text(rrset.rdclass, rrset.rdtype,
                                              ttl, self._convert_content(rtype, content))
            rrset.update(rdataset)
            # Post zone to Hetzner
            synced_change = self._post_zone(ddata['zone'])
            if synced_change:
                self._propagated_record(rtype, name, self._convert_content(rtype, content),
                                        ddata['nameservers'])
            return synced_change
1172469
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data["properties"]

        ip_configurations = []
        raw_settings = properties.get("ipConfigurations", [])
        for raw_configuration in raw_settings:
            raw_configuration["parentResourceID"] = raw_data["resourceId"]
            ip_configuration = IPConfiguration.from_raw_data(raw_configuration)
            ip_configurations.append(ip_configuration)
        properties["ipConfigurations"] = ip_configurations

        raw_settings = properties.get("dnsSettings", {})
        dns_settings = DNSSettings.from_raw_data(raw_settings)
        properties["dnsSettings"] = dns_settings

        raw_settings = properties.get("portSettings", {})
        port_settings = PortSettings.from_raw_data(raw_settings)
        properties["portSettings"] = port_settings

        return super(NetworkInterfaces, cls).process_raw_data(raw_data)
949603
def create_or_update_record(self, dns_type, name, content, **kwargs):
        
        try:
            return self.update_record(dns_type, name, content, **kwargs)
        except RecordNotFound:
            return self.create_record(dns_type, name, content, **kwargs)
135774
def update_record(self, dns_type, name, content, **kwargs):
        
        record = self.get_record(dns_type, name)
        data = {
            'type': dns_type,
            'name': name,
            'content': content
        }
        if kwargs.get('ttl') and kwargs['ttl'] != 1:
            data['ttl'] = kwargs['ttl']
        if kwargs.get('proxied') is True:
            data['proxied'] = True
        else:
            data['proxied'] = False
        content = self.request(
            urllib.parse.urljoin(self.api_url, self.zone['id'] + '/dns_records/' + record['id']),
            'put',
            data=data
        )
        print('DNS record successfully updated')
        return content['result']
861681
function(newValue,property,config) {
                var thesetter = config.setter;
                if ( typeof(config.setter) === 'string' ) {
                    record[config.setter](newValue, property, config,record);
                } else {
                    //assume function
                    thesetter.call(record,newValue, property, config,record);
                }

            }
666382
def execute_update(args):
    

    provider_class = getattr(dnsupdater,
                             dnsupdater.AVAILABLE_PLUGINS.get(args.provider))
    updater_options = {}
    process_message = None
    auth = None

    if args.store:  # --store argument
        if provider_class.auth_type == 'T':
            user_arg = args.usertoken or utils.read_input(
                "Paste your auth token: ")
            auth = authinfo.ApiAuth(usertoken=user_arg)
        else:
            user_arg = args.usertoken or utils.read_input(
                "Type your username: ")
            pass_arg = args.password or getpass.getpass("Type your password: ")
            auth = authinfo.ApiAuth(user_arg, pass_arg)

        authinfo.store(auth, args.provider, args.config)
        exec_result = EXECUTION_RESULT_OK
        if not args.hostname:
            update_ddns = False
            process_message = "Auth info stored."
        else:
            update_ddns = True

    # informations arguments
    elif args.usertoken and args.hostname:
        if provider_class.auth_type == 'T':
            auth = authinfo.ApiAuth(args.usertoken)
        else:
            auth = authinfo.ApiAuth(args.usertoken, args.password)
        update_ddns = True
        exec_result = EXECUTION_RESULT_OK
    elif args.hostname:
        if authinfo.exists(args.provider, args.config):
            auth = authinfo.load(args.provider, args.config)
            update_ddns = True
            exec_result = EXECUTION_RESULT_OK
        else:
            update_ddns = False
            exec_result = EXECUTION_RESULT_NOK
            process_message = "No stored auth information found for " \
                              "provider: '%s'" % args.provider
    else:  # no arguments
        update_ddns = False
        exec_result = EXECUTION_RESULT_NOK
        process_message = "Warning: The hostname to be updated must be " \
                          "provided.\nUsertoken and password can be either " \
                          "provided via command line or stored with --store " \
                          "option.\nExecute noipy --help for more details."

    if update_ddns and args.provider == 'generic':
        if args.url:
            if not URL_RE.match(args.url):
                process_message = "Malformed URL."
                exec_result = EXECUTION_RESULT_NOK
                update_ddns = False
            else:
                updater_options['url'] = args.url
        else:
            process_message = "Must use --url if --provider is 'generic' " \
                              "(default)"
            exec_result = EXECUTION_RESULT_NOK
            update_ddns = False

    response_code = None
    response_text = None
    if update_ddns:
        ip_address = args.ip if args.ip else utils.get_ip()
        if not ip_address:
            process_message = "Unable to get IP address. Check connection."
            exec_result = EXECUTION_RESULT_NOK
        elif ip_address == utils.get_dns_ip(args.hostname):
            process_message = "No update required."
        else:
            updater = provider_class(auth, args.hostname, updater_options)
            print("Updating hostname '%s' with IP address %s "
                  "[provider: '%s']..."
                  % (args.hostname, ip_address, args.provider))
            response_code, response_text = updater.update_dns(ip_address)
            process_message = updater.status_message

    proc_result = {
        'exec_result': exec_result,
        'response_code': response_code,
        'response_text': response_text,
        'process_message': process_message,
    }

    return proc_result
710246
def do_execute(self):
        
        iquery = InstanceQuery()
        iquery.db_url = str(self.resolve_option("db_url"))
        iquery.user = str(self.resolve_option("user"))
        iquery.password = str(self.resolve_option("password"))
        props = str(self.resolve_option("custom_props"))
        if (len(props) > 0) and os.path.isfile(props):
            iquery.custom_properties = props
        iquery.query = str(self.resolve_option("query"))
        data = iquery.retrieve_instances()
        self._output.append(Token(data))
        return None
797801
def init_config(cls):
        
        try:
            # first load current conf and only overwrite needed params
            # we don't want to reset everything
            config_file = os.path.expanduser(cls.home_config)
            config = cls.load(config_file, 'global')
            cls._del('global', 'api.env')

            hidden_apikey = '%s...' % cls.get('api.key', '')[:6]
            apikey = click.prompt('Api key (xmlrpc)',
                                  default=hidden_apikey)
            if apikey == hidden_apikey:
                # if default value then use actual value not hidden one
                apikey = cls.get('api.key')
            env_choice = click.Choice(list(cls.apienvs.keys()))
            apienv = click.prompt('Environnment [production]/ote',
                                  default=cls.default_apienv,
                                  type=env_choice,
                                  show_default=False)
            sshkey = click.prompt('SSH keyfile',
                                  default='~/.ssh/id_rsa.pub')
            hidden_apikeyrest = '%s...' % cls.get('apirest.key', '')[:6]
            apikeyrest = click.prompt('Api key (REST)',
                                      default=hidden_apikeyrest)
            if apikeyrest == hidden_apikeyrest:
                # if default value then use actual value not hidden one
                apikeyrest = cls.get('apirest.key')

            config.update({
                'api': {'key': apikey,
                        'host': cls.apienvs[apienv]},
            })
            if apikeyrest:
                config.update({
                    'apirest': {'key': apikeyrest},
                })

            if sshkey is not None:
                sshkey_file = os.path.expanduser(sshkey)
                if os.path.exists(sshkey_file):
                    config['sshkey'] = [sshkey_file]

            directory = os.path.expanduser(os.path.dirname(config_file))
            if not os.path.exists(directory):
                mkpath(directory, 0o700)

            # save to disk
            cls.save(config_file, config)
            # load in memory
            cls.load(config_file, 'global')
        except (KeyboardInterrupt, click.exceptions.Abort):
            cls.echo('Aborted.')
            sys.exit(1)
287656
def Convert(self, metadata, config, token=None):
    """"""
    result = ExportedDNSClientConfiguration(
        metadata=metadata,
        dns_servers=" ".join(config.dns_server),
        dns_suffixes=" ".join(config.dns_suffix))
    yield result
255128
public static void injectConfigurations(
			String karafEtc,
			String applicationName,
			String scopedInstancePath,
			String domain,
			String ipAddress ) {

		File injectionDir = new File( karafEtc, INJECTED_CONFIGS_DIR );
		if( injectionDir.isDirectory()) {
			for( File source : Utils.listAllFiles( injectionDir, ".cfg.tpl" )) {
				try {
					File target = new File( karafEtc, source.getName().replaceFirst( "\\.tpl$", "" ));

					// Do not overwrite the agent's configuration file (infinite configuration loop)
					if( Constants.KARAF_CFG_FILE_AGENT.equalsIgnoreCase( target.getName()))
						continue;

					String content = Utils.readFileContent( source );
					content = content.replace( "<domain>", domain );
					content = content.replace( "<application-name>", applicationName );
					content = content.replace( "<scoped-instance-path>", scopedInstancePath );
					content = content.replace( "<ip-address>", ipAddress );
					Utils.writeStringInto( content, target );

				} catch( IOException e ) {
					Logger logger = Logger.getLogger( AgentUtils.class.getName());
					logger.severe( "A configuration file could not be injected from " + source.getName());
					Utils.logException( logger, e );
				}
			}
		}
	}