How to use agentConfig method in Best

Best JavaScript code snippet using best

general_settings.ts

Source:general_settings.ts Github

copy

Full Screen

1/*2 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one3 * or more contributor license agreements. Licensed under the Elastic License;4 * you may not use this file except in compliance with the Elastic License.5 */6import { i18n } from '@kbn/i18n';7import { captureBodyRt } from '../runtime_types/capture_body_rt';8import { logLevelRt } from '../runtime_types/log_level_rt';9import { RawSettingDefinition } from './types';10export const generalSettings: RawSettingDefinition[] = [11 // API Request Size12 {13 key: 'api_request_size',14 type: 'bytes',15 defaultValue: '768kb',16 label: i18n.translate('xpack.apm.agentConfig.apiRequestSize.label', {17 defaultMessage: 'API Request Size',18 }),19 description: i18n.translate(20 'xpack.apm.agentConfig.apiRequestSize.description',21 {22 defaultMessage:23 'The maximum total compressed size of the request body which is sent to the APM Server intake api via a chunked encoding (HTTP streaming).\nNote that a small overshoot is possible.\n\nAllowed byte units are `b`, `kb` and `mb`. `1kb` is equal to `1024b`.',24 }25 ),26 excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'],27 },28 // API Request Time29 {30 key: 'api_request_time',31 type: 'duration',32 defaultValue: '10s',33 label: i18n.translate('xpack.apm.agentConfig.apiRequestTime.label', {34 defaultMessage: 'API Request Time',35 }),36 description: i18n.translate(37 'xpack.apm.agentConfig.apiRequestTime.description',38 {39 defaultMessage:40 "Maximum time to keep an HTTP request to the APM Server open for.\n\nNOTE: This value has to be lower than the APM Server's `read_timeout` setting.",41 }42 ),43 excludeAgents: ['js-base', 'rum-js', 'dotnet', 'go', 'nodejs'],44 },45 // Capture body46 {47 key: 'capture_body',48 validation: captureBodyRt,49 type: 'select',50 defaultValue: 'off',51 label: i18n.translate('xpack.apm.agentConfig.captureBody.label', {52 defaultMessage: 'Capture body',53 }),54 description: i18n.translate(55 'xpack.apm.agentConfig.captureBody.description',56 {57 defaultMessage:58 'For transactions that are HTTP requests, the agent can optionally capture the request body (e.g. POST variables).\nFor transactions that are initiated by receiving a message from a message broker, the agent can capture the textual message body.',59 }60 ),61 options: [62 { text: 'off', value: 'off' },63 { text: 'errors', value: 'errors' },64 { text: 'transactions', value: 'transactions' },65 { text: 'all', value: 'all' },66 ],67 excludeAgents: ['js-base', 'rum-js'],68 },69 // Capture headers70 {71 key: 'capture_headers',72 type: 'boolean',73 defaultValue: 'true',74 label: i18n.translate('xpack.apm.agentConfig.captureHeaders.label', {75 defaultMessage: 'Capture Headers',76 }),77 description: i18n.translate(78 'xpack.apm.agentConfig.captureHeaders.description',79 {80 defaultMessage:81 'If set to `true`, the agent will capture HTTP request and response headers (including cookies), as well as message headers/properties when using messaging frameworks (like Kafka).\n\nNOTE: Setting this to `false` reduces network bandwidth, disk space and object allocations.',82 }83 ),84 excludeAgents: ['js-base', 'rum-js', 'nodejs'],85 },86 // LOG_LEVEL87 {88 key: 'log_level',89 validation: logLevelRt,90 type: 'select',91 defaultValue: 'info',92 label: i18n.translate('xpack.apm.agentConfig.logLevel.label', {93 defaultMessage: 'Log level',94 }),95 description: i18n.translate('xpack.apm.agentConfig.logLevel.description', {96 defaultMessage: 'Sets the logging level for the agent',97 }),98 options: [99 { text: 'trace', value: 'trace' },100 { text: 'debug', value: 'debug' },101 { text: 'info', value: 'info' },102 { text: 'warning', value: 'warning' },103 { text: 'error', value: 'error' },104 { text: 'critical', value: 'critical' },105 { text: 'off', value: 'off' },106 ],107 includeAgents: ['dotnet', 'ruby', 'java', 'python', 'nodejs'],108 },109 // Recording110 {111 key: 'recording',112 type: 'boolean',113 defaultValue: 'true',114 label: i18n.translate('xpack.apm.agentConfig.recording.label', {115 defaultMessage: 'Recording',116 }),117 description: i18n.translate('xpack.apm.agentConfig.recording.description', {118 defaultMessage:119 'When recording, the agent instruments incoming HTTP requests, tracks errors, and collects and sends metrics. When set to non-recording, the agent works as a noop, not collecting data and not communicating with the APM Server except for polling for updated configuration. As this is a reversible switch, agent threads are not being killed when set to non-recording, but they will be mostly idle in this state, so the overhead should be negligible. You can use this setting to dynamically control whether Elastic APM is enabled or disabled.',120 }),121 excludeAgents: ['nodejs'],122 },123 // SERVER_TIMEOUT124 {125 key: 'server_timeout',126 type: 'duration',127 defaultValue: '5s',128 label: i18n.translate('xpack.apm.agentConfig.serverTimeout.label', {129 defaultMessage: 'Server Timeout',130 }),131 description: i18n.translate(132 'xpack.apm.agentConfig.serverTimeout.description',133 {134 defaultMessage:135 'If a request to the APM Server takes longer than the configured timeout,\nthe request is cancelled and the event (exception or transaction) is discarded.\nSet to 0 to disable timeouts.\n\nWARNING: If timeouts are disabled or set to a high value, your app could experience memory issues if the APM Server times out.',136 }137 ),138 includeAgents: ['java'],139 },140 // SPAN_FRAMES_MIN_DURATION141 {142 key: 'span_frames_min_duration',143 type: 'duration',144 min: '-1ms',145 defaultValue: '5ms',146 label: i18n.translate('xpack.apm.agentConfig.spanFramesMinDuration.label', {147 defaultMessage: 'Span frames minimum duration',148 }),149 description: i18n.translate(150 'xpack.apm.agentConfig.spanFramesMinDuration.description',151 {152 defaultMessage:153 'In its default settings, the APM agent will collect a stack trace with every recorded span.\nWhile this is very helpful to find the exact place in your code that causes the span, collecting this stack trace does have some overhead. \nWhen setting this option to a negative value, like `-1ms`, stack traces will be collected for all spans. Setting it to a positive value, e.g. `5ms`, will limit stack trace collection to spans with durations equal to or longer than the given value, e.g. 5 milliseconds.\n\nTo disable stack trace collection for spans completely, set the value to `0ms`.',154 }155 ),156 excludeAgents: ['js-base', 'rum-js', 'nodejs'],157 },158 // STACK_TRACE_LIMIT159 {160 key: 'stack_trace_limit',161 type: 'integer',162 defaultValue: '50',163 label: i18n.translate('xpack.apm.agentConfig.stackTraceLimit.label', {164 defaultMessage: 'Stack trace limit',165 }),166 description: i18n.translate(167 'xpack.apm.agentConfig.stackTraceLimit.description',168 {169 defaultMessage:170 'Setting it to 0 will disable stack trace collection. Any positive integer value will be used as the maximum number of frames to collect. Setting it -1 means that all frames will be collected.',171 }172 ),173 includeAgents: ['java', 'dotnet', 'go'],174 },175 // Transaction max spans176 {177 key: 'transaction_max_spans',178 type: 'integer',179 min: 0,180 defaultValue: '500',181 label: i18n.translate('xpack.apm.agentConfig.transactionMaxSpans.label', {182 defaultMessage: 'Transaction max spans',183 }),184 description: i18n.translate(185 'xpack.apm.agentConfig.transactionMaxSpans.description',186 {187 defaultMessage:188 'Limits the amount of spans that are recorded per transaction.',189 }190 ),191 excludeAgents: ['js-base', 'rum-js'],192 },193 // Transaction sample rate194 {195 key: 'transaction_sample_rate',196 type: 'float',197 defaultValue: '1.0',198 label: i18n.translate('xpack.apm.agentConfig.transactionSampleRate.label', {199 defaultMessage: 'Transaction sample rate',200 }),201 description: i18n.translate(202 'xpack.apm.agentConfig.transactionSampleRate.description',203 {204 defaultMessage:205 'By default, the agent will sample every transaction (e.g. request to your service). To reduce overhead and storage requirements, you can set the sample rate to a value between 0.0 and 1.0. We still record overall time and the result for unsampled transactions, but not context information, labels, or spans.',206 }207 ),208 },209 // Sanitize field names210 {211 key: 'sanitize_field_names',212 type: 'text',213 defaultValue:214 'password, passwd, pwd, secret, *key, *token*, *session*, *credit*, *card*, authorization, set-cookie',215 label: i18n.translate('xpack.apm.agentConfig.sanitizeFiledNames.label', {216 defaultMessage: 'Sanitize field names',217 }),218 description: i18n.translate(219 'xpack.apm.agentConfig.sanitizeFiledNames.description',220 {221 defaultMessage:222 'Sometimes it is necessary to sanitize, i.e., remove, sensitive data sent to Elastic APM. This config accepts a list of wildcard patterns of field names which should be sanitized. These apply to HTTP headers (including cookies) and `application/x-www-form-urlencoded` data (POST form fields). The query string and the captured request body (such as `application/json` data) will not get sanitized.',223 }224 ),225 includeAgents: ['java', 'python', 'go'],226 },227 // Ignore transactions based on URLs228 {229 key: 'transaction_ignore_urls',230 type: 'text',231 defaultValue:232 'Agent specific - check out the documentation of this config option in the corresponding agent documentation.',233 label: i18n.translate('xpack.apm.agentConfig.transactionIgnoreUrl.label', {234 defaultMessage: 'Ignore transactions based on URLs',235 }),236 description: i18n.translate(237 'xpack.apm.agentConfig.transactionIgnoreUrl.description',238 {239 defaultMessage:240 'Used to restrict requests to certain URLs from being instrumented. This config accepts a comma-separated list of wildcard patterns of URL paths that should be ignored. When an incoming HTTP request is detected, its request path will be tested against each element in this list. For example, adding `/home/index` to this list would match and remove instrumentation from `http://localhost/home/index` as well as `http://whatever.com/home/index?value1=123`',241 }242 ),243 includeAgents: ['java'],244 },...

Full Screen

Full Screen

RemoteAgentAdapter.test.ts

Source:RemoteAgentAdapter.test.ts Github

copy

Full Screen

1/*2 *3 * Test RemoteAgentAdapter Class4 *5 *6 */7import chai, { assert } from 'chai'8import chaiAsPromised from 'chai-as-promised'9chai.use(chaiAsPromised)10import { randomBytes } from 'crypto'11import { urlJoin } from 'url-join-ts'12import { loadTestSetup, enableSurferInvokableOperations } from 'test/TestSetup'13import { calculateAssetDataHash, extractAssetId, remove0xPrefix, RemoteAgentAdapter } from 'starfish'14let setup = loadTestSetup()15const agentConfig = setup.agents['local']16var accessToken17var adapter18const metaData = {19 "name": "testmetadata",20 "description": "test metadata from starfish-js test",21 "type": "dataset",22 "contentType": "text/plain",23 "contentHash": `${randomBytes(32).toString('hex')}`,24}25const today = new Date(Date.now())26const listing = {27 'name': 'Test file asset',28 'description': 'Test asset for sale',29 'dateCreated': today.toISOString(),30 'author': 'starfish-js-test',31 'license': 'Closed',32 'price': 3.141592, // price is in ocean tokens33 'extra_data': 'Some extra data',34 'tags': ['asset', 'sale', 'test', 'starfish'],35}36const testInovkeName = 'Increment'37describe('RemoteAgentAdapter', () => {38 describe('Access to agent', () => {39 before(async () => {40 adapter = RemoteAgentAdapter.getInstance()41 })42 describe('getAuthorizationToken', () => {43 it('should fetch a current or new token', async () => {44 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')45 const token = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)46 assert(token)47 })48 })49 })50 describe('ddo based services', () => {51 before(async () => {52 adapter = RemoteAgentAdapter.getInstance()53 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')54 accessToken = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)55 })56 describe('getDDO', () => {57 it('should fetch the agent ddo', async () => {58 const ddoText = await adapter.getDDO(agentConfig['url'], accessToken)59 assert(ddoText)60 })61 })62 })63 describe('metaData based services', () => {64 var metadataURL65 var metadataText66 before(async () => {67 adapter = RemoteAgentAdapter.getInstance()68 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')69 accessToken = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)70 metadataText = JSON.stringify(metaData)71 metadataURL = `${agentConfig['url']}/api/v1/meta`72 })73 describe('saveMetadata', () => {74 it('should save metaData to a remote agent', async () => {75 const assetId = await adapter.saveMetadata(metadataText, metadataURL, accessToken)76 assert(assetId)77 })78 })79 describe('readMetadata', () => {80 it('should read a saved metaData item', async () => {81 const assetId = await adapter.saveMetadata(metadataText, metadataURL, accessToken)82 const readMetadata = await adapter.readMetadata(assetId, metadataURL, accessToken)83 assert(readMetadata)84 assert.equal(readMetadata, metadataText)85 })86 })87 describe('getMetadataList', () => {88 it('should read the metaData list on the agent', async () => {89 const assetId = await adapter.saveMetadata(metadataText, metadataURL, accessToken)90 const metadataList = await adapter.getMetaDataList(metadataURL, accessToken)91 assert(metadataList)92 assert(metadataList[assetId])93 })94 })95 })96 describe('market place services', () => {97 var metaDataURL98 var metaDataText99 var marketURL100 var listingText101 before(async () => {102 adapter = RemoteAgentAdapter.getInstance()103 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')104 accessToken = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)105 metaDataText = JSON.stringify(metaData)106 metaDataURL = `${agentConfig['url']}/api/v1/meta`107 listingText = JSON.stringify(listing)108 marketURL = `${agentConfig['url']}/api/v1/market`109 })110 describe('addListing', () => {111 it('should create and add a new listing', async () => {112 const assetId = await adapter.saveMetadata(metaDataText, metaDataURL, accessToken)113 const listingData = await adapter.addListing(listingText, assetId, marketURL, accessToken)114 assert(listingData)115 })116 })117 describe('getListing', () => {118 it('should get a listing using a listing id', async () => {119 const assetId = await adapter.saveMetadata(metaDataText, metaDataURL, accessToken)120 const listingData = await adapter.addListing(listingText, assetId, marketURL, accessToken)121 assert(listingData)122 const readListingData = await adapter.getListing(listingData['id'], marketURL, accessToken)123 assert(readListingData)124 })125 })126 describe('getListingList', () => {127 it('should get a list of listings, but does not work on the surfer agent', async () => {128 const assetId = await adapter.saveMetadata(metaDataText, metaDataURL, accessToken)129 const listingData = await adapter.addListing(listingText, assetId, marketURL, accessToken)130 assert(listingData)131 const filter = {132 userid: listingData['userid']133 }134 assert.isRejected(adapter.getListingList(filter, marketURL, accessToken),135 /Unable to get a list of listing items/)136 })137 })138 describe('updateListing', () => {139 it('should update a listing at the surfer agent', async () => {140 const assetId = await adapter.saveMetadata(metaDataText, metaDataURL, accessToken)141 const listingData = await adapter.addListing(listingText, assetId, marketURL, accessToken)142 assert(listingData)143 let newListingData = listingData144 newListingData['info']['name'] = 'new data'145 const updateListingData = await adapter.updateListing(newListingData, marketURL, accessToken)146 assert(updateListingData)147 })148 })149 })150 describe('market place services', () => {151 var metaDataURL152 var metaDataText153 var storageURL154 var assetId155 var assetData156 before(async () => {157 adapter = RemoteAgentAdapter.getInstance()158 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')159 accessToken = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)160 assetData = Buffer.from(randomBytes(1024))161 const metaDataAsset = metaData162 const hash = calculateAssetDataHash(assetData)163 metaDataAsset['contentType'] = 'application/octet-stream'164 metaDataAsset['contentHash'] = hash165 metaDataText = JSON.stringify(metaDataAsset)166 metaDataURL = `${agentConfig['url']}/api/v1/meta`167 assetId = await adapter.saveMetadata(metaDataText, metaDataURL, accessToken)168 storageURL = `${agentConfig['url']}/api/v1/assets`169 })170 describe('uploadAssetData, downloadAssetData', () => {171 it('should upload asset data', async () => {172 assert(await adapter.uploadAssetData(assetId, assetData, storageURL, accessToken))173 const downloadData = await adapter.downloadAssetData(assetId, storageURL, accessToken)174 assert(downloadData)175 assert(Buffer.from(downloadData).equals(assetData))176 })177 })178 })179 describe('invoke services', () => {180 var invokeURL181 var assetId182 before(async () => {183 adapter = RemoteAgentAdapter.getInstance()184 const invokeList = await enableSurferInvokableOperations(agentConfig['url'], agentConfig['username'], agentConfig['password'])185 assert(invokeList['invokables'][testInovkeName])186 assetId = remove0xPrefix(extractAssetId(invokeList['invokables'][testInovkeName]))187 const tokenURL = urlJoin(agentConfig['url'], '/api/v1/auth/token')188 accessToken = await adapter.getAuthorizationToken(agentConfig['username'], agentConfig['password'], tokenURL)189 invokeURL = `${agentConfig['url']}/api/v1/invoke`190 })191 describe('invoke sync', () => {192 it('should call a sync invoke service', async () => {193 const testNumber = Math.random() * 100194 const inputs = {195 n: testNumber196 }197 const result = await adapter.invoke(assetId, JSON.stringify(inputs), false, invokeURL, accessToken)198 assert(result)199 assert(result['outputs'])200 assert.equal(result['status'], 'succeeded')201 const outputs = result['outputs']202 assert.equal(outputs['n'], testNumber + 1)203 })204 })205 describe('invoke async, getJob', () => {206 it('should call an async invoke service, a get the job status', async () => {207 const testNumber = Math.random() * 100208 const inputs = {209 n: testNumber210 }211 const result = await adapter.invoke(assetId, JSON.stringify(inputs), true, invokeURL, accessToken)212 assert(result)213 let jobResult214 while (true) {215 jobResult = await adapter.getJob(result['jobId'], invokeURL, accessToken)216 if (jobResult['status'] == 'succeeded') {217 break218 }219 }220 assert(jobResult['outputs'])221 const outputs = jobResult['outputs']222 assert.equal(outputs['n'], testNumber + 1)223 })224 })225 })...

Full Screen

Full Screen

agent.manager.service.ts

Source:agent.manager.service.ts Github

copy

Full Screen

1import { Injectable, CacheStore, CACHE_MANAGER, Inject, HttpService } from '@nestjs/common';2import { Logger } from 'protocol-common/logger';3import { ProtocolHttpService } from 'protocol-common/protocol.http.service';4import { ProtocolException } from 'protocol-common/protocol.exception';5import { ProtocolUtility } from 'protocol-common/protocol.utility';6import { DockerService } from './docker.service';7import { IAgentManager } from './agent.manager.interface';8import { AgentConfig } from './agent.config';9import { K8sService } from './k8s.service';10import { AgentCreateDto } from './dtos/agent.create.dto';11/**12 * TODO validation, error cases, etc13 */14@Injectable()15export class AgentManagerService {16 private manager: IAgentManager;17 // TODO expose a non-retry call to ProtocolHttpService so we don't need to keep both18 private http: ProtocolHttpService;19 constructor(20 private readonly httpService: HttpService,21 @Inject(CACHE_MANAGER) private readonly cache: CacheStore22 ) {23 this.http = new ProtocolHttpService(httpService);24 // TODO move this logic to an agent manager factory, which can be injected via a module25 // We can also use env type to infer this26 if (process.env.MANAGER_TYPE === 'DOCKER') {27 this.manager = new DockerService();28 } else if (process.env.MANAGER_TYPE === 'K8S') {29 this.manager = new K8sService();30 } else {31 throw new Error('Invalid config for MANAGER_TYPE');32 }33 }34 /**35 * Contains the general logic to spin up an agent regardless of environment36 */37 public async spinUpAgent(agentDto: AgentCreateDto) {38 const agentConfig = new AgentConfig(agentDto);39 try {40 await this.manager.startAgent(agentConfig);41 } catch (e) {42 Logger.warn(`exception on startAgent() for agent '${agentDto.agentId}'`, e);43 await this.handleAlreadyRunningContainer(agentConfig, agentDto.autoConnect, e);44 }45 await this.setAgentCache(agentConfig);46 this.setSpinDownJob(agentConfig);47 let connectionData = {};48 // when autoConnect is true, then call the createConnection method, when autoCorrect is not defined or null, treat it as true49 if (agentDto.autoConnect === true) {50 // TODO for right now let's delay and then initiate the connection51 const retryDuration = parseInt(process.env.AGENT_RETRY_DURATION, 10);52 await this.pingConnectionWithRetry(agentConfig.agentId, agentConfig.adminPort, agentConfig.adminApiKey, retryDuration);53 connectionData = await this.createConnection(agentConfig.agentId, agentConfig.adminPort, agentConfig.adminApiKey);54 }55 return { agentId: agentConfig.agentId, connectionData };56 }57 /**58 * TODO we should probably respond with something59 * TODO handle case were agent not there60 */61 public async spinDownAgent(agentId: string) {62 try {63 Logger.log('Spinning down agent', agentId);64 await this.cache.del(agentId);65 await this.manager.stopAgent(agentId);66 } catch (e) {67 Logger.warn(`error shutting down agent: '${e.message}'`, e);68 }69 }70 public async isAgentServerUp(agentId: string, adminPort: number, adminApiKey: string): Promise<boolean> {71 try {72 const url = `http://${agentId}:${adminPort}/status`;73 Logger.info(`agent admin url is ${url}`);74 const req: any = {75 method: 'GET',76 url,77 headers: {78 'x-api-key': adminApiKey,79 accept: 'application/json'80 },81 };82 // TODO we should either add a non-retry call to ProtocolHttpService, or make the existing requestWithRetry more configurable83 const res = await this.httpService.request(req).toPromise();84 if (res.status === 200) {85 return true;86 }87 } catch (e) {}88 return false;89 }90 /**91 * TODO move to it's own class and pass in the http object92 * TODO error handling93 */94 private async createConnection(agentId: string, adminPort: number, adminApiKey: string) {95 const url = `http://${agentId}:${adminPort}/connections/create-invitation`;96 const req: any = {97 method: 'POST',98 url,99 headers: {100 'x-api-key': adminApiKey,101 },102 };103 const res = await this.http.requestWithRetry(req);104 return res.data.invitation;105 }106 /**107 * TODO move to it's own class and pass in the http object108 */109 private async pingConnectionWithRetry(agentId: string, adminPort: number, adminApiKey: string, durationMS: number) : Promise<any> {110 const startOf = new Date();111 while (durationMS > ProtocolUtility.timeDelta(new Date(), startOf)) {112 // no point in rushing this113 await ProtocolUtility.delay(1000);114 // attempt a status check, if successful call it good and return, otherwise retry until duration is exceeded115 try {116 if (true === await this.isAgentServerUp(agentId, adminPort, adminApiKey)) {117 Logger.info(`agent ${agentId} is up and responding`);118 return;119 }120 } catch (e) {121 // Do nothing and try again122 }123 }124 throw new ProtocolException('Agent', `Never got a good status code from agent ${agentId}`);125 }126 /**127 * If we get an error attempting to start an agent it could be because the agent is already running128 * If the agent is already in the cache, then attempt to connect to it, otherwise add to cache129 */130 private async handleAlreadyRunningContainer(agentConfig: AgentConfig, autoConnect: boolean, e: any): Promise<any> {131 let agentData: any = await this.cache.get(agentConfig.agentId);132 if (agentData === undefined) {133 /*134 // TODO: we would like to be able to ping agent to make sure its really available135 try {136 await this.pingConnectionWithRetry(agentId, adminApiPort, adminApiKey, 10000);137 } catch (e) {138 Logger.warn(`agent ${agentId} not found in cache and was not reachable`);139 throw e;140 }141 */142 Logger.warn(`agent ${agentConfig.agentId} not found in cache...adding`);143 await this.setAgentCache(agentConfig);144 agentData = await this.cache.get(agentConfig.agentId);145 } else {146 Logger.log(`agent ${agentConfig.agentId} exists and is in cache:`, agentData);147 }148 let connectionData = {};149 if (agentData) {150 if (autoConnect === true) {151 // TODO need error handling if this call fails152 connectionData = await this.createConnection(agentConfig.agentId, agentConfig.adminPort, agentConfig.adminApiKey);153 }154 return {155 agentId: agentConfig.agentId,156 connectionData157 };158 }159 // if the call to handleAlreadyRunningContainer fails, let it fall through because we have a bigger problem.160 Logger.warn(`Unhandled error starting agent '${agentConfig.agentId}'...see previous messages for details`);161 throw e;162 }163 /**164 * TODO check with the governance policy on whether to allow the connection165 */166 public async connectAgent (agentId: string, adminApiKey: string): Promise<any> {167 const agentCache: any = await this.cache.get(agentId);168 const adminPort = (agentCache ? agentCache.adminApiPort : parseInt(process.env.AGENT_ADMIN_PORT, 10));169 await this.pingConnectionWithRetry(agentId, adminPort, adminApiKey, parseInt(process.env.AGENT_RETRY_DURATION, 10));170 const connectionData = await this.createConnection(agentId, adminPort, adminApiKey);171 return { agentId, connectionData };172 }173 /**174 * This gets called in multiple places so ensuring logic stays the same175 */176 private async setAgentCache(agentConfig: AgentConfig): Promise<void> {177 // Generally we want the cache to last 1 second longer than the agent, except when set to an "infinite" value like 0 or -1178 const cacheTtl = (agentConfig.ttl < 0) ? agentConfig.ttl : agentConfig.ttl + 1;179 Logger.info(`record cache limit set to: ${cacheTtl}`);180 await this.cache.set(181 agentConfig.agentId,182 {183 adminApiKey: agentConfig.adminApiKey,184 adminApiPort: agentConfig.adminPort,185 ttl: agentConfig.ttl186 },187 {188 ttl: cacheTtl189 }190 );191 }192 /**193 * ttl = time to live is expected to be in seconds (which we convert to milliseconds). if 0, then live in eternity194 */195 private setSpinDownJob(agentConfig: AgentConfig): void {196 if (agentConfig.ttl > 0 && agentConfig.ttl !== Infinity) {197 setTimeout(198 async () => {199 await this.spinDownAgent(agentConfig.agentId);200 }, agentConfig.ttl * 1000);201 }202 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestAgent = require('bestagent');2var agent = BestAgent.agent();3agent.agentConfig({maxSockets: 1000});4 if (err) {5 console.log(err);6 } else {7 console.log(res);8 }9});10var BestAgent = require('bestagent');11var agent = BestAgent.agent();12agent.agentConfig({maxSockets: 1000});13 if (err) {14 console.log(err);15 } else {16 console.log(res);17 }18});19var BestAgent = require('bestagent');20var agent = BestAgent.agent();21agent.agentConfig({maxSockets: 1000});22 if (err) {23 console.log(err);24 } else {25 console.log(res);26 }27});28var BestAgent = require('bestagent');29var agent = BestAgent.agent();30agent.agentConfig({maxSockets: 1000});31 if (err) {32 console.log(err);33 } else {34 console.log(res);35 }36});37var BestAgent = require('bestagent');38var agent = BestAgent.agent();39agent.agentConfig({maxSockets: 1000});40 if (err) {41 console.log(err);42 } else {43 console.log(res);44 }45});46var BestAgent = require('bestagent');47var agent = BestAgent.agent();48agent.agentConfig({maxSockets: 1000});49 if (err) {50 console.log(err);51 } else {52 console.log(res);53 }54});

Full Screen

Using AI Code Generation

copy

Full Screen

1var agent = require('best-practices-agent');2var config = agent.agentConfig();3config.set('agentName', 'test4');4config.set('agentVersion', '1.0.0');5config.set('agentDescription', 'test4 agent');6config.set('agentType', 'test4');7config.set('agentCategory', 'test4');8config.set('agentProvider', 'test4');9config.set('agentSource', 'test4');10config.set('agentVersion', '1.0.0');11config.set('agentDescription', 'test4 agent');12config.set('agentType', 'test4');13config.set('agentCategory', 'test4');14config.set('agentProvider', 'test4');15config.set('agentSource', 'test4');16config.set('agentVersion', '1.0.0');17config.set('agentDescription', 'test4 agent');18config.set('agentType', 'test4');19config.set('agentCategory', 'test4');20config.set('agentProvider', 'test4');21config.set('agentSource', 'test4');22var agent = require('best-practices-agent');23var config = agent.agentConfig();24config.set('agentName', 'test4');25config.set('agentVersion', '1.0.0');26config.set('agentDescription', 'test4 agent');27config.set('agentType', 'test4');28config.set('agentCategory', 'test4');29config.set('agentProvider', 'test4');30config.set('agentSource', 'test4');31config.set('agentVersion', '1.0.0');32config.set('agentDescription', 'test4 agent');33config.set('agentType', 'test4');34config.set('agentCategory', 'test4');35config.set('agentProvider', 'test4');36config.set('agentSource', 'test4');37config.set('agentVersion', '1.0.0');38config.set('agentDescription', 'test4 agent');39config.set('agentType', 'test4');40config.set('agentCategory', 'test4');41config.set('agentProvider', 'test4');42config.set('agentSource', 'test4');43var agent = require('best-practices-agent');44var config = agent.agentConfig();45config.set('agentName', 'test4');46config.set('agent

Full Screen

Using AI Code Generation

copy

Full Screen

1var bpa = require('bestpractice');2var agent = bpa.agentConfig();3agent.setAgentId('test4');4agent.setAgentName('test4');5agent.setAgentVersion('1.0.0');6agent.setAgentType('test4');7agent.setAgentDescription('test4');8agent.setAgentCategory('test4');9agent.setAgentSubCategory('test4');10agent.setAgentGroup('test4');11agent.setAgentOwner('test4');12agent.setAgentOwnerEmail('test4');13agent.setAgentOwnerPhone('test4');14agent.setAgentOwnerAddress('test4');15agent.setAgentOwnerCity('test4');16agent.setAgentOwnerState('test4');17agent.setAgentOwnerZip('test4');18agent.setAgentOwnerCountry('test4');19agent.setAgentOwnerOrganization('test4');20agent.setAgentOwnerOrganizationURL('test4');21agent.setAgentOwnerOrganizationEmail('test4');22agent.setAgentOwnerOrganizationPhone('test4');23agent.setAgentOwnerOrganizationAddress('test4');24agent.setAgentOwnerOrganizationCity('test4');25agent.setAgentOwnerOrganizationState('test4');26agent.setAgentOwnerOrganizationZip('test4');27agent.setAgentOwnerOrganizationCountry('test4');28agent.setAgentOwnerOrganizationLogoURL('test4');29agent.setAgentOwnerOrganizationLogoURLAltText('test4');30agent.setAgentOwnerOrganizationLogoURLWidth('test4');31agent.setAgentOwnerOrganizationLogoURLHeight('test4');32agent.setAgentOwnerOrganizationLogoURLType('test4');33agent.setAgentOwnerOrganizationLogoURLBase64('test4');34agent.setAgentOwnerOrganizationLogoURLBase64AltText('test4');35agent.setAgentOwnerOrganizationLogoURLBase64Width('test4');36agent.setAgentOwnerOrganizationLogoURLBase64Height('test4');37agent.setAgentOwnerOrganizationLogoURLBase64Type('test4');38agent.setAgentOwnerOrganizationLogoURLBase64Base64('test4');39agent.setAgentOwnerOrganizationLogoURLBase64Base64AltText('test4');40agent.setAgentOwnerOrganizationLogoURLBase64Base64Width('test4');41agent.setAgentOwnerOrganizationLogoURLBase64Base64Height('test4');42agent.setAgentOwnerOrganizationLogoURLBase64Base64Type('test4');43agent.setAgentOwnerOrganizationLogoURLBase64Base64Base64('test4');44agent.setAgentOwnerOrganizationLogoURLBase64Base64Base64AltText('test4');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful