func()

in internal/locking/locking.go [37:110]


func (c *EtcdadmInitMutex) Lock(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) bool {
	sema := newSemaphore()
	cmName := configMapName(cluster.Name)
	log := c.log.WithValues("namespace", cluster.Namespace, "cluster-name", cluster.Name, "configmap-name", cmName, "machine-name", machine.Name)
	err := c.client.Get(ctx, client.ObjectKey{
		Namespace: cluster.Namespace,
		Name:      cmName,
	}, sema.ConfigMap)
	switch {
	case apierrors.IsNotFound(err):
		break
	case err != nil:
		log.Error(err, "Failed to acquire lock")
		return false
	default: // successfully found an existing config map
		info, err := sema.information()
		if err != nil {
			log.Error(err, "Failed to get information about the existing lock")
			return false
		}
		// the machine requesting the lock is the machine that created the lock, therefore the lock is acquired
		if info.MachineName == machine.Name {
			return true
		}

		machine := &clusterv1.Machine{}

		err = c.client.Get(ctx, client.ObjectKey{
			Namespace: eksaSystemNamespace,
			Name:      info.MachineName,
		}, machine)
		if err != nil {
			// Release the lock if for some reason the machine that acquired the lock
			// failed to launch due to a catastrophic event
			//
			// without this check we might end up with a deadlock.
			if apierrors.IsNotFound(err) {
				log.Info("Machine that has acquired the lock not found, releasing the lock", "init-machine", info.MachineName)
				if c.Unlock(ctx, cluster) {
					break
				} else {
					return false
				}
			} else {
				log.Error(err, "Failed to retreive machine", "machine", info.MachineName)
				return false
			}
		}

		log.Info("Waiting on another machine to initialize", "init-machine", info.MachineName)
		return false
	}

	// Adds owner reference, namespace and name
	sema.setMetadata(cluster)
	// Adds the additional information
	if err := sema.setInformation(&information{MachineName: machine.Name}); err != nil {
		log.Error(err, "Failed to acquire lock while setting semaphore information")
		return false
	}

	log.Info("Attempting to acquire the lock")
	err = c.client.Create(ctx, sema.ConfigMap)
	switch {
	case apierrors.IsAlreadyExists(err):
		log.Info("Cannot acquire the lock. The lock has been acquired by someone else")
		return false
	case err != nil:
		log.Error(err, "Error acquiring the lock")
		return false
	default:
		return true
	}
}