Compare commits
94 commits
ceda93338b
...
776ba5e287
| Author | SHA1 | Date | |
|---|---|---|---|
|
776ba5e287 |
|||
|
f38eadc79e |
|||
|
141e028e49 |
|||
|
a4a6be7feb |
|||
|
9409e1f8d2 |
|||
|
cad1a9f46b |
|||
|
bf00d74a26 |
|||
|
825fabb64a |
|||
|
40b29657ae |
|||
|
ff17645c62 |
|||
|
d9f2ec4e67 |
|||
|
74d7fc1425 |
|||
|
beed163b02 |
|||
|
049cabc489 |
|||
|
1e7575bc7d |
|||
|
f8c0ee62ec |
|||
|
c7d20b4124 |
|||
|
3288a2a413 |
|||
|
deac1afe9f |
|||
|
02e558e0e2 |
|||
|
cfbac0034b |
|||
|
a346876cfb |
|||
|
5d980514b8 |
|||
|
2bbe9b40f7 |
|||
|
d3402dd163 |
|||
|
c1b9b3faa4 |
|||
|
88787fd8f7 |
|||
|
019ca104e8 |
|||
|
0b9714ce10 |
|||
|
f9c1cd7d32 |
|||
|
44f01c2373 |
|||
|
2ea3c6dd14 |
|||
|
6f40b3e921 |
|||
|
0b797d1c0c |
|||
|
d050568638 |
|||
|
9fb4d10d27 |
|||
|
d3b471b24a |
|||
|
db222b383c |
|||
|
fd4c7e9a3a |
|||
|
9420a9f7b4 |
|||
|
5a38e09b85 |
|||
|
15a913643e |
|||
|
fc62d5a524 |
|||
|
487972e698 |
|||
|
d1559b2ba0 |
|||
|
0d3d59a019 |
|||
|
a650a34fc3 |
|||
|
454005d6ac |
|||
|
473e1d0108 |
|||
|
00852ec1d3 |
|||
|
07cf77ba7d |
|||
|
a8ffeebb72 |
|||
|
9780947805 |
|||
|
37e345609e |
|||
|
24e3de8088 |
|||
|
44b58b3614 |
|||
|
c1c93f9618 |
|||
|
9892646814 |
|||
|
93a2bc6d33 |
|||
|
de7a678640 |
|||
|
8787904833 |
|||
|
7dbb508058 |
|||
|
f3898b288d |
|||
|
d2bc7e5b7a |
|||
|
fc624e7e96 |
|||
|
7b43cecc57 |
|||
|
e3583e7021 |
|||
|
2c6c1ff2df |
|||
|
348eb4aee3 |
|||
|
c2664e94fa |
|||
|
97132550b0 |
|||
|
38f2ed1b83 |
|||
|
b2d1922eaa |
|||
|
df95d8b4a7 |
|||
|
1ac1e61864 |
|||
|
55ed2c8e53 |
|||
|
b43e45488e |
|||
|
2418e08ee0 |
|||
|
014ae61dbb |
|||
|
1ac5a9fe49 |
|||
|
e1f317aeb9 |
|||
|
72b2e9afa9 |
|||
|
6a225a6162 |
|||
|
3831aa2d71 |
|||
|
6a3e849121 |
|||
|
fc6bb43616 |
|||
|
8d4a66bc89 |
|||
|
ec1d1e0588 |
|||
|
a50dcf6ad9 |
|||
|
6ed9d8abd9 |
|||
|
b25ce92c66 |
|||
|
05b3827e3c |
|||
|
f67376964a |
|||
|
25d4bfa0ee |
66 changed files with 2435 additions and 192 deletions
|
|
@ -32,7 +32,14 @@ jobs:
|
|||
matrix:
|
||||
goos: [linux]
|
||||
goarch: [amd64]
|
||||
binaries: [db, metadata]
|
||||
binaries:
|
||||
- db
|
||||
- metadata
|
||||
- metacli
|
||||
- agent
|
||||
- vpc
|
||||
- dhcp
|
||||
- subnet
|
||||
uses: ./.forgejo/workflows/build.yml
|
||||
with:
|
||||
tag: ${{ needs.set-release-target.outputs.release_cible }}
|
||||
|
|
@ -40,6 +47,24 @@ jobs:
|
|||
goarch: ${{ matrix.goarch }}
|
||||
binari: ${{ matrix.binaries }}
|
||||
secrets: inherit
|
||||
upload-scripts:
|
||||
runs-on: docker
|
||||
needs: [set-release-target]
|
||||
strategy:
|
||||
matrix:
|
||||
script:
|
||||
- run-dnsmasq-in-netns.sh
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Move asset
|
||||
run: |
|
||||
mkdir -p "dist"
|
||||
cp scripts/${{ matrix.script }} dist/
|
||||
- name: Upload script
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ matrix.script }}-${{ needs.set-release-target.outputs.release_cible }}
|
||||
path: dist/${{ matrix.script }}
|
||||
prerelease:
|
||||
runs-on: docker
|
||||
needs: [set-release-target, build]
|
||||
|
|
|
|||
229
LICENSE
229
LICENSE
|
|
@ -1,170 +1,131 @@
|
|||
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
||||
# PolyForm Noncommercial License 1.0.0
|
||||
|
||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
||||
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
## Acceptance
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
||||
In order to get any license under these terms, you must agree
|
||||
to them as both strict obligations and conditions to all
|
||||
your licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
|
||||
## Copyright License
|
||||
|
||||
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
|
||||
The licensor grants you a copyright license for the
|
||||
software to do everything you might do with the software
|
||||
that would otherwise infringe the licensor's copyright
|
||||
in it for any permitted purpose. However, you may
|
||||
only distribute the software according to [Distribution
|
||||
License](#distribution-license) and make changes or new works
|
||||
based on the software according to [Changes and New Works
|
||||
License](#changes-and-new-works-license).
|
||||
|
||||
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
||||
## Distribution License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
||||
The licensor grants you an additional copyright license
|
||||
to distribute copies of the software. Your license
|
||||
to distribute covers distributing the software with
|
||||
changes and new works permitted by [Changes and New Works
|
||||
License](#changes-and-new-works-license).
|
||||
|
||||
Section 1 – Definitions.
|
||||
## Notices
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
||||
You must ensure that anyone who gets a copy of any part of
|
||||
the software from you also gets a copy of these terms or the
|
||||
URL for them above, as well as copies of any plain-text lines
|
||||
beginning with `Required Notice:` that the licensor provided
|
||||
with the software. For example:
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
||||
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
||||
|
||||
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
||||
## Changes and New Works License
|
||||
|
||||
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
||||
The licensor grants you an additional copyright license to
|
||||
make changes and new works based on the software for any
|
||||
permitted purpose.
|
||||
|
||||
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
||||
## Patent License
|
||||
|
||||
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
||||
The licensor grants you a patent license for the software that
|
||||
covers patent claims the licensor can license, or becomes able
|
||||
to license, that you would infringe by using the software.
|
||||
|
||||
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
|
||||
## Noncommercial Purposes
|
||||
|
||||
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||
Any noncommercial purpose is a permitted purpose.
|
||||
|
||||
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
||||
## Personal Uses
|
||||
|
||||
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
||||
Personal use for research, experiment, and testing for
|
||||
the benefit of public knowledge, personal study, private
|
||||
entertainment, hobby projects, amateur pursuits, or religious
|
||||
observance, without any anticipated commercial application,
|
||||
is use for a permitted purpose.
|
||||
|
||||
k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
||||
## Noncommercial Organizations
|
||||
|
||||
l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
||||
Use by any charitable organization, educational institution,
|
||||
public research organization, public safety or health
|
||||
organization, environmental protection organization,
|
||||
or government institution is use for a permitted purpose
|
||||
regardless of the source of funding or obligations resulting
|
||||
from the funding.
|
||||
|
||||
m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
||||
## Fair Use
|
||||
|
||||
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
||||
You may have "fair use" rights for the software under the
|
||||
law. These terms do not limit them.
|
||||
|
||||
Section 2 – Scope.
|
||||
## No Other Rights
|
||||
|
||||
a. License grant.
|
||||
These terms do not allow you to sublicense or transfer any of
|
||||
your licenses to anyone else, or prevent the licensor from
|
||||
granting licenses to anyone else. These terms do not imply
|
||||
any other licenses.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
||||
## Patent Defense
|
||||
|
||||
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
||||
If you make any written claim that the software infringes or
|
||||
contributes to infringement of any patent, your patent license
|
||||
for the software granted under these terms ends immediately. If
|
||||
your company makes such a claim, your patent license ends
|
||||
immediately for work on behalf of your company.
|
||||
|
||||
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
||||
## Violations
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
||||
The first time you are notified in writing that you have
|
||||
violated any of these terms, or done anything with the software
|
||||
not covered by your licenses, your licenses can nonetheless
|
||||
continue if you come into full compliance with these terms,
|
||||
and take practical steps to correct past violations, within
|
||||
32 days of receiving notice. Otherwise, all your licenses
|
||||
end immediately.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section 6(a).
|
||||
## No Liability
|
||||
|
||||
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
||||
***As far as the law allows, the software comes as is, without
|
||||
any warranty or condition, and the licensor will not be liable
|
||||
to you for any damages arising out of these terms or the use
|
||||
or nature of the software, under any kind of legal claim.***
|
||||
|
||||
5. Downstream recipients.
|
||||
## Definitions
|
||||
|
||||
A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
||||
The **licensor** is the individual or entity offering these
|
||||
terms, and the **software** is the software the licensor makes
|
||||
available under these terms.
|
||||
|
||||
B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
|
||||
**You** refers to the individual or entity agreeing to these
|
||||
terms.
|
||||
|
||||
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
||||
**Your company** is any legal entity, sole proprietorship,
|
||||
or other kind of organization that you work for, plus all
|
||||
organizations that have control over, are under the control of,
|
||||
or are under common control with that organization. **Control**
|
||||
means ownership of substantially all the assets of an entity,
|
||||
or the power to direct its management and policies by vote,
|
||||
contract, or otherwise. Control can be direct or indirect.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
||||
**Your licenses** are all the licenses granted to you for the
|
||||
software under these terms.
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
||||
|
||||
Section 3 – License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified form), You must:
|
||||
|
||||
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||
|
||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||
|
||||
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||
|
||||
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
|
||||
|
||||
Section 4 – Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
||||
|
||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
||||
|
||||
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
|
||||
|
||||
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
||||
|
||||
Section 6 – Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||
|
||||
Section 7 – Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
||||
|
||||
Section 8 – Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
||||
|
||||
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
**Use** means anything you do with the software requiring one
|
||||
of your licenses.
|
||||
|
|
|
|||
11
NOTICE.md
Normal file
11
NOTICE.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# 🔒 Utilisation de logiciels open source
|
||||
|
||||
Notre logiciel utilise des composants open source, notamment **NetBox**, un outil de gestion d'infrastructure réseau développé par la communauté NetBox.
|
||||
|
||||
NetBox est distribué sous la **licence Apache License, Version 2.0**. Vous pouvez consulter cette licence à l'adresse suivante :
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Aucune modification n’a été apportée à NetBox dans notre intégration. Il est utilisé tel quel, en tant que base de données d'infrastructure.
|
||||
|
||||
Copyright © 2025 NetBox Contributors.
|
||||
Nous reconnaissons et respectons le travail de la communauté NetBox.
|
||||
17
cmd/agent/main.go
Normal file
17
cmd/agent/main.go
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
bin_name = os.Args[0]
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
fmt.Printf("%s: Start process\n", bin_name)
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
|
@ -51,17 +52,13 @@ func AddInDB(dbName string, line string) error {
|
|||
id := strings.Split(line, ";")[0] + "/bash"
|
||||
key := []byte(dbName + "/" + id)
|
||||
|
||||
return DB.Update(func(txn *badger.Txn) error {
|
||||
return txn.Set(key, []byte(line))
|
||||
})
|
||||
return kv.AddInDB(DB, string(key), line)
|
||||
}
|
||||
|
||||
func DeleteInDB(dbName, id string) error {
|
||||
key := []byte(dbName + "/" + id + "/bash")
|
||||
|
||||
return DB.Update(func(txn *badger.Txn) error {
|
||||
return txn.Delete(key)
|
||||
})
|
||||
return kv.DeleteInDB(DB, string(key))
|
||||
}
|
||||
|
||||
func CountInDB(dbName, id string) int {
|
||||
|
|
@ -125,7 +122,13 @@ func printDB() {
|
|||
}
|
||||
|
||||
func main() {
|
||||
conf, err := configuration.LoadConfig("/etc/two/agent.yml")
|
||||
conf_file := flag.String("conf", "/etc/two/agent.yml", "configuration file")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
args := flag.Args()
|
||||
|
||||
conf, err := configuration.LoadConfig(*conf_file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
|
|
@ -133,56 +136,56 @@ func main() {
|
|||
|
||||
DB = kv.InitDB(kv.Config{
|
||||
Path: conf.Database.Path,
|
||||
})
|
||||
}, false)
|
||||
defer DB.Close()
|
||||
|
||||
if len(os.Args) < 2 {
|
||||
if len(args) < 1 {
|
||||
fmt.Println("Usage: db <cmd> [args...]")
|
||||
return
|
||||
}
|
||||
|
||||
cmd := os.Args[1]
|
||||
cmd := args[0]
|
||||
|
||||
switch cmd {
|
||||
case "check_in_db":
|
||||
if len(os.Args) != 4 {
|
||||
if len(args) != 3 {
|
||||
fmt.Println("Usage: check_in_db <db_name> <id>")
|
||||
os.Exit(1)
|
||||
}
|
||||
ret := CheckInDB(os.Args[2], os.Args[3])
|
||||
ret := CheckInDB(args[1], args[2])
|
||||
os.Exit(ret)
|
||||
case "add_in_db":
|
||||
if len(os.Args) < 4 {
|
||||
if len(args) < 3 {
|
||||
fmt.Println("Usage: add_in_db <db_name> <line...>")
|
||||
os.Exit(1)
|
||||
}
|
||||
line := strings.Join(os.Args[3:], ";")
|
||||
if err := AddInDB(os.Args[2], line); err != nil {
|
||||
line := strings.Join(args[2:], ";")
|
||||
if err := AddInDB(args[1], line); err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
case "delete_in_db":
|
||||
if len(os.Args) != 4 {
|
||||
if len(args) != 3 {
|
||||
fmt.Println("Usage: delete_in_db <db_name> <id>")
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := DeleteInDB(os.Args[2], os.Args[3]); err != nil {
|
||||
if err := DeleteInDB(args[1], args[2]); err != nil {
|
||||
fmt.Println("Error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
case "count_in_db":
|
||||
if len(os.Args) != 4 {
|
||||
if len(args) != 3 {
|
||||
fmt.Println("Usage: count_in_db <db_name> <id>")
|
||||
os.Exit(1)
|
||||
}
|
||||
count := CountInDB(os.Args[2], os.Args[3])
|
||||
count := CountInDB(args[1], args[2])
|
||||
fmt.Println(count)
|
||||
case "get_from_db":
|
||||
if len(os.Args) != 4 {
|
||||
if len(args) != 3 {
|
||||
fmt.Println("Usage: get_from_db <db_name> <id>")
|
||||
os.Exit(1)
|
||||
}
|
||||
line, _ := GetFromDB(os.Args[2], os.Args[3])
|
||||
line, _ := GetFromDB(args[1], args[2])
|
||||
fmt.Println(line)
|
||||
case "print":
|
||||
printDB()
|
||||
|
|
|
|||
64
cmd/dhcp/main.go
Normal file
64
cmd/dhcp/main.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
"git.g3e.fr/syonad/two/internal/dhcp"
|
||||
"git.g3e.fr/syonad/two/pkg/systemd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
subnet := flag.String("subnet", "", "Subnet CIDR (e.g. 10.10.10.0/24)")
|
||||
name := flag.String("name", "", "Config name (e.g. vpc1_br-00002)")
|
||||
gateway := flag.String("gateway", "", "Gateway IP (e.g. 10.10.10.1)")
|
||||
confDir := flag.String("confdir", "/etc/dnsmasq.d", "dnsmasq config directory")
|
||||
flag.Parse()
|
||||
|
||||
if *subnet == "" || *name == "" || *gateway == "" {
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
_, network, err := net.ParseCIDR(*subnet)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid subnet: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
gw := net.ParseIP(*gateway)
|
||||
if gw == nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid gateway IP: %q\n", *gateway)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
conf := dhcp.Config{
|
||||
Network: network,
|
||||
Gateway: gw,
|
||||
Name: *name,
|
||||
ConfDir: *confDir,
|
||||
}
|
||||
|
||||
confPath, err := dhcp.GenerateConfig(conf)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error generating config: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("dnsmasq config written to %s\n", confPath)
|
||||
|
||||
svc, err := systemd.New()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error connecting to systemd: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer svc.Close()
|
||||
|
||||
unit := "dnsmasq@" + *name + ".service"
|
||||
if err := svc.Start(unit); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "error starting %s: %v\n", unit, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("started %s\n", unit)
|
||||
}
|
||||
53
cmd/metacli/main.go
Normal file
53
cmd/metacli/main.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
configuration "git.g3e.fr/syonad/two/internal/config/agent"
|
||||
"git.g3e.fr/syonad/two/internal/metadata"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
conf_file := flag.String("conf", "/etc/two/agent.yml", "configuration file")
|
||||
vm_name := flag.String("vm_name", "", "Nom de la vm")
|
||||
vpc := flag.String("vpc_name", "", "vpc name")
|
||||
bind_ip := flag.String("ip", "", "bind ip")
|
||||
bind_port := flag.String("port", "", "bind port")
|
||||
ssh_key := flag.String("key", "", "Clef ssh")
|
||||
password := flag.String("pass", "", "password user")
|
||||
start := flag.Bool("start", false, "start metadata server")
|
||||
stop := flag.Bool("stop", false, "stop metadata server")
|
||||
dryrun := flag.Bool("dryrun", false, "launch in dry node")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
conf, err := configuration.LoadConfig(*conf_file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
db := kv.InitDB(kv.Config{
|
||||
Path: conf.Database.Path,
|
||||
}, false)
|
||||
defer db.Close()
|
||||
|
||||
if *start {
|
||||
if err := metadata.StartMetadata(metadata.NoCloudConfig{
|
||||
VpcName: *vpc,
|
||||
Name: *vm_name,
|
||||
BindIP: *bind_ip,
|
||||
BindPort: *bind_port,
|
||||
Password: *password,
|
||||
SSHKEY: *ssh_key,
|
||||
}, db, *dryrun); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
} else if *stop {
|
||||
if err := metadata.StopMetadata(*vm_name, db, *dryrun); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
|
||||
"git.g3e.fr/syonad/two/internal/metadata"
|
||||
)
|
||||
|
||||
var (
|
||||
iface = flag.String("interface", "0.0.0.0", "Interface IP à écouter")
|
||||
port = flag.Int("port", 0, "Port à utiliser")
|
||||
netns_name = flag.String("netns", "", "Network namespace à utiliser")
|
||||
conf_file = flag.String("conf", "/etc/two/agent.yml", "configuration file")
|
||||
vm_name = flag.String("vm", "", "Name of the vm")
|
||||
)
|
||||
|
||||
func main() {
|
||||
metadata.StartServer()
|
||||
flag.Parse()
|
||||
|
||||
metadata.StartServer(metadata.ServerConfig{
|
||||
Netns: *netns_name,
|
||||
Iface: *iface,
|
||||
Port: *port,
|
||||
ConfFile: *conf_file,
|
||||
VmName: *vm_name,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
93
cmd/subnet/main.go
Normal file
93
cmd/subnet/main.go
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
configuration "git.g3e.fr/syonad/two/internal/config/agent"
|
||||
"git.g3e.fr/syonad/two/internal/subnet"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
var (
|
||||
name = flag.String("name", "", "Subnet name (ex: sn-00001)")
|
||||
vpcName = flag.String("vpc", "", "VPC name")
|
||||
vxlanID = flag.String("vxlan-id", "", "VXLAN ID")
|
||||
localIP = flag.String("local-ip", "", "Local VTEP IP")
|
||||
gatewayIP = flag.String("gateway-ip", "", "Gateway IP")
|
||||
cidr = flag.String("cidr", "", "Subnet CIDR (ex: 10.10.10.0/24)")
|
||||
action = flag.String("action", "", "Action à effectuer")
|
||||
conf_file = flag.String("conf", "/etc/two/agent.yml", "Configuration file")
|
||||
)
|
||||
|
||||
var DB *badger.DB
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
conf, err := configuration.LoadConfig(*conf_file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
DB = kv.InitDB(kv.Config{
|
||||
Path: conf.Database.Path,
|
||||
}, false)
|
||||
defer DB.Close()
|
||||
|
||||
switch *action {
|
||||
case "create":
|
||||
if *name == "" || *vpcName == "" || *vxlanID == "" || *localIP == "" || *gatewayIP == "" || *cidr == "" {
|
||||
fmt.Println("create requires: -name -vpc -vxlan-id -local-ip -gateway-ip -cidr")
|
||||
os.Exit(1)
|
||||
}
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/state", "creating")
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/vpc", *vpcName)
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/vxlan_id", *vxlanID)
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/local_ip", *localIP)
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/gateway_ip", *gatewayIP)
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/cidr", *cidr)
|
||||
if err := subnet.CreateSubnet(DB, *name); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
case "delete":
|
||||
if *name == "" {
|
||||
fmt.Println("delete requires: -name")
|
||||
os.Exit(1)
|
||||
}
|
||||
kv.AddInDB(DB, "subnet/"+*name+"/state", "deleting")
|
||||
if err := subnet.DeleteSubnet(DB, *name); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if state, err := kv.GetFromDB(DB, "subnet/"+*name+"/state"); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
} else if state == "deleted" {
|
||||
kv.DeleteInDB(DB, "subnet/"+*name)
|
||||
}
|
||||
|
||||
case "check":
|
||||
if *name == "" {
|
||||
fmt.Println("check requires: -name")
|
||||
os.Exit(1)
|
||||
}
|
||||
if state, err := kv.GetFromDB(DB, "subnet/"+*name+"/state"); err != nil {
|
||||
os.Exit(1)
|
||||
} else if state != "created" {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
default:
|
||||
fmt.Printf("Available commands:\n - create\n - delete\n - check\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
65
cmd/vpc/main.go
Normal file
65
cmd/vpc/main.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
configuration "git.g3e.fr/syonad/two/internal/config/agent"
|
||||
"git.g3e.fr/syonad/two/internal/vpc"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
var (
|
||||
netns = flag.String("netns", "", "Network namespace à faire")
|
||||
name = flag.String("name", "", "interface name")
|
||||
action = flag.String("action", "", "Action a faire")
|
||||
conf_file = flag.String("conf", "/etc/two/agent.yml", "configuration file")
|
||||
)
|
||||
|
||||
var DB *badger.DB
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
conf, err := configuration.LoadConfig(*conf_file)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
DB = kv.InitDB(kv.Config{
|
||||
Path: conf.Database.Path,
|
||||
}, false)
|
||||
defer DB.Close()
|
||||
|
||||
switch *action {
|
||||
case "create":
|
||||
kv.AddInDB(DB, "vpc/"+*name+"/state", "creating")
|
||||
if err := vpc.CreateVPC(DB, *name); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
case "delete":
|
||||
kv.AddInDB(DB, "vpc/"+*name+"/state", "deleting")
|
||||
if err := vpc.DeleteVPC(DB, *name); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
if state, err := kv.GetFromDB(DB, "vpc/"+*name+"/state"); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
} else if state == "deleted" {
|
||||
kv.DeleteInDB(DB, "vpc/"+*name)
|
||||
}
|
||||
case "check":
|
||||
if state, err := kv.GetFromDB(DB, "vpc/"+*name+"/state"); err != nil {
|
||||
os.Exit(1)
|
||||
} else if state != "created" {
|
||||
os.Exit(1)
|
||||
}
|
||||
default:
|
||||
fmt.Printf("Available commande:\n - create\n - delete\n - check\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
2
conf/agent/config.dev.yml
Normal file
2
conf/agent/config.dev.yml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
database:
|
||||
path: "./data/"
|
||||
10
go.mod
10
go.mod
|
|
@ -1,9 +1,12 @@
|
|||
module git.g3e.fr/syonad/two
|
||||
|
||||
go 1.23.8
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.11
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.6.0 // indirect
|
||||
github.com/dgraph-io/badger/v4 v4.8.0 // indirect
|
||||
github.com/dgraph-io/ristretto/v2 v2.2.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
|
|
@ -11,6 +14,7 @@ require (
|
|||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/google/flatbuffers v25.2.10+incompatible // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
|
|
@ -21,13 +25,15 @@ require (
|
|||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/spf13/viper v1.21.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/vishvananda/netlink v1.3.1 // indirect
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.37.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/net v0.41.0 // indirect
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
)
|
||||
|
|
|
|||
12
go.sum
12
go.sum
|
|
@ -1,5 +1,7 @@
|
|||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coreos/go-systemd/v22 v22.6.0 h1:aGVa/v8B7hpb0TKl0MWoAavPDmHvobFe5R5zn0bCJWo=
|
||||
github.com/coreos/go-systemd/v22 v22.6.0/go.mod h1:iG+pp635Fo7ZmV/j14KUcmEyWF+0X7Lua8rrTWzYgWU=
|
||||
github.com/dgraph-io/badger/v4 v4.8.0 h1:JYph1ChBijCw8SLeybvPINizbDKWZ5n/GYbz2yhN/bs=
|
||||
github.com/dgraph-io/badger/v4 v4.8.0/go.mod h1:U6on6e8k/RTbUWxqKR0MvugJuVmkxSNc79ap4917h4w=
|
||||
github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM=
|
||||
|
|
@ -15,6 +17,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
|||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q=
|
||||
github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
|
|
@ -35,6 +39,10 @@ github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
|||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
|
||||
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||
|
|
@ -47,8 +55,12 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
|||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
|
||||
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
|
|
|
|||
83
internal/config/agent/config_test.go
Normal file
83
internal/config/agent/config_test.go
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeYAML(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "config.yml")
|
||||
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
||||
t.Fatalf("impossible d'écrire le fichier de config : %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// --- LoadConfig ---
|
||||
|
||||
func TestLoadConfig_ValidFile(t *testing.T) {
|
||||
path := writeYAML(t, `
|
||||
database:
|
||||
path: /tmp/mydb
|
||||
`)
|
||||
cfg, err := LoadConfig(path)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadConfig a échoué : %v", err)
|
||||
}
|
||||
if cfg.Database.Path != "/tmp/mydb" {
|
||||
t.Errorf("database.path attendu %q, obtenu %q", "/tmp/mydb", cfg.Database.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfig_DefaultPath(t *testing.T) {
|
||||
// Fichier vide → viper applique la valeur par défaut
|
||||
path := writeYAML(t, "")
|
||||
cfg, err := LoadConfig(path)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadConfig a échoué : %v", err)
|
||||
}
|
||||
if cfg.Database.Path != "/var/lib/two/data/" {
|
||||
t.Errorf("valeur par défaut attendue %q, obtenu %q", "/var/lib/two/data/", cfg.Database.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfig_MissingFile_UsesDefaults(t *testing.T) {
|
||||
// Fichier inexistant : viper ignore l'erreur ReadInConfig et retourne les défauts
|
||||
cfg, err := LoadConfig("/chemin/inexistant/config.yml")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadConfig devrait retourner les défauts si le fichier est absent : %v", err)
|
||||
}
|
||||
if cfg.Database.Path != "/var/lib/two/data/" {
|
||||
t.Errorf("valeur par défaut attendue, obtenu %q", cfg.Database.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfig_PartialConfig_MissingDatabaseKey(t *testing.T) {
|
||||
// Fichier sans la clé database → valeur par défaut
|
||||
path := writeYAML(t, `
|
||||
autrekey: valeur
|
||||
`)
|
||||
cfg, err := LoadConfig(path)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadConfig a échoué : %v", err)
|
||||
}
|
||||
if cfg.Database.Path != "/var/lib/two/data/" {
|
||||
t.Errorf("valeur par défaut attendue, obtenu %q", cfg.Database.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfig_CustomPath(t *testing.T) {
|
||||
path := writeYAML(t, `
|
||||
database:
|
||||
path: /opt/two/data
|
||||
`)
|
||||
cfg, err := LoadConfig(path)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadConfig a échoué : %v", err)
|
||||
}
|
||||
if cfg.Database.Path != "/opt/two/data" {
|
||||
t.Errorf("attendu %q, obtenu %q", "/opt/two/data", cfg.Database.Path)
|
||||
}
|
||||
}
|
||||
|
|
@ -17,9 +17,7 @@ func LoadConfig(path string) (*Config, error) {
|
|||
|
||||
v.SetDefault("database.path", "/var/lib/two/data/")
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.ReadInConfig()
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
|
|
|
|||
157
internal/dhcp/dhcp_test.go
Normal file
157
internal/dhcp/dhcp_test.go
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
package dhcp
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func parseNet(t *testing.T, cidr string) *net.IPNet {
|
||||
t.Helper()
|
||||
_, network, err := net.ParseCIDR(cidr)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCIDR(%q) : %v", cidr, err)
|
||||
}
|
||||
return network
|
||||
}
|
||||
|
||||
// --- cloneIP ---
|
||||
|
||||
func TestCloneIP_IsIndependent(t *testing.T) {
|
||||
ip := net.ParseIP("10.0.0.1").To4()
|
||||
clone := cloneIP(ip)
|
||||
clone[3] = 99
|
||||
if ip[3] == 99 {
|
||||
t.Error("cloneIP devrait retourner une copie indépendante")
|
||||
}
|
||||
}
|
||||
|
||||
// --- incrementIP ---
|
||||
|
||||
func TestIncrementIP_Simple(t *testing.T) {
|
||||
ip := net.ParseIP("10.0.0.1").To4()
|
||||
incrementIP(ip)
|
||||
if ip.String() != "10.0.0.2" {
|
||||
t.Errorf("attendu 10.0.0.2, obtenu %s", ip)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementIP_Carry(t *testing.T) {
|
||||
ip := net.ParseIP("10.0.0.255").To4()
|
||||
incrementIP(ip)
|
||||
if ip.String() != "10.0.1.0" {
|
||||
t.Errorf("attendu 10.0.1.0, obtenu %s", ip)
|
||||
}
|
||||
}
|
||||
|
||||
// --- GenerateConfig ---
|
||||
|
||||
func newConf(t *testing.T, cidr string) Config {
|
||||
t.Helper()
|
||||
_, network, _ := net.ParseCIDR(cidr)
|
||||
return Config{
|
||||
Network: network,
|
||||
Gateway: net.ParseIP("192.168.1.1").To4(),
|
||||
Name: "test",
|
||||
ConfDir: t.TempDir(),
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_CreatesFile(t *testing.T) {
|
||||
conf := newConf(t, "192.168.1.0/29") // 6 hôtes
|
||||
path, err := GenerateConfig(conf)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateConfig a échoué : %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
t.Errorf("le fichier %q n'a pas été créé", path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_FilenameMatchesName(t *testing.T) {
|
||||
conf := newConf(t, "192.168.1.0/29")
|
||||
path, err := GenerateConfig(conf)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateConfig a échoué : %v", err)
|
||||
}
|
||||
|
||||
expected := filepath.Join(conf.ConfDir, "test.conf")
|
||||
if path != expected {
|
||||
t.Errorf("chemin attendu %q, obtenu %q", expected, path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_ContainsGateway(t *testing.T) {
|
||||
conf := newConf(t, "192.168.1.0/29")
|
||||
path, _ := GenerateConfig(conf)
|
||||
content, _ := os.ReadFile(path)
|
||||
|
||||
if !strings.Contains(string(content), "dhcp-option=3,192.168.1.1") {
|
||||
t.Errorf("gateway absente du fichier généré :\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_ContainsDhcpRange(t *testing.T) {
|
||||
_, network, _ := net.ParseCIDR("10.10.0.0/24")
|
||||
conf := Config{
|
||||
Network: network,
|
||||
Gateway: net.ParseIP("10.10.0.1").To4(),
|
||||
Name: "vpc1",
|
||||
ConfDir: t.TempDir(),
|
||||
}
|
||||
path, _ := GenerateConfig(conf)
|
||||
content, _ := os.ReadFile(path)
|
||||
|
||||
if !strings.Contains(string(content), "dhcp-range=10.10.0.0,static,255.255.255.0,12h") {
|
||||
t.Errorf("dhcp-range absent ou incorrect :\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_OneHostEntryPerIP(t *testing.T) {
|
||||
// /29 = réseau + broadcast + 6 hôtes → 8 adresses
|
||||
conf := newConf(t, "10.0.0.0/29")
|
||||
path, _ := GenerateConfig(conf)
|
||||
content, _ := os.ReadFile(path)
|
||||
|
||||
lines := strings.Split(string(content), "\n")
|
||||
count := 0
|
||||
for _, l := range lines {
|
||||
if strings.HasPrefix(l, "dhcp-host=") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
// /29 contient 8 adresses (0 à 7)
|
||||
if count != 8 {
|
||||
t.Errorf("attendu 8 entrées dhcp-host, obtenu %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_MACPrefix(t *testing.T) {
|
||||
conf := newConf(t, "10.0.0.0/30") // 4 adresses
|
||||
path, _ := GenerateConfig(conf)
|
||||
content, _ := os.ReadFile(path)
|
||||
|
||||
if !strings.Contains(string(content), "00:22:33:") {
|
||||
t.Errorf("préfixe MAC 00:22:33: absent :\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateConfig_CreatesConfDir(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "sous", "dossier")
|
||||
_, network, _ := net.ParseCIDR("10.0.0.0/30")
|
||||
conf := Config{
|
||||
Network: network,
|
||||
Gateway: net.ParseIP("10.0.0.1").To4(),
|
||||
Name: "net",
|
||||
ConfDir: dir,
|
||||
}
|
||||
if _, err := GenerateConfig(conf); err != nil {
|
||||
t.Fatalf("GenerateConfig devrait créer les répertoires manquants : %v", err)
|
||||
}
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
t.Errorf("répertoire %q non créé", dir)
|
||||
}
|
||||
}
|
||||
47
internal/dhcp/generate.go
Normal file
47
internal/dhcp/generate.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package dhcp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GenerateConfig(c Config) (string, error) {
|
||||
mask := fmt.Sprintf("%d.%d.%d.%d", c.Network.Mask[0], c.Network.Mask[1], c.Network.Mask[2], c.Network.Mask[3])
|
||||
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "no-resolv\n")
|
||||
fmt.Fprintf(&sb, "dhcp-range=%s,static,%s,12h\n", c.Network.IP.String(), mask)
|
||||
fmt.Fprintf(&sb, "dhcp-option=3,%s\n", c.Gateway.String())
|
||||
fmt.Fprintf(&sb, "dhcp-option=6,1.1.1.1,8.8.8.8\n\n")
|
||||
|
||||
i := 0
|
||||
for ip := cloneIP(c.Network.IP); c.Network.Contains(ip); incrementIP(ip) {
|
||||
fmt.Fprintf(&sb, "dhcp-host=00:22:33:%02X:%02X:%02X,%s\n",
|
||||
(i>>16)&0xFF, (i>>8)&0xFF, i&0xFF, ip)
|
||||
i++
|
||||
}
|
||||
|
||||
outPath := filepath.Join(c.ConfDir, c.Name+".conf")
|
||||
if err := os.MkdirAll(c.ConfDir, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return outPath, os.WriteFile(outPath, []byte(sb.String()), 0644)
|
||||
}
|
||||
|
||||
func incrementIP(ip net.IP) {
|
||||
for j := len(ip) - 1; j >= 0; j-- {
|
||||
ip[j]++
|
||||
if ip[j] != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cloneIP(ip net.IP) net.IP {
|
||||
clone := make(net.IP, len(ip))
|
||||
copy(clone, ip)
|
||||
return clone
|
||||
}
|
||||
12
internal/dhcp/struct.go
Normal file
12
internal/dhcp/struct.go
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
package dhcp
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Network *net.IPNet
|
||||
Gateway net.IP
|
||||
Name string
|
||||
ConfDir string
|
||||
}
|
||||
40
internal/metadata/handle.go
Normal file
40
internal/metadata/handle.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
package metadata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.g3e.fr/syonad/two/pkg/systemd"
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func StartMetadata(config NoCloudConfig, db *badger.DB, dryrun bool) error {
|
||||
service, err := systemd.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to systemd: %w", err)
|
||||
}
|
||||
defer service.Close()
|
||||
|
||||
LoadNcCloudInDB(config, db)
|
||||
if !dryrun {
|
||||
if err := service.Start("metadata@" + config.Name + ".service"); err != nil {
|
||||
return fmt.Errorf("failed to start metadata@%s: %w", config.Name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func StopMetadata(vm_name string, db *badger.DB, dryrun bool) error {
|
||||
service, err := systemd.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to systemd: %w", err)
|
||||
}
|
||||
defer service.Close()
|
||||
|
||||
UnLoadNoCloudInDB(vm_name, db)
|
||||
if !dryrun {
|
||||
if err := service.Stop("metadata@" + vm_name + ".service"); err != nil {
|
||||
return fmt.Errorf("failed to stop metadata@%s: %w", vm_name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
200
internal/metadata/metadata_test.go
Normal file
200
internal/metadata/metadata_test.go
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
package metadata
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
)
|
||||
|
||||
func newCfg() NoCloudConfig {
|
||||
return NoCloudConfig{
|
||||
VpcName: "vpc-test",
|
||||
BindIP: "169.254.169.254",
|
||||
BindPort: "80",
|
||||
Name: "vm1",
|
||||
Password: "s3cr3t",
|
||||
SSHKEY: "ssh-ed25519 AAAA... user@host",
|
||||
}
|
||||
}
|
||||
|
||||
func newTestDB(t *testing.T) interface{ Close() error } {
|
||||
t.Helper()
|
||||
db := kv.InitDB(kv.Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
// --- RenderConfig ---
|
||||
|
||||
func TestRenderConfig_MetaData(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
out, err := RenderConfig("templates/meta-data.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig meta-data : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "instance-id: vm1") {
|
||||
t.Errorf("instance-id absent :\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "local-hostname: vm1") {
|
||||
t.Errorf("local-hostname absent :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_VendorData_ContainsPassword(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
out, err := RenderConfig("templates/vendor-data.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig vendor-data : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "s3cr3t") {
|
||||
t.Errorf("password absent du vendor-data :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_VendorData_ContainsSSHKey(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
out, err := RenderConfig("templates/vendor-data.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig vendor-data : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "ssh-ed25519 AAAA... user@host") {
|
||||
t.Errorf("clé SSH absente du vendor-data :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_NetworkConfig(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
out, err := RenderConfig("templates/network-config.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig network-config : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "dhcp4: true") {
|
||||
t.Errorf("dhcp4 absent du network-config :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_UserData(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
out, err := RenderConfig("templates/user-data.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig user-data : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "passwd -d root") {
|
||||
t.Errorf("user-data inattendu :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_InvalidTemplate(t *testing.T) {
|
||||
_, err := RenderConfig("templates/inexistant.tmpl", newCfg())
|
||||
if err == nil {
|
||||
t.Error("RenderConfig devrait retourner une erreur pour un template inexistant")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderConfig_SpecialCharsInName(t *testing.T) {
|
||||
cfg := newCfg()
|
||||
cfg.Name = "vm-prod-01"
|
||||
out, err := RenderConfig("templates/meta-data.tmpl", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("RenderConfig : %v", err)
|
||||
}
|
||||
if !strings.Contains(out, "vm-prod-01") {
|
||||
t.Errorf("nom vm-prod-01 absent :\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// --- LoadNcCloudInDB / UnLoadNoCloudInDB ---
|
||||
|
||||
func TestLoadNcCloudInDB_StoresAllKeys(t *testing.T) {
|
||||
db := kv.InitDB(kv.Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
cfg := newCfg()
|
||||
LoadNcCloudInDB(cfg, db)
|
||||
|
||||
keys := []string{
|
||||
"metadata/vm1/meta-data",
|
||||
"metadata/vm1/user-data",
|
||||
"metadata/vm1/network-config",
|
||||
"metadata/vm1/vendor-data",
|
||||
"metadata/vm1/vpc",
|
||||
"metadata/vm1/bind_ip",
|
||||
"metadata/vm1/bind_port",
|
||||
}
|
||||
for _, key := range keys {
|
||||
val, err := kv.GetFromDB(db, key)
|
||||
if err != nil {
|
||||
t.Errorf("clé %q absente après LoadNcCloudInDB : %v", key, err)
|
||||
}
|
||||
if val == "" && key != "metadata/vm1/user-data" {
|
||||
t.Errorf("clé %q vide après LoadNcCloudInDB", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNcCloudInDB_VpcAndBindValues(t *testing.T) {
|
||||
db := kv.InitDB(kv.Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
cfg := newCfg()
|
||||
LoadNcCloudInDB(cfg, db)
|
||||
|
||||
vpc, _ := kv.GetFromDB(db, "metadata/vm1/vpc")
|
||||
if vpc != "vpc-test" {
|
||||
t.Errorf("vpc attendu %q, obtenu %q", "vpc-test", vpc)
|
||||
}
|
||||
|
||||
ip, _ := kv.GetFromDB(db, "metadata/vm1/bind_ip")
|
||||
if ip != "169.254.169.254" {
|
||||
t.Errorf("bind_ip attendu %q, obtenu %q", "169.254.169.254", ip)
|
||||
}
|
||||
|
||||
port, _ := kv.GetFromDB(db, "metadata/vm1/bind_port")
|
||||
if port != "80" {
|
||||
t.Errorf("bind_port attendu %q, obtenu %q", "80", port)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnLoadNoCloudInDB_RemovesAllKeys(t *testing.T) {
|
||||
db := kv.InitDB(kv.Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
cfg := newCfg()
|
||||
LoadNcCloudInDB(cfg, db)
|
||||
UnLoadNoCloudInDB("vm1", db)
|
||||
|
||||
keys := []string{
|
||||
"metadata/vm1/meta-data",
|
||||
"metadata/vm1/user-data",
|
||||
"metadata/vm1/network-config",
|
||||
"metadata/vm1/vendor-data",
|
||||
"metadata/vm1/vpc",
|
||||
"metadata/vm1/bind_ip",
|
||||
"metadata/vm1/bind_port",
|
||||
}
|
||||
for _, key := range keys {
|
||||
_, err := kv.GetFromDB(db, key)
|
||||
if err == nil {
|
||||
t.Errorf("clé %q devrait être supprimée après UnLoadNoCloudInDB", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnLoadNoCloudInDB_DoesNotAffectOtherVMs(t *testing.T) {
|
||||
db := kv.InitDB(kv.Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
cfg1 := newCfg()
|
||||
cfg2 := newCfg()
|
||||
cfg2.Name = "vm2"
|
||||
LoadNcCloudInDB(cfg1, db)
|
||||
LoadNcCloudInDB(cfg2, db)
|
||||
|
||||
UnLoadNoCloudInDB("vm1", db)
|
||||
|
||||
_, err := kv.GetFromDB(db, "metadata/vm2/vpc")
|
||||
if err != nil {
|
||||
t.Errorf("vm2 ne devrait pas être supprimée : %v", err)
|
||||
}
|
||||
}
|
||||
46
internal/metadata/render.go
Normal file
46
internal/metadata/render.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package metadata
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"text/template"
|
||||
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
//go:embed templates/*.tmpl
|
||||
var templateFS embed.FS
|
||||
|
||||
func RenderConfig(path string, cfg NoCloudConfig) (string, error) {
|
||||
tpl, err := template.ParseFS(templateFS, path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := tpl.Execute(&buf, cfg); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func LoadNcCloudInDB(config NoCloudConfig, db *badger.DB) {
|
||||
meta_data, _ := RenderConfig("templates/meta-data.tmpl", config)
|
||||
user_data, _ := RenderConfig("templates/user-data.tmpl", config)
|
||||
network_config, _ := RenderConfig("templates/network-config.tmpl", config)
|
||||
vendor_data, _ := RenderConfig("templates/vendor-data.tmpl", config)
|
||||
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/meta-data", meta_data)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/user-data", user_data)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/network-config", network_config)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/vendor-data", vendor_data)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/vpc", config.VpcName)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/bind_ip", config.BindIP)
|
||||
kv.AddInDB(db, "metadata/"+config.Name+"/bind_port", config.BindPort)
|
||||
}
|
||||
|
||||
func UnLoadNoCloudInDB(vm_name string, db *badger.DB) {
|
||||
kv.DeleteInDB(db, "metadata/"+vm_name)
|
||||
}
|
||||
|
|
@ -1,24 +1,20 @@
|
|||
package metadata
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
configuration "git.g3e.fr/syonad/two/internal/config/agent"
|
||||
"git.g3e.fr/syonad/two/internal/netns"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
)
|
||||
|
||||
var data NoCloudData
|
||||
|
||||
var (
|
||||
iface = flag.String("interface", "0.0.0.0", "Interface IP à écouter")
|
||||
port = flag.Int("port", 8080, "Port à utiliser")
|
||||
file = flag.String("file", "", "Fichier JSON contenant les données NoCloud")
|
||||
)
|
||||
|
||||
func getIP(r *http.Request) string {
|
||||
ip, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
|
|
@ -27,6 +23,51 @@ func getIP(r *http.Request) string {
|
|||
return ip
|
||||
}
|
||||
|
||||
func getFromDB(config ServerConfig) NoCloudData {
|
||||
var netns_name string
|
||||
var port int
|
||||
var iface string
|
||||
|
||||
conf_db, _ := configuration.LoadConfig(config.ConfFile)
|
||||
|
||||
db := kv.InitDB(kv.Config{Path: conf_db.Database.Path}, true)
|
||||
defer db.Close()
|
||||
|
||||
metadata, _ := kv.GetFromDB(db, "metadata/"+config.VmName+"/meta-data")
|
||||
userdata, _ := kv.GetFromDB(db, "metadata/"+config.VmName+"/user-data")
|
||||
networkconfig, _ := kv.GetFromDB(db, "metadata/"+config.VmName+"/network-config")
|
||||
vendordata, _ := kv.GetFromDB(db, "metadata/"+config.VmName+"/vendor-data")
|
||||
|
||||
if config.Netns == "" {
|
||||
netns_name, _ = kv.GetFromDB(db, "metadata/"+config.VmName+"/vpc")
|
||||
} else {
|
||||
netns_name = config.Netns
|
||||
}
|
||||
|
||||
if config.Iface == "" {
|
||||
iface, _ = kv.GetFromDB(db, "metadata/"+config.VmName+"/bind_ip")
|
||||
} else {
|
||||
iface = config.Iface
|
||||
}
|
||||
|
||||
if config.Port == 0 {
|
||||
sport, _ := kv.GetFromDB(db, "metadata/"+config.VmName+"/bind_port")
|
||||
port, _ = strconv.Atoi(sport)
|
||||
} else {
|
||||
port = config.Port
|
||||
}
|
||||
|
||||
return NoCloudData{
|
||||
MetaData: metadata,
|
||||
UserData: userdata,
|
||||
NetworkConfig: networkconfig,
|
||||
VendorData: vendordata,
|
||||
NetNs: netns_name,
|
||||
Iface: iface,
|
||||
Port: port,
|
||||
}
|
||||
}
|
||||
|
||||
func rootHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ip := getIP(r)
|
||||
path := r.URL.Path
|
||||
|
|
@ -51,25 +92,18 @@ func rootHandler(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
func StartServer() {
|
||||
flag.Parse()
|
||||
func StartServer(config ServerConfig) {
|
||||
data = getFromDB(config)
|
||||
|
||||
if *file == "" {
|
||||
log.Fatal("Vous devez spécifier un fichier via --file")
|
||||
if data.NetNs != "" {
|
||||
if err := netns.Enter(data.NetNs); err != nil {
|
||||
log.Fatalf("Impossible d'entrer dans le netns: %v", err)
|
||||
}
|
||||
|
||||
raw, err := ioutil.ReadFile(*file)
|
||||
if err != nil {
|
||||
log.Fatalf("Erreur de lecture du fichier: %v", err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
log.Fatalf("Erreur de parsing JSON: %v", err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", rootHandler)
|
||||
|
||||
address := fmt.Sprintf("%s:%d", *iface, *port)
|
||||
address := fmt.Sprintf("%s:%d", data.Iface, data.Port)
|
||||
log.Printf("Serveur NoCloud démarré sur http://%s/", address)
|
||||
log.Fatal(http.ListenAndServe(address, nil))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,29 @@
|
|||
package metadata
|
||||
|
||||
type NoCloudData struct {
|
||||
MetaData string `json:"meta-data"`
|
||||
UserData string `json:"user-data"`
|
||||
NetworkConfig string `json:"network-config"`
|
||||
VendorData string `json:"vendor-data"`
|
||||
MetaData string
|
||||
UserData string
|
||||
NetworkConfig string
|
||||
VendorData string
|
||||
NetNs string
|
||||
Iface string
|
||||
Port int
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
Netns string
|
||||
File string
|
||||
Iface string
|
||||
Port int
|
||||
ConfFile string
|
||||
VmName string
|
||||
}
|
||||
|
||||
type NoCloudConfig struct {
|
||||
VpcName string
|
||||
BindIP string
|
||||
BindPort string
|
||||
Name string
|
||||
Password string
|
||||
SSHKEY string
|
||||
}
|
||||
|
|
|
|||
2
internal/metadata/templates/meta-data.tmpl
Normal file
2
internal/metadata/templates/meta-data.tmpl
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
instance-id: {{ .Name }}
|
||||
local-hostname: {{ .Name }}
|
||||
4
internal/metadata/templates/network-config.tmpl
Normal file
4
internal/metadata/templates/network-config.tmpl
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
version: 2
|
||||
ethernets:
|
||||
eth0:
|
||||
dhcp4: true
|
||||
3
internal/metadata/templates/user-data.tmpl
Normal file
3
internal/metadata/templates/user-data.tmpl
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/sh
|
||||
|
||||
passwd -d root
|
||||
13
internal/metadata/templates/vendor-data.tmpl
Normal file
13
internal/metadata/templates/vendor-data.tmpl
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
#cloud-config
|
||||
users:
|
||||
- name: syonad
|
||||
lock_passwd: false
|
||||
gecos: alpine Cloud User
|
||||
groups: [adm, wheel]
|
||||
doas:
|
||||
- permit nopass syonad
|
||||
sudo: ["ALL=(ALL) NOPASSWD:ALL"]
|
||||
shell: /bin/ash
|
||||
passwd: "{{ .Password }}"
|
||||
ssh_authorized_keys:
|
||||
- "{{ .SSHKEY }}"
|
||||
21
internal/netif/addr.go
Normal file
21
internal/netif/addr.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func AddrAdd(iface string, ip net.IP) error {
|
||||
link, err := netlink.LinkByName(iface)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
addr := &netlink.Addr{
|
||||
IPNet: &net.IPNet{
|
||||
IP: ip,
|
||||
Mask: net.CIDRMask(32, 32),
|
||||
},
|
||||
}
|
||||
return netlink.AddrAdd(link, addr)
|
||||
}
|
||||
38
internal/netif/bridge.go
Normal file
38
internal/netif/bridge.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func CreateBridge(name string, mtu int) error {
|
||||
br := &netlink.Bridge{
|
||||
LinkAttrs: netlink.LinkAttrs{
|
||||
Name: name,
|
||||
MTU: mtu,
|
||||
},
|
||||
}
|
||||
|
||||
if err := netlink.LinkAdd(br); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := netlink.LinkSetUp(br); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func BridgeSetMaster(iface, bridge string) error {
|
||||
link, err := netlink.LinkByName(iface)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
br, err := netlink.LinkByName(bridge)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return netlink.LinkSetMaster(link, br)
|
||||
}
|
||||
13
internal/netif/delete.go
Normal file
13
internal/netif/delete.go
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func DeleteLink(name string) error {
|
||||
link, err := netlink.LinkByName(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return netlink.LinkDel(link)
|
||||
}
|
||||
21
internal/netif/route_linux.go
Normal file
21
internal/netif/route_linux.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
//go:build linux
|
||||
|
||||
package netif
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func RouteAdd(iface string, subnet *net.IPNet) error {
|
||||
link, err := netlink.LinkByName(iface)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return netlink.RouteAdd(&netlink.Route{
|
||||
LinkIndex: link.Attrs().Index,
|
||||
Dst: subnet,
|
||||
Scope: netlink.SCOPE_LINK,
|
||||
})
|
||||
}
|
||||
9
internal/netif/route_other.go
Normal file
9
internal/netif/route_other.go
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
//go:build !linux
|
||||
|
||||
package netif
|
||||
|
||||
import "net"
|
||||
|
||||
func RouteAdd(_ string, _ *net.IPNet) error {
|
||||
return nil
|
||||
}
|
||||
21
internal/netif/upDown.go
Normal file
21
internal/netif/upDown.go
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func LinkSetUp(name string) error {
|
||||
link, err := netlink.LinkByName(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return netlink.LinkSetUp(link)
|
||||
}
|
||||
|
||||
func LinkSetDown(name string) error {
|
||||
link, err := netlink.LinkByName(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return netlink.LinkSetDown(link)
|
||||
}
|
||||
48
internal/netif/veth.go
Normal file
48
internal/netif/veth.go
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
"github.com/vishvananda/netns"
|
||||
)
|
||||
|
||||
func CreateVethToNetns(rootIf, nsIf, netnsPath string, mtu int) error {
|
||||
// Obligatoire : netns lié au thread
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
// Ouvrir le netns cible
|
||||
ns, err := netns.GetFromPath(netnsPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open netns: %w, %s", err, netnsPath)
|
||||
}
|
||||
defer ns.Close()
|
||||
|
||||
// Créer le veth dans le netns courant
|
||||
veth := &netlink.Veth{
|
||||
LinkAttrs: netlink.LinkAttrs{
|
||||
Name: rootIf,
|
||||
MTU: mtu,
|
||||
},
|
||||
PeerName: nsIf,
|
||||
}
|
||||
|
||||
if err := netlink.LinkAdd(veth); err != nil {
|
||||
return fmt.Errorf("link add: %w", err)
|
||||
}
|
||||
|
||||
// Récupérer l'interface peer
|
||||
peer, err := netlink.LinkByName(nsIf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("peer not found: %w", err)
|
||||
}
|
||||
|
||||
// Déplacer le peer dans le netns cible
|
||||
if err := netlink.LinkSetNsFd(peer, int(ns)); err != nil {
|
||||
return fmt.Errorf("set ns: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
20
internal/netif/vxlan.go
Normal file
20
internal/netif/vxlan.go
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
package netif
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
func CreateVxlan(name string, vxlanID int, localIP net.IP) error {
|
||||
vxlan := &netlink.Vxlan{
|
||||
LinkAttrs: netlink.LinkAttrs{
|
||||
Name: name,
|
||||
},
|
||||
VxlanId: vxlanID,
|
||||
Port: 4789,
|
||||
SrcAddr: localIP,
|
||||
Learning: false,
|
||||
}
|
||||
return netlink.LinkAdd(vxlan)
|
||||
}
|
||||
5
internal/netns/call.go
Normal file
5
internal/netns/call.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package netns
|
||||
|
||||
func Call(name string, fn func() error) error {
|
||||
return call(name, fn)
|
||||
}
|
||||
44
internal/netns/call_linux.go
Normal file
44
internal/netns/call_linux.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
//go:build linux
|
||||
|
||||
package netns
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func call(name string, fn func() error) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
// sauvegarde du netns courant
|
||||
orig, err := os.Open("/proc/self/ns/net")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer orig.Close()
|
||||
|
||||
// entrer dans le netns cible
|
||||
f, err := os.Open(fmt.Sprintf("/var/run/netns/%s", name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := unix.Setns(int(f.Fd()), unix.CLONE_NEWNET); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// exécuter la fonction dans le netns
|
||||
err = fn()
|
||||
|
||||
// toujours revenir au netns d'origine
|
||||
if restoreErr := unix.Setns(int(orig.Fd()), unix.CLONE_NEWNET); restoreErr != nil {
|
||||
return restoreErr
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
7
internal/netns/call_other.go
Normal file
7
internal/netns/call_other.go
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//go:build !linux
|
||||
|
||||
package netns
|
||||
|
||||
func call(_ string, fn func() error) error {
|
||||
return fn()
|
||||
}
|
||||
5
internal/netns/create.go
Normal file
5
internal/netns/create.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package netns
|
||||
|
||||
func Create(name string) error {
|
||||
return create(name)
|
||||
}
|
||||
69
internal/netns/create_linux.go
Normal file
69
internal/netns/create_linux.go
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
//go:build linux
|
||||
|
||||
package netns
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func create(name string) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
base := "/var/run/netns"
|
||||
path := base + "/" + name
|
||||
|
||||
if err := os.MkdirAll(base, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// si le fichier existe déjà, le démonter d'abord
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
unix.Unmount(path, unix.MNT_DETACH)
|
||||
os.Remove(path)
|
||||
}
|
||||
|
||||
// fichier cible
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f.Close()
|
||||
|
||||
// sauvegarde du netns courant
|
||||
orig, err := os.Open("/proc/self/ns/net")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer orig.Close()
|
||||
|
||||
// nouveau netns
|
||||
if err := unix.Unshare(unix.CLONE_NEWNET); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// bind mount du netns du thread courant vers /var/run/netns/<name>
|
||||
// /proc/self/ns/net pointe vers le ns du processus (thread principal),
|
||||
// pas du thread courant — il faut utiliser le tid explicitement
|
||||
threadNsPath := fmt.Sprintf("/proc/self/task/%d/ns/net", unix.Gettid())
|
||||
if err := unix.Mount(
|
||||
threadNsPath,
|
||||
path,
|
||||
"",
|
||||
unix.MS_BIND,
|
||||
"",
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// revenir au netns original
|
||||
if err := unix.Setns(int(orig.Fd()), unix.CLONE_NEWNET); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
5
internal/netns/create_other.go
Normal file
5
internal/netns/create_other.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//go:build !linux
|
||||
|
||||
package netns
|
||||
|
||||
func create(string) error { return nil }
|
||||
5
internal/netns/delete.go
Normal file
5
internal/netns/delete.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package netns
|
||||
|
||||
func Delete(name string) error {
|
||||
return delete(name)
|
||||
}
|
||||
18
internal/netns/delete_linux.go
Normal file
18
internal/netns/delete_linux.go
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
//go:build linux
|
||||
|
||||
package netns
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func delete(name string) error {
|
||||
path := "/var/run/netns/" + name
|
||||
|
||||
if err := unix.Unmount(path, unix.MNT_DETACH); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Remove(path)
|
||||
}
|
||||
5
internal/netns/delete_other.go
Normal file
5
internal/netns/delete_other.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
//go:build !linux
|
||||
|
||||
package netns
|
||||
|
||||
func delete(string) error { return nil }
|
||||
5
internal/netns/enter.go
Normal file
5
internal/netns/enter.go
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package netns
|
||||
|
||||
func Enter(name string) error {
|
||||
return enter(name)
|
||||
}
|
||||
26
internal/netns/enter_linux.go
Normal file
26
internal/netns/enter_linux.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
//go:build linux
|
||||
|
||||
package netns
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func enter(name string) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
path := fmt.Sprintf("/var/run/netns/%s", name)
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return unix.Setns(int(f.Fd()), unix.CLONE_NEWNET)
|
||||
}
|
||||
8
internal/netns/enter_other.go
Normal file
8
internal/netns/enter_other.go
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//go:build !linux
|
||||
|
||||
package netns
|
||||
|
||||
func enter(name string) error {
|
||||
// Ignoré hors Linux
|
||||
return nil
|
||||
}
|
||||
14
internal/netns/exist.go
Normal file
14
internal/netns/exist.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
package netns
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
func exist(name string) bool {
|
||||
_, err := os.Stat("/var/run/netns/" + name)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func Exist(name string) bool {
|
||||
return exist(name)
|
||||
}
|
||||
186
internal/subnet/create.go
Normal file
186
internal/subnet/create.go
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
package subnet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.g3e.fr/syonad/two/internal/dhcp"
|
||||
"git.g3e.fr/syonad/two/internal/netif"
|
||||
"git.g3e.fr/syonad/two/internal/netns"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
"git.g3e.fr/syonad/two/pkg/systemd"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func CreateSubnet(db *badger.DB, subnetName string) error {
|
||||
state, err := kv.GetFromDB(db, "subnet/"+subnetName+"/state")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state != "creating" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// lecture des paramètres depuis la DB
|
||||
vpcName, err := kv.GetFromDB(db, "subnet/"+subnetName+"/vpc")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get vpc: %w", err)
|
||||
}
|
||||
|
||||
vxlanIDStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/vxlan_id")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get vxlan_id: %w", err)
|
||||
}
|
||||
vxlanID, err := strconv.Atoi(vxlanIDStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse vxlan_id: %w", err)
|
||||
}
|
||||
|
||||
localIPStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/local_ip")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get local_ip: %w", err)
|
||||
}
|
||||
localIP := net.ParseIP(localIPStr)
|
||||
if localIP == nil {
|
||||
return fmt.Errorf("invalid local_ip: %s", localIPStr)
|
||||
}
|
||||
|
||||
gatewayIPStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/gateway_ip")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get gateway_ip: %w", err)
|
||||
}
|
||||
gatewayIP := net.ParseIP(gatewayIPStr)
|
||||
if gatewayIP == nil {
|
||||
return fmt.Errorf("invalid gateway_ip: %s", gatewayIPStr)
|
||||
}
|
||||
|
||||
cidr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/cidr")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get cidr: %w", err)
|
||||
}
|
||||
_, subnet, err := net.ParseCIDR(cidr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse cidr: %w", err)
|
||||
}
|
||||
|
||||
// subnet_id = partie après le premier '-' (ex: "sn-00001" -> "00001")
|
||||
subnetID := strings.SplitN(subnetName, "-", 2)[1]
|
||||
bridge := "br-" + subnetID
|
||||
vxlanIface := fmt.Sprintf("vxlan-%d", vxlanID)
|
||||
|
||||
// veth pair
|
||||
if err := netif.CreateVethToNetns("v-"+subnetID+"-e", "v-"+subnetID+"-i", "/var/run/netns/"+vpcName, 1500); err != nil {
|
||||
return fmt.Errorf("create veth: %w", err)
|
||||
}
|
||||
|
||||
// bridge dans le root netns
|
||||
if err := netif.CreateBridge(bridge, 1500); err != nil {
|
||||
return fmt.Errorf("create bridge: %w", err)
|
||||
}
|
||||
|
||||
// bridge dans le netns VPC
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
return netif.CreateBridge(bridge, 1500)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("create bridge in netns: %w", err)
|
||||
}
|
||||
|
||||
// vxlan
|
||||
if err := netif.CreateVxlan(vxlanIface, vxlanID, localIP); err != nil {
|
||||
return fmt.Errorf("create vxlan: %w", err)
|
||||
}
|
||||
|
||||
// ajout des interfaces dans les bridges
|
||||
if err := netif.BridgeSetMaster("v-"+subnetID+"-e", bridge); err != nil {
|
||||
return fmt.Errorf("add veth-e to bridge: %w", err)
|
||||
}
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
return netif.BridgeSetMaster("v-"+subnetID+"-i", bridge)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("add veth-i to bridge in netns: %w", err)
|
||||
}
|
||||
if err := netif.BridgeSetMaster(vxlanIface, bridge); err != nil {
|
||||
return fmt.Errorf("add vxlan to bridge: %w", err)
|
||||
}
|
||||
|
||||
// montée des interfaces dans le root netns
|
||||
for _, iface := range []string{"v-" + subnetID + "-e", vxlanIface, bridge} {
|
||||
if err := netif.LinkSetUp(iface); err != nil {
|
||||
return fmt.Errorf("set up %s: %w", iface, err)
|
||||
}
|
||||
}
|
||||
|
||||
// montée des interfaces dans le netns VPC
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
for _, iface := range []string{"v-" + subnetID + "-i", bridge} {
|
||||
if err := netif.LinkSetUp(iface); err != nil {
|
||||
return fmt.Errorf("set up %s: %w", iface, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return fmt.Errorf("set up interfaces in netns: %w", err)
|
||||
}
|
||||
|
||||
// IP gateway (/32) sur le bridge interne
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
return netif.AddrAdd(bridge, gatewayIP)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("add addr to bridge in netns: %w", err)
|
||||
}
|
||||
|
||||
// route subnet (scope link) dans le netns VPC
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
return netif.RouteAdd(bridge, subnet)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("add route in netns: %w", err)
|
||||
}
|
||||
|
||||
// ebtables : drop ARP Request vers la gateway sur ce bridge
|
||||
if err := exec.Command("ebtables", "-A", "FORWARD",
|
||||
"--out-interface", bridge,
|
||||
"-p", "arp",
|
||||
"--arp-op", "Request",
|
||||
"--arp-ip-dst", gatewayIP.String(),
|
||||
"-j", "DROP").Run(); err != nil {
|
||||
return fmt.Errorf("ebtables arp rule: %w", err)
|
||||
}
|
||||
|
||||
// ebtables : drop trafic DHCP sur ce bridge
|
||||
if err := exec.Command("ebtables", "-A", "FORWARD",
|
||||
"--out-interface", bridge,
|
||||
"-p", "IPv4",
|
||||
"--ip-protocol", "udp",
|
||||
"--ip-source-port", "67:68",
|
||||
"--ip-destination-port", "67:68",
|
||||
"-j", "DROP").Run(); err != nil {
|
||||
return fmt.Errorf("ebtables dhcp rule: %w", err)
|
||||
}
|
||||
|
||||
// génération de la config dnsmasq et démarrage du service
|
||||
conf := dhcp.Config{
|
||||
Network: subnet,
|
||||
Gateway: gatewayIP,
|
||||
Name: vpcName + "_" + bridge,
|
||||
ConfDir: "/etc/dnsmasq.d",
|
||||
}
|
||||
if _, err := dhcp.GenerateConfig(conf); err != nil {
|
||||
return fmt.Errorf("generate dhcp config: %w", err)
|
||||
}
|
||||
|
||||
svc, err := systemd.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect to systemd: %w", err)
|
||||
}
|
||||
defer svc.Close()
|
||||
|
||||
if err := svc.Start("dnsmasq@" + conf.Name + ".service"); err != nil {
|
||||
return fmt.Errorf("start dnsmasq: %w", err)
|
||||
}
|
||||
|
||||
return kv.AddInDB(db, "subnet/"+subnetName+"/state", "created")
|
||||
}
|
||||
95
internal/subnet/delete.go
Normal file
95
internal/subnet/delete.go
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
package subnet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.g3e.fr/syonad/two/internal/netif"
|
||||
"git.g3e.fr/syonad/two/internal/netns"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
"git.g3e.fr/syonad/two/pkg/systemd"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func DeleteSubnet(db *badger.DB, subnetName string) error {
|
||||
state, err := kv.GetFromDB(db, "subnet/"+subnetName+"/state")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state != "deleting" {
|
||||
return nil
|
||||
}
|
||||
|
||||
vpcName, err := kv.GetFromDB(db, "subnet/"+subnetName+"/vpc")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get vpc: %w", err)
|
||||
}
|
||||
|
||||
vxlanIDStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/vxlan_id")
|
||||
if err != nil {
|
||||
return fmt.Errorf("get vxlan_id: %w", err)
|
||||
}
|
||||
|
||||
subnetID := strings.SplitN(subnetName, "-", 2)[1]
|
||||
bridge := "br-" + subnetID
|
||||
vxlanIface := "vxlan-" + vxlanIDStr
|
||||
|
||||
// arrêt du service dnsmasq
|
||||
svc, err := systemd.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect to systemd: %w", err)
|
||||
}
|
||||
defer svc.Close()
|
||||
|
||||
svcName := "dnsmasq@" + vpcName + "_" + bridge + ".service"
|
||||
if err := svc.Stop(svcName); err != nil {
|
||||
return fmt.Errorf("stop dnsmasq: %w", err)
|
||||
}
|
||||
|
||||
// suppression de la config dnsmasq
|
||||
if err := os.Remove("/etc/dnsmasq.d/" + vpcName + "_" + bridge + ".conf"); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove dnsmasq config: %w", err)
|
||||
}
|
||||
|
||||
// suppression des règles ebtables
|
||||
exec.Command("ebtables", "-D", "FORWARD",
|
||||
"--out-interface", bridge,
|
||||
"-p", "arp",
|
||||
"--arp-op", "Request",
|
||||
"-j", "DROP").Run()
|
||||
|
||||
exec.Command("ebtables", "-D", "FORWARD",
|
||||
"--out-interface", bridge,
|
||||
"-p", "IPv4",
|
||||
"--ip-protocol", "udp",
|
||||
"--ip-source-port", "67:68",
|
||||
"--ip-destination-port", "67:68",
|
||||
"-j", "DROP").Run()
|
||||
|
||||
// suppression du bridge dans le netns VPC
|
||||
if err := netns.Call(vpcName, func() error {
|
||||
return netif.DeleteLink(bridge)
|
||||
}); err != nil {
|
||||
return fmt.Errorf("delete bridge in netns: %w", err)
|
||||
}
|
||||
|
||||
// suppression du vxlan
|
||||
if err := netif.DeleteLink(vxlanIface); err != nil {
|
||||
return fmt.Errorf("delete vxlan: %w", err)
|
||||
}
|
||||
|
||||
// suppression du veth pair (supprime les deux côtés)
|
||||
if err := netif.DeleteLink("v-" + subnetID + "-e"); err != nil {
|
||||
return fmt.Errorf("delete veth: %w", err)
|
||||
}
|
||||
|
||||
// suppression du bridge dans le root netns
|
||||
if err := netif.DeleteLink(bridge); err != nil {
|
||||
return fmt.Errorf("delete bridge: %w", err)
|
||||
}
|
||||
|
||||
return kv.AddInDB(db, "subnet/"+subnetName+"/state", "deleted")
|
||||
}
|
||||
61
internal/vpc/create.go
Normal file
61
internal/vpc/create.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
package vpc
|
||||
|
||||
import (
|
||||
"git.g3e.fr/syonad/two/internal/netif"
|
||||
"git.g3e.fr/syonad/two/internal/netns"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func CreateVPC(db *badger.DB, name string) error {
|
||||
// missing
|
||||
// search data in db
|
||||
// change state in db
|
||||
|
||||
// create netns
|
||||
if state, err := kv.GetFromDB(db, "vpc/"+name+"/state"); err != nil {
|
||||
return err
|
||||
} else if state == "creating" {
|
||||
if err := netns.Create(name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create veth public for this netns
|
||||
if err := netif.CreateVethToNetns("vp-"+name+"-e", "vp-public-i", "/var/run/netns/"+name, 9000); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create public bridge in netns
|
||||
if err := netns.Call(name, func() error {
|
||||
return netif.CreateBridge("br-public", 1500)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set veth to ext public bridge
|
||||
if err := netif.BridgeSetMaster("vp-"+name+"-e", "br-public"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set veth to int public bridge
|
||||
if err := netns.Call(name, func() error {
|
||||
return netif.BridgeSetMaster("vp-public-i", "br-public")
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set set ext veth up
|
||||
if err := netif.LinkSetUp("vp-" + name + "-e"); err != nil {
|
||||
return err
|
||||
}
|
||||
// set set int veth up
|
||||
if err := netns.Call(name, func() error {
|
||||
return netif.LinkSetUp("vp-public-i")
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
kv.AddInDB(db, "vpc/"+name+"/state", "created")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
26
internal/vpc/delete.go
Normal file
26
internal/vpc/delete.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package vpc
|
||||
|
||||
import (
|
||||
"git.g3e.fr/syonad/two/internal/netif"
|
||||
"git.g3e.fr/syonad/two/internal/netns"
|
||||
"git.g3e.fr/syonad/two/pkg/db/kv"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func DeleteVPC(db *badger.DB, name string) error {
|
||||
if state, err := kv.GetFromDB(db, "vpc/"+name+"/state"); err != nil {
|
||||
return err
|
||||
} else if state == "deleting" {
|
||||
if err := netif.DeleteLink("vp-" + name + "-e"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := netns.Delete(name); err != nil {
|
||||
return err
|
||||
}
|
||||
kv.AddInDB(db, "vpc/"+name+"/state", "deleted")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
11
pkg/db/kv/addInDB.go
Normal file
11
pkg/db/kv/addInDB.go
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
package kv
|
||||
|
||||
import (
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func AddInDB(db *badger.DB, key string, value string) error {
|
||||
return db.Update(func(txn *badger.Txn) error {
|
||||
return txn.Set([]byte(key), []byte(value))
|
||||
})
|
||||
}
|
||||
42
pkg/db/kv/deleteInDB.go
Normal file
42
pkg/db/kv/deleteInDB.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package kv
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func deleteKey(db *badger.DB, key string) error {
|
||||
return db.Update(func(txn *badger.Txn) error {
|
||||
return txn.Delete([]byte(key))
|
||||
})
|
||||
}
|
||||
|
||||
func DeleteInDB(db *badger.DB, key string) error {
|
||||
|
||||
prefix := []byte(key + "/")
|
||||
|
||||
err := db.View(func(txn *badger.Txn) error {
|
||||
opts := badger.DefaultIteratorOptions
|
||||
opts.PrefetchValues = false
|
||||
|
||||
it := txn.NewIterator(opts)
|
||||
defer it.Close()
|
||||
|
||||
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
|
||||
item := it.Item()
|
||||
key := item.Key()
|
||||
|
||||
k := append([]byte{}, key...)
|
||||
if err := deleteKey(db, string(k)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return deleteKey(db, key)
|
||||
}
|
||||
22
pkg/db/kv/getInDB.go
Normal file
22
pkg/db/kv/getInDB.go
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package kv
|
||||
|
||||
import (
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func GetFromDB(db *badger.DB, key string) (string, error) {
|
||||
var result string
|
||||
|
||||
err := db.View(func(txn *badger.Txn) error {
|
||||
item, err := txn.Get([]byte(key))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return item.Value(func(val []byte) error {
|
||||
result = string(val)
|
||||
return nil
|
||||
})
|
||||
})
|
||||
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -4,8 +4,10 @@ import (
|
|||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
func InitDB(conf Config) *badger.DB {
|
||||
opts := badger.DefaultOptions(conf.Path)
|
||||
func InitDB(conf Config, readonly bool) *badger.DB {
|
||||
opts := badger.DefaultOptions(conf.Path).
|
||||
WithReadOnly(readonly).
|
||||
WithBypassLockGuard(readonly)
|
||||
opts.Logger = nil
|
||||
opts.ValueLogFileSize = 10 << 20 // 10 Mo par fichier vlog
|
||||
opts.NumMemtables = 1
|
||||
|
|
|
|||
153
pkg/db/kv/kv_test.go
Normal file
153
pkg/db/kv/kv_test.go
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
package kv
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/dgraph-io/badger/v4"
|
||||
)
|
||||
|
||||
// newTestDB ouvre une base BadgerDB dans un répertoire temporaire.
|
||||
// La base est fermée automatiquement en fin de test.
|
||||
func newTestDB(t *testing.T) *badger.DB {
|
||||
t.Helper()
|
||||
db := InitDB(Config{Path: t.TempDir()}, false)
|
||||
t.Cleanup(func() { db.Close() })
|
||||
return db
|
||||
}
|
||||
|
||||
// --- InitDB ---
|
||||
|
||||
func TestInitDB_ValidPath(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
if db == nil {
|
||||
t.Fatal("InitDB devrait retourner une DB non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitDB_InvalidPath_Panics(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatal("InitDB avec un chemin invalide devrait paniquer")
|
||||
}
|
||||
}()
|
||||
InitDB(Config{Path: "/chemin/inexistant/absolu"}, false)
|
||||
}
|
||||
|
||||
// --- AddInDB ---
|
||||
|
||||
func TestAddInDB_NewKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
if err := AddInDB(db, "vpc/test", "valeur"); err != nil {
|
||||
t.Fatalf("AddInDB a échoué : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddInDB_OverwriteExistingKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
AddInDB(db, "vpc/test", "premiere")
|
||||
if err := AddInDB(db, "vpc/test", "deuxieme"); err != nil {
|
||||
t.Fatalf("AddInDB (écrasement) a échoué : %v", err)
|
||||
}
|
||||
|
||||
val, _ := GetFromDB(db, "vpc/test")
|
||||
if val != "deuxieme" {
|
||||
t.Errorf("valeur attendue %q, obtenu %q", "deuxieme", val)
|
||||
}
|
||||
}
|
||||
|
||||
// --- GetFromDB ---
|
||||
|
||||
func TestGetFromDB_ExistingKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
AddInDB(db, "vpc/foo", "bar")
|
||||
|
||||
val, err := GetFromDB(db, "vpc/foo")
|
||||
if err != nil {
|
||||
t.Fatalf("GetFromDB a échoué : %v", err)
|
||||
}
|
||||
if val != "bar" {
|
||||
t.Errorf("valeur attendue %q, obtenu %q", "bar", val)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFromDB_MissingKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
|
||||
_, err := GetFromDB(db, "inexistant")
|
||||
if !errors.Is(err, badger.ErrKeyNotFound) {
|
||||
t.Errorf("erreur attendue ErrKeyNotFound, obtenu : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetFromDB_EmptyValue(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
AddInDB(db, "vpc/vide", "")
|
||||
|
||||
val, err := GetFromDB(db, "vpc/vide")
|
||||
if err != nil {
|
||||
t.Fatalf("GetFromDB a échoué : %v", err)
|
||||
}
|
||||
if val != "" {
|
||||
t.Errorf("valeur attendue vide, obtenu %q", val)
|
||||
}
|
||||
}
|
||||
|
||||
// --- DeleteInDB ---
|
||||
|
||||
func TestDeleteInDB_SimpleKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
AddInDB(db, "vpc/a", "v")
|
||||
|
||||
if err := DeleteInDB(db, "vpc/a"); err != nil {
|
||||
t.Fatalf("DeleteInDB a échoué : %v", err)
|
||||
}
|
||||
|
||||
_, err := GetFromDB(db, "vpc/a")
|
||||
if !errors.Is(err, badger.ErrKeyNotFound) {
|
||||
t.Errorf("la clé devrait être supprimée, obtenu : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteInDB_WithSubkeys(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
// Clé parente + sous-clés (préfixe "vpc/net1/")
|
||||
AddInDB(db, "vpc/net1", "parent")
|
||||
AddInDB(db, "vpc/net1/ip", "10.0.0.1")
|
||||
AddInDB(db, "vpc/net1/gw", "10.0.0.254")
|
||||
|
||||
if err := DeleteInDB(db, "vpc/net1"); err != nil {
|
||||
t.Fatalf("DeleteInDB a échoué : %v", err)
|
||||
}
|
||||
|
||||
for _, key := range []string{"vpc/net1", "vpc/net1/ip", "vpc/net1/gw"} {
|
||||
_, err := GetFromDB(db, key)
|
||||
if !errors.Is(err, badger.ErrKeyNotFound) {
|
||||
t.Errorf("clé %q devrait être supprimée, obtenu : %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteInDB_DoesNotDeleteSiblings(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
AddInDB(db, "vpc/net1", "a")
|
||||
AddInDB(db, "vpc/net2", "b") // ne doit pas être supprimée
|
||||
|
||||
DeleteInDB(db, "vpc/net1")
|
||||
|
||||
val, err := GetFromDB(db, "vpc/net2")
|
||||
if err != nil {
|
||||
t.Fatalf("vpc/net2 ne devrait pas être supprimée : %v", err)
|
||||
}
|
||||
if val != "b" {
|
||||
t.Errorf("valeur attendue %q, obtenu %q", "b", val)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteInDB_MissingKey(t *testing.T) {
|
||||
db := newTestDB(t)
|
||||
// Supprimer une clé inexistante ne doit pas crasher
|
||||
if err := DeleteInDB(db, "inexistant"); err != nil {
|
||||
t.Logf("DeleteInDB clé inexistante retourne : %v (non bloquant)", err)
|
||||
}
|
||||
}
|
||||
114
pkg/systemd/main.go
Normal file
114
pkg/systemd/main.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package systemd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-systemd/v22/dbus"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 5 * time.Second
|
||||
jobTimeout = 30 * time.Second
|
||||
jobMode = "replace"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
conn *dbus.Conn
|
||||
}
|
||||
|
||||
type ServiceStatus struct {
|
||||
Name string
|
||||
LoadState string
|
||||
ActiveState string
|
||||
SubState string
|
||||
MainPID uint32
|
||||
}
|
||||
|
||||
// New crée une connexion D-Bus systemd (scope système)
|
||||
func New() (*Manager, error) {
|
||||
conn, err := dbus.NewSystemConnectionContext(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Manager{conn: conn}, nil
|
||||
}
|
||||
|
||||
// Close ferme la connexion D-Bus
|
||||
func (m *Manager) Close() {
|
||||
if m.conn != nil {
|
||||
m.conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// Start démarre un service systemd
|
||||
func (m *Manager) Start(service string) error {
|
||||
return m.job("StartUnit", service)
|
||||
}
|
||||
|
||||
// Stop arrête un service systemd
|
||||
func (m *Manager) Stop(service string) error {
|
||||
return m.job("StopUnit", service)
|
||||
}
|
||||
|
||||
func (m *Manager) job(method, service string) error {
|
||||
callCtx, callCancel := context.WithTimeout(context.Background(), defaultTimeout)
|
||||
defer callCancel()
|
||||
|
||||
ch := make(chan string, 1)
|
||||
|
||||
var err error
|
||||
switch method {
|
||||
case "StartUnit":
|
||||
_, err = m.conn.StartUnitContext(callCtx, service, jobMode, ch)
|
||||
case "StopUnit":
|
||||
_, err = m.conn.StopUnitContext(callCtx, service, jobMode, ch)
|
||||
default:
|
||||
return errors.New("unsupported job method")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
waitCtx, waitCancel := context.WithTimeout(context.Background(), jobTimeout)
|
||||
defer waitCancel()
|
||||
|
||||
select {
|
||||
case result := <-ch:
|
||||
if result != "done" {
|
||||
return fmt.Errorf("%s %s failed: %s", method, service, result)
|
||||
}
|
||||
case <-waitCtx.Done():
|
||||
return fmt.Errorf("%s %s timed out after %s", method, service, jobTimeout)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Status retourne l’état courant du service
|
||||
func (m *Manager) Status(service string) (*ServiceStatus, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
props, err := m.conn.GetUnitPropertiesContext(ctx, service)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status := &ServiceStatus{
|
||||
Name: service,
|
||||
LoadState: props["LoadState"].(string),
|
||||
ActiveState: props["ActiveState"].(string),
|
||||
SubState: props["SubState"].(string),
|
||||
}
|
||||
|
||||
if pid, ok := props["MainPID"].(uint32); ok {
|
||||
status.MainPID = pid
|
||||
}
|
||||
|
||||
return status, nil
|
||||
}
|
||||
92
scripts/deploy.sh
Normal file
92
scripts/deploy.sh
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
SED_PARAM=""
|
||||
unameOut="$(uname -s)"
|
||||
case "${unameOut}" in
|
||||
Linux*) SED_PARAM=" -i ";;
|
||||
Darwin*) SED_PARAM=" -i '' ";;
|
||||
*) exit 1
|
||||
esac
|
||||
|
||||
SCRIPT_PATH="scripts/deploy.sh"
|
||||
|
||||
exec_with_dry_run () {
|
||||
if [[ ${1} -eq ${FLAGS_TRUE} ]]; then
|
||||
echo "# ${2}"
|
||||
else
|
||||
eval "${2}" 2> /tmp/error || \
|
||||
{
|
||||
echo -e "failed with following error";
|
||||
output=$(cat /tmp/error | sed -e "s/^/ error -> /g");
|
||||
echo -e "${output}";
|
||||
return 1;
|
||||
}
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
check_latest_script () {
|
||||
REMOTE_URL="${1}"
|
||||
LOCAL_PATH="${2}"
|
||||
|
||||
REMOTE=$(curl --silent "${REMOTE_URL}" | sha256sum)
|
||||
LOCAL=$(cat ${LOCAL_PATH} | sha256sum)
|
||||
|
||||
[[ "${REMOTE}" == "${LOCAL}" ]] || return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
download_binaries () {
|
||||
DRY_RUN="${1}"
|
||||
TAG="${2}"
|
||||
GIT_SERVER="${3}"
|
||||
REPO_PATH="${4}"
|
||||
|
||||
#'.[0].assets.[].browser_download_url'
|
||||
[[ "${TAG}" == "" ]] && TAG=$(curl --silent "${GIT_SERVER}api/v1/repos/${REPO_PATH}releases/?limit=1" | jq -r '.[0].tag_name')
|
||||
echo "Deploy ${TAG} binaries"
|
||||
|
||||
BIN_PATH="/opt/two/${TAG}/bin/"
|
||||
LN_PATH="/opt/two/bin/"
|
||||
|
||||
exec_with_dry_run "${DRY_RUN}" "mkdir -p \"${BIN_PATH}\""
|
||||
exec_with_dry_run "${DRY_RUN}" "mkdir -p \"${LN_PATH}\""
|
||||
|
||||
curl --silent "${GIT_SERVER}api/v1/repos/${REPO_PATH}releases/tags/${TAG}" | jq -c '.assets[]' | while read tmp
|
||||
do
|
||||
BINARY_NAME=$(echo "${tmp}" | jq -r '.name')
|
||||
BINARY_SHORT_NAME=$(echo "${BINARY_NAME}" | cut -d_ -f 1)
|
||||
BINARY_URL=$(echo "${tmp}" | jq -r '.browser_download_url')
|
||||
exec_with_dry_run "${DRY_RUN}" "curl --silent '${BINARY_URL}' -o '${BIN_PATH}${BINARY_NAME}'"
|
||||
exec_with_dry_run "${DRY_RUN}" "chmod +x '${BIN_PATH}${BINARY_NAME}'"
|
||||
exec_with_dry_run "${DRY_RUN}" "rm -f '${LN_PATH}${BINARY_SHORT_NAME}'"
|
||||
exec_with_dry_run "${DRY_RUN}" "ln -s '${BIN_PATH}${BINARY_NAME}' '${LN_PATH}${BINARY_SHORT_NAME}'"
|
||||
done
|
||||
}
|
||||
|
||||
main () {
|
||||
[[ -f ./libs/shflags ]] && . ./libs/shflags || eval "$(curl --silent https://git.g3e.fr/H6N/tools/raw/branch/main/libs/shflags)"
|
||||
|
||||
DEFINE_boolean 'dryrun' false 'Enable dry-run mode' 'd'
|
||||
DEFINE_boolean 'up_script' true 'Upgrade script' 's'
|
||||
DEFINE_string 'git_server' 'https://git.g3e.fr/' 'Git Server' 'g'
|
||||
DEFINE_string 'repo_path' 'syonad/two/' 'Path of repository' 'r'
|
||||
DEFINE_string 'branch' 'main/' 'Branch name' 'b'
|
||||
DEFINE_string 'tag' '' 'Tag name' 't'
|
||||
|
||||
FLAGS "$@" || exit $?
|
||||
eval set -- "${FLAGS_ARGV}"
|
||||
|
||||
SCRIPT_URL="${FLAGS_git_server}${FLAGS_repo_path}raw/branch/${FLAGS_branch}${SCRIPT_PATH}"
|
||||
check_latest_script "${SCRIPT_URL}" "${0}" || (
|
||||
[[ ${FLAGS_up_script} -eq ${FLAGS_TRUE} ]] && \
|
||||
exec_with_dry_run "${FLAGS_dryrun}" "curl --silent '${SCRIPT_URL}' -o '${0}'"
|
||||
exit 1
|
||||
)
|
||||
|
||||
download_binaries "${FLAGS_dryrun}" "${FLAGS_tag}" "${FLAGS_git_server}" "${FLAGS_repo_path}"
|
||||
}
|
||||
|
||||
[[ "${BASH_SOURCE[0]}" == "${0}" ]] && (main "$@" || exit 1)
|
||||
[[ "${BASH_SOURCE[0]}" == "" ]] && (main "$@" || exit 1)
|
||||
21
scripts/run-dnsmasq-in-netns.sh
Normal file
21
scripts/run-dnsmasq-in-netns.sh
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Expects one argument: netns_bridge (e.g. vpc-00003_br-00002 or vpc1_br0)
|
||||
arg="$1"
|
||||
NETNS="${arg%%_*}"
|
||||
BRIDGE="${arg#*_}"
|
||||
|
||||
echo "start dnsmasq ${NETNS} ${BRIDGE}"
|
||||
|
||||
exec ip netns exec "${NETNS}" \
|
||||
dnsmasq \
|
||||
--no-daemon \
|
||||
--interface="${BRIDGE}" \
|
||||
--bind-interfaces \
|
||||
--pid-file="/run/dnsmasq-$arg.pid" \
|
||||
--conf-file="/etc/dnsmasq.d/$arg.conf" \
|
||||
--no-hosts \
|
||||
--no-resolv \
|
||||
--log-facility="/var/log/dnsmasq-$arg.log" \
|
||||
--no-daemon -p0
|
||||
11
systemd/dnsmasq@.service
Normal file
11
systemd/dnsmasq@.service
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
[Unit]
|
||||
Description=dnsmasq in netns %i
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/opt/two/bin/run-dnsmasq-in-netns.sh %i
|
||||
ExecStopPost=/bin/rm -f /run/dnsmasq-%i.pid
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
10
systemd/metadata@.service
Normal file
10
systemd/metadata@.service
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[Unit]
|
||||
Description=metadata in netns %i
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/opt/two/bin/metadata --vm %i
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Loading…
Add table
Add a link
Reference in a new issue