launchdarkly.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. from datetime import datetime, timedelta
  10. from os import environ
  11. import launchdarkly_api # type: ignore
  12. from launchdarkly_api.api import feature_flags_api # type: ignore
  13. MAX_AGE = timedelta(hours=24)
  14. # Access keys required for interacting with LaunchDarkly.
  15. LAUNCHDARKLY_API_TOKEN = environ.get("LAUNCHDARKLY_API_TOKEN")
  16. def clean_up_test_features() -> None:
  17. print(f"Deleting LaunchDarkly features whose age exceeds {MAX_AGE}")
  18. configuration = launchdarkly_api.Configuration(
  19. api_key=dict(ApiKey=LAUNCHDARKLY_API_TOKEN)
  20. )
  21. with launchdarkly_api.ApiClient(configuration) as api_client:
  22. api = feature_flags_api.FeatureFlagsApi(api_client)
  23. project_key = "default"
  24. now = datetime.utcnow()
  25. flags = api.get_feature_flags(
  26. project_key,
  27. env="ci-cd",
  28. tag="ci-test",
  29. archived=True,
  30. )
  31. for flag in flags["items"]:
  32. key = flag["key"]
  33. age = now - datetime.fromtimestamp(flag["creation_date"] / 1000)
  34. if age <= MAX_AGE:
  35. print(f"Skipping flag {key} (age={age}) whose age is beneath threshold")
  36. else:
  37. try:
  38. print(f"Deleting flag {key} (age={age})")
  39. api.delete_feature_flag(project_key, key)
  40. except Exception as e:
  41. print(f"Error while trying to delete flag {key}: {e}")
  42. def main() -> None:
  43. clean_up_test_features()
  44. if __name__ == "__main__":
  45. main()