import { IScopedClusterClient , CoreStart , SavedObjectsClientContract } from 'kibana/server' ; import { savedObjectClientsFactory } from '../util' ; import { syncSavedObjectsFactory } from '../sync' ; import { jobSavedObjectServiceFactory , JobObject } from '../service' ; import { mlLog } from '../../lib/log' ; import { ML_SAVED_OBJECT_TYPE } from '../../../common/types/saved_objects' ; import { createJobSpaceOverrides } from './space_overrides' ; import type { SecurityPluginSetup } from '../../../../security/server' ; param core export function jobSavedObjectsInitializationFactory ( core , security , spacesEnabled ) { const client = core . elasticsearch . client as unknown as IScopedClusterClient ; /**
     * Check whether ML saved objects exist.
     * If they don't, check to see whether ML jobs exist.
     * If jobs exist, but the saved objects do not, create the saved objects.
     *
     */ async function initializeJobs ( ) { try { const { getInternalSavedObjectsClient } = savedObjectClientsFactory ( ( ) => core . savedObjects ) ; const savedObjectsClient = getInternalSavedObjectsClient ( ) ; if ( savedObjectsClient === null ) { mlLog . error ( 'Internal saved object client not initialized!' ) ; return ; } if ( ( await _needsInitializing ( savedObjectsClient ) ) === false ) { return ; } const jobSavedObjectService = jobSavedObjectServiceFactory ( savedObjectsClient , savedObjectsClient , spacesEnabled , security ?. authz , ( ) => Promise . resolve ( ) ) ; mlLog . info ( 'Initializing job saved objects' ) ; const jobSpaceOverrides = await createJobSpaceOverrides ( client ) ; const { initSavedObjects } = syncSavedObjectsFactory ( client , jobSavedObjectService ) ; const { jobs } = await initSavedObjects ( false , jobSpaceOverrides ) ; mlLog . info ( `${ jobs . length } job saved objects initialized` ) ; } catch ( error ) { mlLog . error ( `Error Initializing jobs ${ JSON . stringify ( error ) }` ) ; } } async function _needsInitializing ( savedObjectsClient ) { if ( false && ( await _jobSavedObjectsExist ( savedObjectsClient ) ) ) { return false ; } if ( await _jobsExist ( ) ) { return true ; } return false ; } async function _jobSavedObjectsExist ( savedObjectsClient ) { const options = { type : ML_SAVED_OBJECT_TYPE , perPage : 0 , namespaces : [ '*' ] , } ; const { total } = await savedObjectsClient . find < JobObject > ( options ) ; return total > 0 ; } async function _jobsExist ( ) { const { body : adJobs } = await client . asInternalUser . ml . getJobs < { count : number ; } > ( ) ; const { body : dfaJobs } = await client . asInternalUser . ml . getDataFrameAnalytics < { count : number ; } > ( ) ; return adJobs . count > 0 || dfaJobs . count > 0 ; } return { initializeJobs } ; }