def BulkLabel(label, hostnames, token=None, client_index=None):
  if client_index is None:
    client_index = aff4.FACTORY.Create(
        MAIN_INDEX, aff4_type="ClientIndex", mode="rw", object_exists=True,
        token=token)

  fqdns = set()
  for hostname in hostnames:
    fqdns.add(hostname.lower())

  labelled_urns = client_index.LookupClients(["+label:%s" % label])

  # If a labelled client fqdn isn't in the set of target fqdns remove the label.
  # Labelled clients with a target fqdn need no action and are removed from the
  # set of target fqdns.
  for client in aff4.FACTORY.MultiOpen(labelled_urns, token=token,
                                       aff4_type="VFSGRRClient", mode="rw"):
    fqdn = utils.SmartStr(client.Get("FQDN")).lower()
    if fqdn not in fqdns:
      client_index.RemoveClientLabels(client)
      client.RemoveLabels(label, owner="GRR")
      client.Flush()
      client_index.AddClient(client)
    else:
      fqdns.discard(fqdn)

  # The residual set of fqdns needs labelling.
  # Get the latest URN for these clients and open them to add the label.
  urns = []
  keywords = ["+host:%s" % fqdn for fqdn in fqdns]
  for client_list in client_index.ReadClientPostingLists(keywords).itervalues():
    for client_id in client_list:
      urns.append(rdfvalue.RDFURN(client_id))

  for client in aff4.FACTORY.MultiOpen(urns, token=token,
                                       aff4_type="VFSGRRClient", mode="rw"):
    client.AddLabels(label, owner="GRR")
    client.Flush()
    client_index.AddClient(client)
Assign a label to a group of clients based on hostname.
dataset/ETHPy150Open google/grr/grr/lib/client_index.py/BulkLabel