in pkg/controller/agent/fleet.go [300:356]
func reconcileEnrollmentToken(params Params, api fleetAPI) (EnrollmentAPIKey, error) {
defer api.client.CloseIdleConnections()
agent := params.Agent
ctx := params.Context
// do we have an existing token that we have rolled out previously?
tokenName, exists := agent.Annotations[FleetTokenAnnotation]
if !exists {
// setup fleet to create default policies (and tokens)
if err := api.setupFleet(ctx); err != nil {
return EnrollmentAPIKey{}, err
}
}
// what policy should we enroll this agent in?
policyID, err := findPolicyID(ctx, params.EventRecorder, agent, api)
if err != nil {
return EnrollmentAPIKey{}, err
}
if exists {
// get the enrollment token identified by the annotation
key, err := api.getEnrollmentAPIKey(ctx, tokenName)
// the annotation might contain corrupted or no longer valid information
if err != nil && commonhttp.IsNotFound(err) {
goto FindOrCreate
}
if err != nil {
return EnrollmentAPIKey{}, err
}
// if the token is valid and for the right policy we are done here
if key.Active && key.PolicyID == policyID {
return key, nil
}
}
FindOrCreate:
key, err := api.findEnrollmentAPIKey(ctx, policyID)
if err != nil && errors.Is(err, errNoMatchingTokenFound) {
ulog.FromContext(ctx).Info("Could not find existing Fleet enrollment API keys, creating new one", "error", err.Error())
key, err = api.createEnrollmentAPIKey(ctx, policyID)
if err != nil {
return EnrollmentAPIKey{}, err
}
}
if err != nil {
return EnrollmentAPIKey{}, err
}
// this potentially creates conflicts we could introduce reconciler state similar to the ES controller and handle it on the top level
if agent.Annotations == nil {
agent.Annotations = map[string]string{}
}
agent.Annotations[FleetTokenAnnotation] = key.ID
err = params.Client.Update(ctx, &agent)
if err != nil {
return EnrollmentAPIKey{}, err
}
return key, nil
}