From c07eeea3abdf9b41675f50499a62fb1291a93dd9 Mon Sep 17 00:00:00 2001 From: svkalinin Date: Sun, 28 Nov 2021 10:30:05 +0300 Subject: [PATCH] Initial release --- csv2glpi/go.mod | 7 + csv2glpi/importer.go | 172 ++++++ glpi/LICENSE | 339 ++++++++++++ glpi/README-ru.md | 398 ++++++++++++++ glpi/README.md | 195 +++++++ glpi/glpi.go | 1034 ++++++++++++++++++++++++++++++++++++ glpi/go.mod | 3 + zabbix2glpi/go.mod | 12 + zabbix2glpi/zabbix2glpi.go | 487 +++++++++++++++++ 9 files changed, 2647 insertions(+) create mode 100644 csv2glpi/go.mod create mode 100644 csv2glpi/importer.go create mode 100644 glpi/LICENSE create mode 100644 glpi/README-ru.md create mode 100644 glpi/README.md create mode 100644 glpi/glpi.go create mode 100644 glpi/go.mod create mode 100644 zabbix2glpi/go.mod create mode 100644 zabbix2glpi/zabbix2glpi.go diff --git a/csv2glpi/go.mod b/csv2glpi/go.mod new file mode 100644 index 0000000..5509f9f --- /dev/null +++ b/csv2glpi/go.mod @@ -0,0 +1,7 @@ +module importer + +go 1.16 + +replace glpi => ../glpi + +require glpi v0.0.0-00010101000000-000000000000 // indirect diff --git a/csv2glpi/importer.go b/csv2glpi/importer.go new file mode 100644 index 0000000..5fe4d44 --- /dev/null +++ b/csv2glpi/importer.go @@ -0,0 +1,172 @@ +package main + +import ( + "encoding/csv" + "strings" + // "encoding/json" + "flag" + "fmt" + "glpi" + "os" + "reflect" + "strconv" + "unicode/utf8" +) + +var ( + glpiServerAPI string + glpiUserToken string + glpiAppToken string + glpiAssetsType string + glpiVersion bool + operation string + inFileName string + inFormat string + inCSVSeparator string + inCSVComment string + outFileName string + outFormat string + outCSVSeparator string + outCSVComment string +) + +func CSVToGLPI(glpiAPI *glpi.Session, fileName string) { + file, err := os.Open(fileName) + if err != nil { + panic(err) + } + defer file.Close() + + reader := csv.NewReader(file) + reader.Comment, _ = utf8.DecodeRuneInString(inCSVComment) + reader.Comma, _ = utf8.DecodeRuneInString(inCSVSeparator) + reader.TrimLeadingSpace = true + + headers, err := reader.Read() + if err != nil { + fmt.Println(err) + } + + for { + record, err := reader.Read() + if err != nil { + fmt.Println(err) + break + } + fmt.Println(record) + var ( + recordMap glpi.GlpiPhone + ) + + // recordMap.Name = "test" + // Read the headers and find field name in structure + for fieldIndex, fieldName := range headers { + s := reflect.ValueOf(&recordMap).Elem() + typeOfT := s.Type() + for i := 0; i < s.NumField(); i++ { + // if the field is found in the structure, we assign it a value of the appropriate type + if strings.EqualFold(strings.ToLower(fieldName), strings.ToLower(typeOfT.Field(i).Name)) { + switch fmt.Sprint(typeOfT.Field(i).Type) { + case "int": + convValue, _ := strconv.Atoi(record[fieldIndex]) + s.Field(i).SetInt(int64(convValue)) + case "string": + s.Field(i).SetString(record[fieldIndex]) + case "bool": + convValue, _ := strconv.ParseBool(record[fieldIndex]) + s.Field(i).SetBool(convValue) + } + } + } + } + // fmt.Println(recordMap) + fmt.Println("Added", glpiAssetsType, "with ID:", glpiAPI.ItemOperation("add", glpiAssetsType, recordMap)) + } +} + +func ExportFromGLPI(glpiAPI *glpi.Session, fileName string) { + fmt.Println(fileName) + // file, err := os.Open(fileName) + // if err != nil { + // panic(err) + // } + // defer file.Close() + + // reader := csv.NewReader(file) + // reader.Comma = outCSVSeparator +} + +func main() { + + flag.StringVar(&glpiServerAPI, "glpi-server-api", "", "Glpi instance API URL. GLPI_SERVER_URL") + flag.StringVar(&glpiUserToken, "glpi-user-token", "", "Glpi user API token. GLPI_USER_TOKEN") + flag.StringVar(&glpiAppToken, "glpi-app-token", "", "Glpi aplication API token. GLPI_APP_TOKEN") + flag.StringVar(&glpiAssetsType, "glpi-assets-type", "", "Glpi assets type (aka Computer, Printer, Phone, e.t.c.)") + flag.BoolVar(&glpiVersion, "glpi-version", false, "Get the Glpi version") + + flag.StringVar(&operation, "operation", "", "import - import data to GLPI from file\n\texport - export data from GLPI to file\n\t") + + flag.StringVar(&inFileName, "in-file", "", "the name of the file containing the imported data") + flag.StringVar(&inFormat, "in-format", "csv", "input file data format") + flag.StringVar(&inCSVSeparator, "in-csv-separator", ";", "input csv-file separator") + flag.StringVar(&inCSVComment, "in-csv-comment", "#", "input csv-file comments symbol") + + flag.StringVar(&outFileName, "out-file", "", "the name of the file containing the exported data") + flag.StringVar(&outFormat, "out-format", "json", "Output format: 'go' - go map, 'json' - json string, 'csv' - common separated value") + flag.StringVar(&outCSVSeparator, "out-csv-separator", ";", "output csv-file separator") + flag.StringVar(&outCSVComment, "out-csv-comment", "#", "output csv-file comments symbol") + flag.Parse() + + //----------------------------------------------------------- + if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_SERVER_API`, or used with '-glpi-server-api' argument") + os.Exit(1) + } else if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") != "" { + glpiServerAPI = os.Getenv("GLPI_SERVER_API") + } + + if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_USER_TOKEN`, or used with '-glpi-user-token' argument") + os.Exit(1) + } else if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") != "" { + glpiUserToken = os.Getenv("GLPI_USER_TOKEN") + } + + if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_APP_TOKEN`, or used with '-glpi-app-token' argument") + os.Exit(1) + } else if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") != "" { + glpiAppToken = os.Getenv("GLPI_APP_TOKEN") + } + + glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken) + if err != nil { + fmt.Println(err) + return + } + _, err = glpiSession.InitSession() + if err != nil { + fmt.Println(err) + return + } + + if glpiVersion { + fmt.Println("GLPI version:", glpiSession.Version()) + } + + switch operation { + case "import": + if inFileName == "" || glpiAssetsType == "" { + fmt.Println("Setting the input file name and glpi assets type, use the '-in-file' and '-glpi-assets-type' argument") + } else { + CSVToGLPI(glpiSession, inFileName) + } + case "export": + if outFileName == "" { + fmt.Println("Setting the output file name, use the '-out-file' argument") + } else { + ExportFromGLPI(glpiSession, outFileName) + } + } + glpiSession.KillSession() +} diff --git a/glpi/LICENSE b/glpi/LICENSE new file mode 100644 index 0000000..22fbe5d --- /dev/null +++ b/glpi/LICENSE @@ -0,0 +1,339 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. \ No newline at end of file diff --git a/glpi/README-ru.md b/glpi/README-ru.md new file mode 100644 index 0000000..79d9740 --- /dev/null +++ b/glpi/README-ru.md @@ -0,0 +1,398 @@ +Данный модуль для языка GO реализует механизм работы с HTTP API системы GLPI. Описание АПИ доступно по адресу https://github.com/glpi-project/glpi/blob/9.5/bugfixes/apirest.md, и также в установленной системе по ссылке https://glpi/apirest.php . + +Ниже представлен вариант использования на примере работы с принтером. Т.е. в примере будет выполнено: +- Добавление производителя +- Добавление модели принтера +- Добавление домена +- Добавление сети (виртуальная сущность связывающаяя активы на сетевом уровне) +- Добавление принтера +- Добавление сетевого порта и привязка его к принтеру +- Добавление IP-адреса и привязка его к порту +- Добавление модели картриджа +- Добавление картриджа как еденицы учета +- "Установка" картриджа (привязка его к соответствующему принтеру) + +Алгоритм работы с активами и другими сущностями GLPI ничем не отличается от данного примера. + +# Краткое описание API + +## Инициализация сессии + + Работа с API в GLPI производится в рамках сессии, которая определяется на основе кода доступа (токена). Данный код генерится и возвращается после положительной авторизации пользователя. Для этого требуется выполнить HTTP запрос к API методу "initSession" и передать в нём Application токен ("Настройки" -> "Общие" -> "API") и токен пользователя ("Администрирование" -> "Пользователи" -> Пользователь -> "Ключи Удаленного доступа") либо имя и пароль. + + ```curl -s -X GET -H "Content-Type: application/json" -H "Authorization: user_token ${GLPI_USER_TOKEN}" -H "App-Token: ${GLPI_APP_TOKEN}" "https://glpi/apirest.php/initSession"``` + +При положительном ответе система вернет: + +``` +{ + "session_token": "6ud8p3llbvl4qkf56t7klvhvr" +} +``` + +В дальнейшем в запросах передается токен приложения и токен сессии: + +```curl -s -X GET -H "Content-Type: application/json" -H "Session-Token: ${GLPI_SESSION_TOKEN}" -H "App-Token: ${GLPI_APP_TOKEN}" "https://glpi/apirest.php/passivedcequipment"``` + +## Получение данных из GLPI + +Для получения данных необходимо выполнить http-запрос к определенному методу API. Например для вывода информации о всех компьютерах ссылка будет выглядеть вот так: + +```"https://glpi/apirest.php/computer"``` + +для получения данных по конкретному компьютеру: + +```"https://glpi/apirest.php/computer/123"``` + + +где "computer" - это тип актива (сущности, еденицы учета и т.п.), "123" - это уникальный идентификатор записи. + +# Пример использования go-модуля glpi + +## Импорт пакетов + +``` go +package main +import ( + "encoding/json" + "fmt" + "glpi" + "os" +) +``` + +## Установка переменных +Объявляем и инициализируем переменные: + +``` go +var ( + glpiServerAPI string + glpiUserToken string + glpiAppToken string +) +glpiServerAPI = os.Getenv("GLPI_SERVER_API") +glpiUserToken = os.Getenv("GLPI_USER_TOKEN") +glpiAppToken = os.Getenv("GLPI_APP_TOKEN") +``` + +* glpiServerAPI - адрес вызова API, в нашем случае берется из переменной окружения и равен https://glpi/apirest.php +* glpiUserToken - код доступа к API GLPI для конкретного пользователя +* glpiAppToken - код доступа к API GLPI + +Для удобства работы, значения для данных переменных, беруться из переменных окружения. + +Так как для начала работы необходимо получить код доступа для конкретной сессии, то произведем инициализацию сессиии: +``` go +glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken) +if err != nil { + fmt.Println(err) + return +} +``` +glpi.NewSession - создает переменную типа Session и возвращает указатель на нее. + +``` go +_, err = glpiSession.InitSession() +if err != nil { + fmt.Println(err) + return +} +``` +glpiSession.InitSession() - инициализирует сессию, т.е. при вызове данной функции, происходит подключение к GLPI API и возвращается значение кода доступа (токена)сессии. Его значение сохраняется в поле структуры "glpiSession.sessionToken". Данный код можно посмотреть вызвав функцию "glpiSession.GetSessionToken()", т.е. + +```fmt.Println(glpiSession.GetSessionToken())``` + +Установим значения некоторых переменных: + +``` go +itemType := "Printer" +printerName := "acc-prn1" +printerDomain := "domain.local" +``` + +В GLPI API для поиска данных реализован метод search, вызываемый по ссылке http://glpi/apirest.php/search/itemtype/, где itemtype это тип еденицы учета либо другой сущности внутри GLPI (computer, monitor, printer, line и так далее). + +В модуле glpi для поиска используется функция "SearchItem(itemType string, itemName string)" вызываемая с параметрами: + +- itemType - вышеозначенный тип +- itemName - имя. + +В случае положительного результата функция возвращает цифровой уникальный идентификатор записи "ID". + +Тут стоит остановиться подробнее на описании структуры и типах. В GO-модуле glpi каждая из сущностей представлена ввиде структуры с соответсвующим именем. Внтури структуры описано соответствие её полей и полей в итоговом JSON запросе. Например для производителей: + +``` go +type GlpiManufacturer struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} +``` + +Имена и типы полей go-структуры соответсвуют именам и типам таковых в JSON, кроме первой буквы (в json она маленькая). + +Для операций с записями в модуле реализованы функции с именами соответствующими glpi-типам (кроме простых типов с одинаковой струкрутрой). Функция на вход принимает тип запроса ("add" - добавление записи, "update" - редактирование, "delete" -удаление) и структуру соответствующего типа. + +Т.е. для производителей это будет glpiSession.Manufacturer("add", manufacturersData) для принтеров glpiSession.Printer("add", printerData) и так далее. + +Для простых типов введена структура: + +``` go +type GlpiSimpleItem struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} +``` + +Для моделей оборудования различного типа: + +``` go +type GlpiItemModel struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` + Product_number string `json:"product_number"` +} +``` + +И соответсвенно им и функции SimpleItem() и ItemModel(). + +В данном примере произведем поиск производителя по наименованию, и если записи с таким именем не найдено то добавим её. + +``` go +// Get manufacturer ID or append new records/ +manufacturersID := glpiSession.SearchItem("Manufacturer", "Systers") +if manufacturersID == 0 { + manufacturersData := glpi.GlpiManufacturer{ + Name: "Systers", + Comment: "Holly Systers inc.", + } + manufacturersID = glpiSession.ItemOperation("add", "Manufacturer", manufacturersData) +} +``` + +Т.е. если manufacturersID будет равен 0 то инициализируем переменную типа GlpiManufacturer, заполним поля требуемыми значениями и вызовем нужную функцию. На выходе получим ID производителя для дальнейшего использования. + +Найдем или добавим сеть (в данном контексте "сеть" - используется для объединения активов и построения схемы сети): + +``` go +// Get network ID or append new records/ +networksID := glpiSession.SearchItem("Network", "Head office") +if networksID == 0 { + networksData := glpi.GlpiSimpleItem{ + Name: "Head office", + Comment: "Head office network", + } + networksID = glpiSession.ItemOperation("add", "Network", networksData) +} +``` + +Модель принтера: + +``` go +// Search a used printer model, or append if don't find it. +printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200") +if printerModelID == 0 { + printerModelData := glpi.GlpiItemModel{ + Name: "Sys 1200", + } + printerModelID = glpiSession.ItemOperation("add", "PrinterModel", printerModelData) +} +```` + + +Аналогичным образом поступаем и с остальными данными. Добавляем принтер с данными указанными в нижеприведенной структуре. В значениях полей указаны идентификаторы уже созданных записей, плюс переменные полученные выше (в принципе, для добавления принтера достаточно одного имени, остальное можно добавить позже): + +``` go +printerData := glpi.GlpiPrinter{ + Name: printerName, + Locations_id: 1, + Users_id_tech: 3, + Users_id: 2, + Groups_id_tech: 1, + Groups_id: 2, + Have_usb: 1, + Networks_id: networksID, + Manufacturers_id: manufacturersID, + Printermodels_id: printerModelID, +} + +printerID := glpiSession.ItemOperation("add", "Printer", printerData) +fmt.Println("Printer was added, ID:", printerID) +``` + +Так как принтер подразумевается сетевой то добавим к нему сетевой порт и привяжем к нему IP-адрес. Данная функциональность подобным образом обрабатывается и для других активов GLPI, т.е. алгоритм работы тот-же меняются только itemtype. + +Добавляем порт: + +``` go +// Added Ethernet network port +networkPortData := glpi.GlpiNetworkPort{ + Name: "Eth1", + Items_id: printerID, + Itemtype: itemType, + Logical_number: 1, + Instantiation_type: "NetworkPortEthernet", +} +glpiPortID := glpiSession.ItemOperation("add", "NetworkPort", networkPortData) +fmt.Println("Network port was added, ID: ", glpiPortID) +```` + +Добавляем домен: + +``` go +// Getting domain ID, or add it +glpiFqdnID := glpiSession.SearchItem("FQDN", printerDomain) +if glpiFqdnID == 0 { + fqdnData := glpi.GlpiFQDN{ + Name: printerDomain, + FQDN: printerDomain, + Comment: "Our local domain", + } + glpiFqdnID = glpiSession.ItemOperation("add", "fqdn", fqdnData) +} +fmt.Println("Domain - ", printerDomain, glpiFqdnID) +``` + +Связываем воедино сетевой порт, сетевое имя принтера и домен: + +``` go + networkData := glpi.GlpiNetworkName{ + Name: printerName, + Itemtype: "NetworkPort", + Items_id: glpiPortID, + Fqdns_id: glpiFqdnID, + Comment: "Network port", + } + glpiNetworkID := glpiSession.ItemOperation("add", "NetworkName", networkData) + fmt.Println("Added network name for", printerName, "with ID:", glpiNetworkID) +``` + +Добавляем IP-адрес и привязываем его к принтеру и сетевому имени (порту): + +``` go +ipData := glpi.GlpiIPAddress{ + Name: "172.30.30.123", + Itemtype: "NetworkName", + Items_id: glpiNetworkID, + Mainitems_id: printerID, + Mainitemtype: itemType, + Comment: "Network port", +} +glpiIpAddressID := glpiSession.ItemOperation("add", "IPAddress", ipData) +fmt.Println("Added IP address:", glpiIpAddressID) +``` + +Т.е. схема добавления "Железка" -> "Порт" -> "Сетевое имя (сеть)" -> "IP-адрес" будет общая для всех активов или устройств имеющих сетевые порты. + +На этом с принтером всё. Теперь можно добавить картриджей. Сперва добавляем модель картриджа + +``` go +// ADD cartridge +requestDataCartridgeItem := glpi.GlpiCartridgeItem{ + // Id: "11", + Name: "С4092B", + // Users_id_tech: 3, + // Users_id: 2, + // Groups_id_tech: 1, + // Groups_id: 2, + // Cartridgeitemtypes_id: 0, + Manufacturers_id: manufacturersID, + Alarm_threshold: 5, +} +cartridgeItemsID := glpiSession.ItemOperation("add", "CartridgeItem", requestDataCartridgeItem) +fmt.Println("Add a cartridge item:", cartridgeItemsID) +``` + +Затем указываем соответсвие (добавляем запись) между моделью принтера и моделью картриджа + +``` go +// Linked printer model and cartridge +// printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200") +requestData := glpi.GlpiCartridgeItemPrinterModel{ + // Id: "11", + Cartridgeitems_id: cartridgeItemsID, + Printermodels_id: printerModelID, +} + +cartridgeItemsPrinterModel := glpiSession.ItemOperation("add", "cartridgeitem_printermodel", requestData) +fmt.Println("Added a link between Cartridge model and Printer model:", cartridgeItemsPrinterModel) +``` + +Затем добавляем картридж уже как еденицу хранения, привязывая к модели: + +``` go +// Get the ID of an existing printer, or add it +// printerID = glpiSession.SearchItem("Printer", "acc-prn1") + +requestDataCartridge := glpi.GlpiCartridge{ + // Id: "11", + Cartridgeitems_id: cartridgeItemsID, +} + +cartridgeID := glpiSession.ItemOperation("add", "Cartridge", requestDataCartridge) +fmt.Println("Added a cartridge:", cartridgeID) +``` + +"Установим" картридж в принтер, т.е. привяжем конкретный картридж к конкретному принтеру: + +``` go +// Getting a new cartridge info +res := glpiSession.GetItem("Cartridge", cartridgeID, "") +fmt.Println("Cartridge:", string(res)) + +var cartridgeInfo glpi.GlpiCartridge +err = json.Unmarshal(res, &cartridgeInfo) + +if err != nil { + fmt.Println(err) +} + +// Installing the cartridge in the printer +cartridgeInfo.Printers_id = printerID +cartridgeInfo.Date_use = "2021-08-20" + +res1 := glpiSession.ItemOperation("update", "Cartridge", cartridgeInfo) +fmt.Println("Add a link between cartridge and printer:", res1) +``` + +Перед обновлением конкретной записи требуется выбрать все данные и сохранить в переменную соответствующего типа, если этого не сделать то при выполнении операции "update" не инициализированные поля будут пустыми (т.е. данные затрутся). + +Для получения информации о конкретном оборудовании в модуле есть функция ```GetItem(itemType string, itemID int, otherParam string)```. Она принимает на вход тип оборудования и его ID, возвращает JSON ввиде массива байт ([]byte). Так как функция GetItem() возвращает JSON, то его можно увидеть просто преобразовав байты в строку при помощи string() + +Получим информацию о добавленном картридже и выведем в косоль: + +``` go +// Getting a new cartridge info +res := glpiSession.GetItem("Cartridge", cartridgeID, "") +fmt.Println("Cartridge:", string(res)) +``` + +Для преобразования данных из json в структуру требуемого нам типа применим функцию json.Unmarshal(): + +``` go +var cartridgeInfo glpi.GlpiCartridge +err = json.Unmarshal(res, &cartridgeInfo) +if err != nil { + fmt.Println(err) +} +fmt.Println("Cartridge:", cartridgeInfo) +``` + +Доступ к полям структуры можно получить штатным образом: + +- cartridgeInfo.Id - уникальный идентификатор +- cartridgeInfo.Printers_id - идентификатор принтера +- cartridgeInfo.Date_in - дата установкии +- и т.д. + +После выполнения всех операция удаляем нашу сессию. GLPI периодически сессии очищает сам, но лучше удалить: + +``` go +_, err = glpiSession.KillSession() +if err != nil { + fmt.Println(err) + return +} +``` \ No newline at end of file diff --git a/glpi/README.md b/glpi/README.md new file mode 100644 index 0000000..f155c4b --- /dev/null +++ b/glpi/README.md @@ -0,0 +1,195 @@ +GLPI +==== + +This Go library implements the GLPI HTTP REST API. This module provides working with all the assets and some GLPI items. + +Getting started +=============== + +## Setting the variables + +Setting a three variables for connecting a GLPI API: + +``` go +var ( + glpiServerAPI string + glpiUserToken string + glpiAppToken string +) +glpiServerAPI = os.Getenv("GLPI_SERVER_API") +glpiUserToken = os.Getenv("GLPI_USER_TOKEN") +glpiAppToken = os.Getenv("GLPI_APP_TOKEN") +``` + +Where: + +- GLPI_USER_TOKEN - the API access token for each user (setting in a user profile) +- GLPI_APP_TOKEN - the application token (setting in the "Setup"->"General"->"API" section GLPI UI) +- GLPI_SERVER_API - API URL (like as https://glpi/apirest.php) + +## Connection to the API and initial session + +``` go +glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken) +if err != nil { + fmt.Println(err) + return +} +_, err = glpiSession.InitSession() +if err != nil { + fmt.Println(err) + return +} +``` +glpiSession.InitSession() - initializes the session, i.e. when this function is called, the module is connected to the GLPI and the session access code (token) is returned. Its value is stored in the field of the "glpi Session.session Token" structure. This code can be viewed by calling the function "glpi Session.Get Session Token ()", i.e. + +``` go +fmt.Println(glpiSession.GetSessionToken()) +``` + +Work with some items +==================== + +## Adding the Manufacturer + +``` go +manufacturersData := glpi.GlpiManufacturer{ + Name: "Yet Another", + Comment: "Yet Another inc.", +} +manufacturersID = glpiSession.ItemOperation("add", "Manufacturer", manufacturersData) +``` + +If it's all right, the new manufacturers ID will be written to the "manufacturersID" variable. + +## Adding the printers model + +For simple model types, you should use the structure GlpiItemModel and ItemModel() function: + +``` go +type GlpiSimpleItem struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} +``` + +Adding the new printer model: + +``` go +printerModelData := glpi.GlpiItemModel{ + Name: "Sys 1200", +} +printerModelID = glpiSession.ItemOperation("add", "PrinterModel", printerModelData) +``` + +## Adding the printer + +``` go +// Add new printer +printerData := glpi.GlpiPrinter{ + // Id: "11", + Name: "First printer", + Have_usb: 1, + Manufacturers_id: manufacturersID, + Printermodels_id: printerModelID, +} + +printerID := glpiSession.ItemOperation("add", "Printer", printerData) +fmt.Println("Printer was added, ID:", printerID) +``` + +## Adding a cartridge model and linking them to the printer model + +``` go +// ADD cartridge +requestDataCartridgeItem := glpi.GlpiCartridgeItem{ + // Id: "11", + Name: "С4092B", + Manufacturers_id: manufacturersID, + Alarm_threshold: 5, +} +cartridgeItemsID := glpiSession.ItemOperation("add", "CartridgeItem", requestDataCartridgeItem) +fmt.Println("Add a cartridge item:", cartridgeItemsID) + +// Linked printer model and cartridge +// printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200") +requestData := glpi.GlpiCartridgeItemPrinterModel{ + // Id: "11", + Cartridgeitems_id: cartridgeItemsID, + Printermodels_id: printerModelID, +} + +cartridgeItemsPrinterModel := glpiSession.ItemOperation("add", "cartridgeitem_printermodel", requestData) +fmt.Println("Added a link between Cartridge model and Printer model:", cartridgeItemsPrinterModel) +``` + +## Adding a cartridge and linking them to the printer + +``` go +requestDataCartridge := glpi.GlpiCartridge{ + // Id: "11", + Cartridgeitems_id: cartridgeItemsID, +} + +cartridgeID := glpiSession.ItemOperation("add", "Cartridge", requestDataCartridge) +fmt.Println("Added a cartridge:", cartridgeID) + +// Getting a new cartridge info +res := glpiSession.GetItem("Cartridge", cartridgeID, "") +fmt.Println("Cartridge:", string(res)) + +var cartridgeInfo glpi.GlpiCartridge +err = json.Unmarshal(res, &cartridgeInfo) + +if err != nil { + fmt.Println(err) +} + +// Installing the cartridge in the printer +cartridgeInfo.Printers_id = printerID +cartridgeInfo.Date_use = "2021-08-20" + +res1 := glpiSession.ItemOperation("update", "Cartridge", cartridgeInfo) +fmt.Println("Add a link between cartridge and printer:", res1) +``` + +## Search the items + +To get the element ID, the module provides the ```SearchItem()``` function: + +``` func (glpi *Session) SearchItem(itemType string, itemName string) int {}``` + +If an element with the specified name was found, the function returns its ID. + +``` go +// Get network ID or append new records/ +networksID := glpiSession.SearchItem("Network", "Head office") +if networksID == 0 { + networksData := glpi.GlpiSimpleItem{ + Name: "Head office", + Comment: "Head office network", + } + networksID = glpiSession.ItemOperation("add", "Network", networksData) +} +``` + +Getting ended +============= + +## Kill the session + +After all operations are completed, the session should be closed + +``` go +_, err = glpiSession.KillSession() +if err != nil { + fmt.Println(err) + return +} +``` + +License +======= + +Released under the GNU GPL License \ No newline at end of file diff --git a/glpi/glpi.go b/glpi/glpi.go new file mode 100644 index 0000000..554ccee --- /dev/null +++ b/glpi/glpi.go @@ -0,0 +1,1034 @@ +package glpi + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "strconv" + "strings" + "time" +) + +type Session struct { + url string + userToken string + appToken string + sessionToken string +} + +type GlpiComputer struct { + Id int `json:"id"` + Autoupdatesystems_id int `json:"autoupdatesystems_id"` + Computermodels_id int `json:"computermodels_id"` + Computertypes_id int `json:"computertypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Entities_id int `json:"entities_id"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Is_deleted int `json:"is_deleted"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Networks_id int `json:"networks_id"` + Otherserial string `json:"otherserial"` + Serial string `json:"serial"` + States_id int `json:"states_id"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` + UUID string `json:"uuid"` + Template_name string `json:"template_name"` +} + +type GlpiMonitor struct { + Id int `json:"id"` + Monitormodels_id int `json:"monitormodels_id"` + Monitortypes_id int `json:"monitortypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Entities_id int `json:"entities_id"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Is_global int `json:"is_global"` + Is_template int `json:"is_template"` + Is_deleted int `json:"is_deleted"` + Have_micro int `json:"have_micro"` + Have_speaker int `json:"have_speaker"` + Have_subd int `json:"have_subd"` + Have_bnc int `json:"have_bnc"` + Have_dvi int `json:"have_dvi"` + Have_pivot int `json:"have_pivot"` + Have_hdmi int `json:"have_hdmi"` + Have_displayport int `json:"have_displayport"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Otherserial string `json:"otherserial"` + Serial string `json:"serial"` + Size string `json:"size"` + States_id int `json:"states_id"` + Template_name string `json:"template_name"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` +} + +type GlpiSoftware struct { + Id int `json:"id"` + Comment string `json:"comment"` + Entities_id int `json:"entities_id"` + Is_helpdesk_visible int `json:"is_helpdesk_visible"` + Is_update int `json:"is_update"` + Is_template int `json:"is_template"` + Is_valid int `json:"is_valid"` + Is_deleted int `json:"is_deleted"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Softwares_id int `json:"softwares_id"` + Softwarecategories_id int `json:"softwarecategories_id"` + Template_name string `json:"template_name"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` +} + +type GlpiOperatingSystem struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} + +type GlpiManufacturer struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} + +type GlpiComputerModel struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` + Product_number string `json:"product_number"` + Weight int `json:"weight"` + Required_units int `json:"required_units"` + Depth int `json:"depth"` + Power_connections int `json:"power_connections"` + Power_consumption int `json:"power_consumption"` + Is_half_rack int `json:"is_half_rack"` + Picture_front string `json:"picture_front"` + Picture_rear string `json:"picture_rear"` +} + +type GlpiNetworkEquipment struct { + Id int `json:"id"` + Networkequipmentmodels_id int `json:"networkequipmentmodels_id"` + Networkequipmenttypes_id int `json:"networkequipmenttypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Entities_id int `json:"entities_id"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Is_deleted int `json:"is_deleted"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Networks_id int `json:"networks_id"` + Otherserial string `json:"otherserial"` + Ram string `json:"ram"` + Serial string `json:"serial"` + States_id int `json:"states_id"` + Template_name string `json:"template_name"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` +} + +type GlpiInfocom struct { + Id int `json:"id"` + Bill string `json:"bill"` + Budgets_id int `json:"budgets_id"` + Businesscriticities_id int `json:"businesscriticities_id"` + Buy_date string `json:"buy_date"` + Comment string `json:"comment"` + Decommission_date string `json:"decommission_date"` + Delivery_date string `json:"delivery_date"` + Delivery_number string `json:"delivery_number"` + Entities_id int `json:"entities_id"` + Immo_number string `json:"immo_number"` + Inventory_date string `json:"inventory_date"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Order_date string `json:"order_date"` + Order_number string `json:"order_number"` + Sink_coeff int `json:"sink_coeff"` + Sink_time int `json:"sink_time"` + Sink_type int `json:"sink_type"` + Suppliers_id int `json:"suppliers_id"` + Use_date string `json:"use_date"` + Value string `json:"value"` + Warranty_date string `json:"warranty_date"` + Warranty_duration int `json:"warranty_duration"` + Warranty_info string `json:"warranty_info"` + Warranty_value string `json:"warranty_value"` +} + +type GlpiTicket struct { + Id int `json:"id"` + Entities_id int `json:"entities_id"` + Name string `json:"name"` + Date string `json:"date"` + Closedate string `json:"closedate"` + Solvedate string `json:"solvedate"` + Status int `json:"status"` + Users_id_lastupdater int `json:"users_id_lastupdater"` + Users_id_recipient int `json:"users_id_recipient"` + Requesttypes_id int `json:"requesttypes_id"` + Content string `json:"content"` + Urgency int `json:"urgency"` + Impact int `json:"impact"` + Priority int `json:"priority"` + Itilcategories_id int `json:"itilcategories_id"` + Ticket_type int `json:"type"` + Global_validation int `json:"global_validation"` + Slas_id_ttr int `json:"slas_id_ttr"` + Slas_id_tto int `json:"slas_id_tto"` + Slalevels_id_ttr int `json:"slalevels_id_ttr"` + Time_to_resolve string `json:"time_to_resolve"` + Time_to_own string `json:"time_to_own"` + Begin_waiting_date string `json:"begin_waiting_date"` + Sla_waiting_durationrity int `json:"sla_waiting_duration"` + Ola_waiting_duration int `json:"ola_waiting_duration"` + Olas_id_tto int `json:"olas_id_tto"` + Olas_id_ttr int `json:"olas_id_ttr"` + Olalevels_id_ttr int `json:"olalevels_id_ttr"` + Ola_ttr_begin_date string `json:"ola_ttr_begin_date"` + Internal_time_to_resolve string `json:"internal_time_to_resolve"` + Internal_time_to_own string `json:"internal_time_to_own"` + Waiting_duration int `json:"waiting_duration"` + Close_delay_stat int `json:"close_delay_stat"` + Solve_delay_stat int `json:"solve_delay_stat"` + Takeintoaccount_delay_stat int `json:"takeintoaccount_delay_stat"` + Actiontime int `json:"actiontime"` + Is_deleted int `json:"is_deleted"` + Locations_id int `json:"locations_id"` + Validation_percent int `json:"validation_percent"` +} + +type GlpiOSItem struct { + Id int `json:"id"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Entities_id int `json:"entities_id"` + Operatingsystems_id int `json:"operatingsystems_id"` + Operatingsystemversions_id int `json:"operatingsystemversions_id"` + Operatingsystemservicepacks_id int `json:"operatingsystemservicepacks_id"` + Operatingsystemarchitectures_id int `json:"operatingsystemarchitectures_id"` + Operatingsystemkernelversions_id int `json:"operatingsystemkernelversions_id"` + Operatingsystemeditions_id int `json:"operatingsystemeditions_id"` + License_number string `json:"license_number"` + Licenseid string `json:"licenseid"` +} + +type GlpiPeripheral struct { + Id int `json:"id"` + Peripheralmodels_id int `json:"peripheralmodels_id"` + Peripheraltypes_id int `json:"peripheraltypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Entities_id int `json:"entities_id"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Is_global int `json:"is_global"` + Is_template int `json:"is_template"` + Is_deleted int `json:"is_deleted"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Otherserial string `json:"otherserial"` + Brand string `json:"brand"` + Serial string `json:"serial"` + States_id int `json:"states_id"` + Template_name string `json:"template_name"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` +} + +type GlpiPrinter struct { + Id int `json:"id"` + Printermodels_id int `json:"printermodels_id"` + Printertypes_id int `json:"printertypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Is_global int `json:"is_global"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Have_serial int `json:"have_serial"` + Have_parallel int `json:"have_parallel"` + Have_usb int `json:"have_usb"` + Have_wifi int `json:"have_wifi"` + Have_ethernet int `json:"have_ethernet"` + Memory_size string `json:"memory_size"` + Init_pages_counter int `json:"init_pages_counter"` + Last_pages_counter int `json:"last_pages_counter"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Networks_id int `json:"networks_id"` + Otherserial string `json:"otherserial"` + Serial string `json:"serial"` + States_id int `json:"states_id"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` + Is_template int `json:"is_template"` + Template_name string `json:"template_name"` + Is_deleted int `json:"is_deleted"` +} + +// https://glpi/apirest.php/cartridge +type GlpiCartridge struct { + Id int `json:"id"` + Cartridgeitems_id int `json:"cartridgeitems_id"` + Entities_id int `json:"entities_id"` + Printers_id int `json:"printers_id"` + Date_in string `json:"date_in"` + Date_use string `json:"date_use"` + Date_out string `json:"date_out"` + Pages int `json:"pages"` +} + +// https://glpi/apirest.php/cartridgeitem +type GlpiCartridgeItem struct { + Id int `json:"id"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Name string `json:"name"` + Ref string `json:"ref"` + Cartridgeitemtypes_id int `json:"cartridgeitemtypes_id"` + Manufacturers_id int `json:"manufacturers_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Comment string `json:"comment"` + Alarm_threshold int `json:"alarm_threshold"` + Is_deleted int `json:"is_deleted"` +} + +// https://glpi/apirest.php/cartridgeitem_printermodel +type GlpiCartridgeItemPrinterModel struct { + Id int `json:"id"` + Cartridgeitems_id int `json:"cartridgeitems_id"` + Printermodels_id int `json:"printermodels_id"` +} + +// https://glpi/apirest.php/Consumable +type GlpiConsumable struct { + Id int `json:"id"` + Consumableitems_id int `json:"consumableitems_id"` + Entities_id int `json:"entities_id"` + Date_in string `json:"date_in"` + Date_out string `json:"date_out"` + Itemtype string `json:"itemtype"` + Items_id int `json:"items_id"` +} + +// https://glpi/apirest.php/consumableitem +type GlpiConsumableItem struct { + Id int `json:"id"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Name string `json:"name"` + Ref string `json:"ref"` + Сonsumableitemtypes_id int `json:"consumableitemtypes_id"` + Manufacturers_id int `json:"manufacturers_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Comment string `json:"comment"` + Alarm_threshold int `json:"alarm_threshold"` + Otherserial string `json:"otherserial"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/phone +type GlpiPhone struct { + Id int `json:"id"` + Brand string `json:"brand"` + Phonemodels_id int `json:"phonemodels_id"` + Phonetypes_id int `json:"phonetypes_id"` + Comment string `json:"comment"` + Contact string `json:"contact"` + Contact_num string `json:"contact_num"` + Entities_id int `json:"entities_id"` + Groups_id int `json:"groups_id"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Is_global int `json:"is_global"` + Is_deleted int `json:"is_deleted"` + Locations_id int `json:"locations_id"` + Manufacturers_id int `json:"manufacturers_id"` + Name string `json:"name"` + Phonepowersupplies_id int `json:"phonepowersupplies_id"` + Otherserial string `json:"otherserial"` + Serial string `json:"serial"` + States_id int `json:"states_id"` + Users_id int `json:"users_id"` + Users_id_tech int `json:"users_id_tech"` + Template_name string `json:"template_name"` + Have_headset int `json:"have_headset"` + Have_hp int `json:"have_hp"` + Number_line string `json:"number_line"` +} + +// http://glpi/apirest.php/rack +type GlpiRack struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Serial string `json:"serial"` + Otherserial string `json:"otherserial"` + Rackmodels_id int `json:"phonemodels_id"` + Manufacturers_id int `json:"manufacturers_id"` + Racktypes_id int `json:"phonetypes_id"` + States_id int `json:"states_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Width int `json:"width"` + Height int `json:"height"` + Depth int `json:"depth"` + Number_units int `json:"number_units"` + Is_template int `json:"is_template"` + Template_name string `json:"template_name"` + Dcrooms_id int `json:"dcrooms_id"` + Room_orientation int `json:"room_orientation"` + Position string `json:"position"` + Bgcolor string `json:"bgcolor"` + Max_power int `json:"max_power"` + Mesured_power int `json:"mesured_power"` + Max_weight int `json:"max_weight"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/item_rack +type GlpiRackItem struct { + Id int `json:"id"` + Racks_id int `json:"racks_id"` + Itemtype string `json:"itemtype"` + Items_id int `json:"items_id"` + Position int `json:"position"` + Orientation int `json:"orientation"` + Bgcolor string `json:"bgcolor"` + Hpos int `json:"hpos"` + Is_reserved int `json:"is_reserved"` +} + +// http://glpi/apirest.php/enclosure +type GlpiEnclosure struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Serial string `json:"serial"` + Otherserial string `json:"otherserial"` + Enclosuremodels_id int `json:"enclosuremodels_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Template_name string `json:"template_name"` + Orientation int `json:"orientation"` + Power_supplies int `json:"power_supplies"` + States_id int `json:"states_id"` + Comment string `json:"comment"` + Manufacturers_id int `json:"manufacturers_id"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/enclosuremodel +type GlpiEnclosureModel struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + Product_number int `json:"product_number"` + Weight int `json:"weight"` + Required_units string `json:"required_units"` + Depth string `json:"depth"` + Power_connections int `json:"power_connections"` + Power_consumption int `json:"power_consumption"` + Is_half_rack int `json:"is_half_rack"` + Picture_front string `json:"picture_front"` + Picture_rear string `json:"picture_rear"` +} + +type GlpiEnclosureItem struct { + Id int `json:"id"` + Enclosures_id int `json:"enclosures_id"` + Itemtype string `json:"itemtype"` + Items_id int `json:"items_id"` + Position int `json:"position"` +} + +// http://glpi/apirest.php/pdu +type GlpiPDU struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Serial string `json:"serial"` + Otherserial string `json:"otherserial"` + Pdumodels_id int `json:"pdumodels_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Template_name string `json:"template_name"` + States_id int `json:"states_id"` + Comment string `json:"comment"` + Manufacturers_id int `json:"manufacturers_id"` + Pdutypes_id int `json:"pdutypes_id"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/pduemodel +type GlpiPDUModel struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + Product_number int `json:"product_number"` + Weight int `json:"weight"` + Required_units string `json:"required_units"` + Depth string `json:"depth"` + Power_connections int `json:"power_connections"` + Max_power int `json:"max_power"` + Is_half_rack int `json:"is_half_rack"` + Picture_front string `json:"picture_front"` + Picture_rear string `json:"picture_rear"` + Is_rackable int `json:"is_rackable"` +} + +// http://glpi/apirest.php/pdu_plug +type GlpiPDUPlug struct { + Id int `json:"id"` + Plugs_id int `json:"plugs_id"` + Pdus_id int `json:"pdus_id"` + Number_plugs int `json:"number_plugs"` +} + +// http://glpi/apirest.php/passivedcequipment +type GlpiPassivedcEquipment struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Locations_id int `json:"locations_id"` + Serial string `json:"serial"` + Otherserial string `json:"otherserial"` + Passivedcequipmentmodels_id int `json:"passivedcequipmentmodels_id"` + Passivedcequipmenttypes_id int `json:"passivedcequipmenttypes_id"` + Users_id_tech int `json:"users_id_tech"` + Groups_id_tech int `json:"groups_id_tech"` + Is_template int `json:"is_template"` + Template_name string `json:"template_name"` + States_id int `json:"states_id"` + Comment string `json:"comment"` + Manufacturers_id int `json:"manufacturers_id"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/PassivedcEquipmentModel +type GlpiPassivedcEquipmentModel struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + Product_number int `json:"product_number"` + Weight int `json:"weight"` + Required_units string `json:"required_units"` + Depth string `json:"depth"` + Power_connections int `json:"power_connections"` + Power_consumption int `json:"power_consumption"` + Is_half_rack int `json:"is_half_rack"` + Picture_front string `json:"picture_front"` + Picture_rear string `json:"picture_rear"` +} + +// http://glpi/apirest.php/DeviceSimcard +type GlpiDeviceSimcard struct { + Id int `json:"id"` + Designation string `json:"name"` + Comment string `json:"comment"` + Entities_id int `json:"entities_id"` + Manufacturers_id int `json:"manufacturers_id"` + Voltage int `json:"voltage"` + Devicesimcardtypes_id int `json:"devicesimcardtypes_id"` + Allow_voip int `json:"allow_voip"` +} + +// http://glpi/apirest.php/item_DeviceSimcard +type GlpiDeviceSimcardItem struct { + Id int `json:"id"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Devicesimcards_id int `json:"devicesimcards_id"` + Entities_id int `json:"entities_id"` + Serial string `json:"serial"` + Otherserial string `json:"otherserial"` + States_id int `json:"states_id"` + Locations_id int `json:"locations_id"` + Lines_id int `json:"lines_id"` + Users_id int `json:"users_id"` + Groups_id int `json:"groups_id"` + Pin string `json:"pin"` + Pin2 string `json:"pin2"` + Puk string `json:"puk"` + Puk2 string `json:"puk2"` + Msin string `json:"msin"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/line +type GlpiLine struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Caller_num string `json:"caller_num"` + Caller_name string `json:"caller_name"` + Users_id int `json:"users_id"` + Groups_id int `json:"groups_id"` + Lineoperators_id int `json:"lineoperators_id"` + Locations_id int `json:"locations_id"` + States_id int `json:"states_id"` + Linetypes_id int `json:"linetypes_id"` + Comment string `json:"comment"` + Is_deleted int `json:"is_deleted"` +} + +// http://glpi/apirest.php/lineoperator +type GlpiLineOperator struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + Mcc int `json:"mcc"` + Mnc int `json:"mnc"` + Entities_id int `json:"entities_id"` +} + +// http://glpi/apirest.php/NetworkPort +type GlpiNetworkPort struct { + Id int `json:"id"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Entities_id int `json:"entities_id"` + Logical_number int `json:"logical_number"` + Name string `json:"name"` + Instantiation_type string `json:"instantiation_type"` + Mac string `json:"mac"` + Comment string `json:"comment"` +} + +// http://glpi/apirest.php/NetworkName +type GlpiNetworkName struct { + Id int `json:"id"` + Entities_id int `json:"entities_id"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Name string `json:"name"` + Comment string `json:"comment"` + Fqdns_id int `json:"fqdns_id"` +} + +// http://glpi/apirest.php/ipaddress +type GlpiIPAddress struct { + Id int `json:"id"` + Entities_id int `json:"entities_id"` + Items_id int `json:"items_id"` + Itemtype string `json:"itemtype"` + Version int `json:"version"` + Name string `json:"name"` + Comment string `json:"comment"` + Binary_0 int `json:"binary_0"` + Binary_1 int `json:"binary_1"` + Binary_2 int `json:"binary_2"` + Binary_3 int `json:"binary_3"` + Mainitems_id int `json:"mainitems_id"` + Mainitemtype string `json:"mainitemtype"` +} + +// http://glpi/apirest.php/fqdn +type GlpiFQDN struct { + Id int `json:"id"` + Name string `json:"name"` + Comment string `json:"comment"` + FQDN string `json:"fqdn"` + Entities_id int `json:"entities_id"` +} + +// http://glpi/apirest.php/problem +type GlpiProblem struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Is_deleted int `json:"is_deleted"` + Status int `json:"status"` + Content string `json:"content"` + Date string `json:"date"` + Solvedate string `json:"solvedate"` + Closedate string `json:"closedate"` + Time_to_resolve string `json:"time_to_resolve"` + Users_id_recipient int `json:"users_id_recipient"` + Users_id_lastupdater int `json:"users_id_lastupdater"` + Urgency int `json:"urgency"` + Impact int `json:"impact"` + Priority int `json:"priority"` + Itilcategories_id int `json:"itilcategories_id"` + Impactcontent string `json:"impactcontent"` + Causecontent string `json:"causecontent"` + Symptomcontent string `json:"symptomcontent"` + Actiontime int `json:"actiontime"` + Begin_waiting_date string `json:"begin_waiting_date"` + Waiting_duration int `json:"waiting_duration"` + Close_delay_stat int `json:"close_delay_stat"` + Solve_delay_stat int `json:"solve_delay_stat"` +} + +// http://glpi/apirest.php/change +type GlpiChange struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Is_deleted int `json:"is_deleted"` + Status int `json:"status"` + Content string `json:"content"` + Date string `json:"date"` + Solvedate string `json:"solvedate"` + Closedate string `json:"closedate"` + Time_to_resolve string `json:"time_to_resolve"` + Users_id_recipient int `json:"users_id_recipient"` + Users_id_lastupdater int `json:"users_id_lastupdater"` + Urgency int `json:"urgency"` + Impact int `json:"impact"` + Priority int `json:"priority"` + Itilcategories_id int `json:"itilcategories_id"` + Impactcontent string `json:"impactcontent"` + Controlistcontent string `json:"controlistcontent"` + Rolloutplancontent string `json:"rolloutplancontent"` + Backoutplancontent string `json:"backoutplancontent"` + Checklistcontent string `json:"checklistcontent"` + Global_validation int `json:"global_validation"` + Validation_percent int `json:"validation_percent"` + Actiontime int `json:"actiontime"` + Begin_waiting_date string `json:"begin_waiting_date"` + Waiting_duration int `json:"waiting_duration"` + Close_delay_stat int `json:"close_delay_stat"` + Solve_delay_stat int `json:"solve_delay_stat"` +} + +// http://glpi/apirest.php/ticketrecurrent +type GlpiTicketrecurrent struct { + Id int `json:"id"` + Name string `json:"name"` + Entities_id int `json:"entities_id"` + Is_active int `json:"is_active"` + Tickettemplates_id int `json:"tickettemplates_id"` + Begin_date string `json:"begin_date"` + Periodicity string `json:"periodicity"` + Create_before int `json:"create_before"` + Next_creation_date string `json:"next_creation_date"` + Calendars_id int `json:"calendars_id"` + End_date string `json:"end_date"` +} + +// This is a common data type for simple GLPI entities, like as: +// computertype, monitortype, networkequipmenttype, consumableitemtype, phonetype +// phonepowersupply, racktype, pdu, plug, passivedcequipmenttype, linetype +type GlpiSimpleItem struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` +} + +// This is a common data type for simple GLPI entities, like as: +// PrinterModel, PhoneModel, RackModel, DeviceCaseModel, DeviceDriveModel, DeviceGenericModel, +// DeviceGraphicCardModel, DeviceHardDriveModel, DeviceMemoryModel, DeviceMotherBoardModel, +// DeviceNetworkCardModel, DevicePciModel, DevicePowerSupplyModel, DeviceProcessorModel, +// DeviceSoundCardModel, DeviceSensorModel +type GlpiItemModel struct { + Id int `json:"id"` + Comment string `json:"comment"` + Name string `json:"name"` + Product_number string `json:"product_number"` +} + +// Http client setting +var client = &http.Client{ + Transport: &http.Transport{ + MaxIdleConnsPerHost: 10, + ResponseHeaderTimeout: 60 * time.Second, + DialContext: (&net.Dialer{Timeout: time.Second}).DialContext, + TLSClientConfig: &tls.Config{ + MaxVersion: tls.VersionTLS11, + InsecureSkipVerify: true, + }, + }, +} + +func NewSession(server, apiUserToken, apiAppToken string) (*Session, error) { + return &Session{server, apiUserToken, apiAppToken, ""}, nil +} + +func (glpi *Session) GetSessionToken() string { + return glpi.sessionToken +} + +// Init GLPI-session. +// Return glpi session token +func (glpi *Session) InitSession() (string, error) { + request, err := http.NewRequest("GET", glpi.url+"/initSession", nil) + if err != nil { + fmt.Println(request, err) + } + request.Header.Add("Content-Type", "application/json") + request.Header.Add("Authorization", "user_token "+glpi.userToken) + request.Header.Add("App-Token", glpi.appToken) + // fmt.Println(request) + + resp, err := client.Do(request) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + var result map[string]interface{} + json.NewDecoder(resp.Body).Decode(&result) + // fmt.Println(result["sessionToken"]) + + glpi.sessionToken = result["session_token"].(string) + + return result["session_token"].(string), nil +} + +// Kill GLPI-session. +// Return response code and error +func (glpi *Session) KillSession() (int, error) { + request, err := http.NewRequest("GET", glpi.url+"/killSession", nil) + if err != nil { + fmt.Println(request, err) + } + request.Header.Add("Content-Type", "application/json") + request.Header.Add("Session-Token", glpi.sessionToken) + request.Header.Add("App-Token", glpi.appToken) + + resp, err := client.Do(request) + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + return resp.StatusCode, err +} + +// Making http(s) request for metthod PUT and POST +func (glpi *Session) MakeRequest(method string, requestURL string, data map[string]interface{}) (map[string]interface{}, error) { + encodedData, err := json.Marshal(data) + if err != nil { + fmt.Println(encodedData, err) + } + request, err := http.NewRequest(method, glpi.url+"/"+requestURL+"/", bytes.NewBuffer(encodedData)) + + if err != nil { + fmt.Println(request, err) + } + request.Header.Add("Content-Type", "application/json") + request.Header.Add("Session-Token", glpi.sessionToken) + request.Header.Add("App-Token", glpi.appToken) + + response, err := client.Do(request) + + if err != nil { + fmt.Println(err) + } + + defer response.Body.Close() + + var result map[string]interface{} + // This is a magic. Because glpi PUT(DELETE) return an array [], but POST return {} + switch method { + case "PUT": + var r []map[string]interface{} + json.NewDecoder(response.Body).Decode(&r) + var res map[string]interface{} + // fmt.Println("length", len(r[0])) + if len(r[0]) > 0 { + res = map[string]interface{}{ + "status": 1, + } + } else { + res = map[string]interface{}{ + "status": 0, + } + } + result = res + // fmt.Println(result["status"]) + case "DELETE": + var r []map[string]interface{} + json.NewDecoder(response.Body).Decode(&r) + var res map[string]interface{} + if len(r[0]) > 0 { + res = map[string]interface{}{ + "status": 1, + } + } else { + res = map[string]interface{}{ + "status": 0, + } + } + result = res + // fmt.Println(result["status"]) + case "POST": + // var result map[string]interface{} + json.NewDecoder(response.Body).Decode(&result) + } + // fmt.Println(result) + return result, nil + +} + +// Making http(s) request for method GET +func (glpi *Session) MakeRequestGET(requestURL string) (bytes.Buffer, error) { + request, err := http.NewRequest("GET", glpi.url+"/"+requestURL, nil) + + if err != nil { + fmt.Println(request, err) + } + request.Header.Add("Content-Type", "application/json") + request.Header.Add("Session-Token", glpi.sessionToken) + request.Header.Add("App-Token", glpi.appToken) + + response, err := client.Do(request) + + if err != nil { + fmt.Println(err) + } + + var buf bytes.Buffer + _, err = io.Copy(&buf, response.Body) + if err != nil { + return buf, err + } + response.Body.Close() + return buf, nil +} + +// Add GLPI item +// Return new item id +func (glpi *Session) AddItem(itemType string, data map[string]interface{}) int { + response, err := glpi.MakeRequest("POST", itemType, data) + if err != nil { + fmt.Println(err) + } + // fmt.Println(response) + return int(response["id"].(float64)) +} + +// Update GLPI item +// Return result +func (glpi *Session) UpdateItem(itemType string, data map[string]interface{}) int { + response, err := glpi.MakeRequest("PUT", itemType+"/", data) + if err != nil { + fmt.Println(err) + } + + res, _ := strconv.Atoi(fmt.Sprint(response["status"])) + return res + +} + +// Delete GLPI item +// Return result +func (glpi *Session) DeleteItem(itemType string, data map[string]interface{}) int { + response, err := glpi.MakeRequest("DELETE", itemType+"/", data) + if err != nil { + fmt.Println(err) + } + res, _ := strconv.Atoi(fmt.Sprint(response["status"])) + return res + +} + +// Get GLPI config +func (glpi *Session) GetConfig() map[string]map[string]interface{} { + response, err := glpi.MakeRequestGET("getGlpiConfig") + if err != nil { + fmt.Println(err) + } + var result map[string]map[string]interface{} + json.Unmarshal(response.Bytes(), &result) + return result +} + +// Get GLPI version +func (glpi *Session) Version() string { + result := glpi.GetConfig() + return fmt.Sprint(result["cfg_glpi"]["version"]) +} + +// Get one Item. +func (glpi *Session) GetItem(itemType string, itemID int, otherParam string) []byte { + response, err := glpi.MakeRequestGET(itemType + "/" + strconv.Itoa(itemID) + string('?') + otherParam) + if err != nil { + fmt.Println(err) + } + return response.Bytes() +} + +// Search Item. Return item id if object was found +func (glpi *Session) SearchItem(itemType string, itemName string) int { + response, err := glpi.MakeRequestGET(itemType + "/?range=0-10000") + if err != nil { + fmt.Println(err) + } + var result []map[string]interface{} + json.Unmarshal(response.Bytes(), &result) + var found_id int + for _, item := range result { + if strings.EqualFold(itemName, fmt.Sprint(item["name"])) { + found_id, _ = strconv.Atoi(fmt.Sprint(item["id"])) + } + } + return found_id +} + +// Update item status +// http://glpi/apirest.php/_glpi_itemType_ +func (glpi *Session) UpdateItemStatus(itemType string, itemID int, itemStatusID int) { + message := map[string]interface{}{ + "input": map[string]int{ + "id": itemID, + "states_id": itemStatusID, + }, + } + fmt.Println(glpi.UpdateItem(itemType, message)) +} + +//------------------------------------------------------------------------------------------------- +func (glpi *Session) ItemOperation(operation string, glpiItemType string, data interface{}) int { + message := map[string]interface{}{ + "input": data, + } + var response int + switch operation { + case "add": + response = glpi.AddItem(glpiItemType, message) + case "update": + response = glpi.UpdateItem(glpiItemType, message) + case "delete": + response = glpi.DeleteItem(glpiItemType, message) + } + return response +} diff --git a/glpi/go.mod b/glpi/go.mod new file mode 100644 index 0000000..3200fcb --- /dev/null +++ b/glpi/go.mod @@ -0,0 +1,3 @@ +module glpi + +go 1.16 diff --git a/zabbix2glpi/go.mod b/zabbix2glpi/go.mod new file mode 100644 index 0000000..962e4e5 --- /dev/null +++ b/zabbix2glpi/go.mod @@ -0,0 +1,12 @@ +module zabbix2glpi + +go 1.16 + +replace glpi => ../glpi + +replace zabbix => ../../zabbix/zabbix + +require ( + glpi v0.0.0-00010101000000-000000000000 + zabbix v0.0.0-00010101000000-000000000000 +) diff --git a/zabbix2glpi/zabbix2glpi.go b/zabbix2glpi/zabbix2glpi.go new file mode 100644 index 0000000..f6387b9 --- /dev/null +++ b/zabbix2glpi/zabbix2glpi.go @@ -0,0 +1,487 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "glpi" + "os" + "strings" + "zabbix" +) + +// Find and return a single host object by name +func GetHost(zabbixAPI *zabbix.API, host string) (zabbix.ZabbixHost, error) { + params := make(map[string]interface{}, 0) + filter := make(map[string]string, 0) + filter["host"] = host + params["filter"] = filter + params["output"] = "extend" + params["select_groups"] = "extend" + params["templated_hosts"] = 1 + params["selectInventory"] = "extend" + params["selectInterfaces"] = "extend" + ret, err := zabbixAPI.Host("get", params) + + // This happens if there was an RPC error + if err != nil { + return nil, err + } + + // If our call was successful + if len(ret) > 0 { + return ret[0], err + } + + // This will be the case if the RPC call was successful, but + // Zabbix had an issue with the data we passed. + return nil, &zabbix.ZabbixError{0, "", "Host not found"} +} + +func GetHostGroup(zabbixAPI *zabbix.API, hostgroup string, select_type string) (zabbix.ZabbixHostGroup, error) { + params := make(map[string]interface{}, 0) + filter := make(map[string]string, 0) + filter["name"] = hostgroup + params["filter"] = filter + params["output"] = "extend" + if select_type == "all_hosts" { + params["selectHosts"] = "extend" + } + // params["select_groups"] = "extend" + //params["templated_hosts"] = 1 + ret, err := zabbixAPI.HostGroup("get", params) + + if err != nil { + return nil, err + } + + // If our call was successful + if len(ret) > 0 { + return ret[0], err + } + + // This will be the case if the RPC call was successful, but + // Zabbix had an issue with the data we passed. + return nil, &zabbix.ZabbixError{0, "", "HostGroup not found"} +} + +func MigrateHost(glpiAPI *glpi.Session, zabbixAPI *zabbix.API, item interface{}, glpiLocationID int) { + var ( + zbxHostOS string + zbxHostIP string + zbxHostFQDN string + zbxHostSerial string + zbxHostOtherSerial string + zbxHostUseDate string + zbxHostManufacturer string + zbxHostComputerModel string + glpiItemStatusID int + ) + itemType := "Computer" + typeID := glpiAPI.SearchItem("ComputerType", "Сервер") + // location_id := glpiAPI.SearchItem("Location", "ГО") + fmt.Println(typeID) + // Получаем имя узла, id и флаг инвентаризации + zbxHostName := fmt.Sprint(item.(map[string]interface{})["host"]) + + zbxHostStatus := fmt.Sprint(item.(map[string]interface{})["status"]) + // // если "inventory_mode": "-1" то инвентаризация отключена + zbxHostHasInventory := fmt.Sprint(item.(map[string]interface{})["inventory_mode"]) + // Если имя узла в заббикс как FQDN то обрезаем до первой точки + // zbxHostName_short := strings.Split(zbxHostName, ".")[0] + + glpiCompID := glpiAPI.SearchItem("Computer", strings.ToLower(zbxHostName)) + + fmt.Println(">>>>>>> ", zbxHostName) + + if glpiCompID != 0 { + fmt.Println("Узел ", zbxHostName, " существует в glpi c id:", glpiCompID) + return + } + // По имени узла запрашиваем полную информацию из заббикса и выдергиваем данные + zbxHostInfo, _ := GetHost(zabbixAPI, fmt.Sprint(zbxHostName)) + for _, i := range zbxHostInfo["interfaces"].([]interface{}) { + zbxHostIP = fmt.Sprint(i.(map[string]interface{})["ip"]) + zbxHostFQDN = strings.ToLower(fmt.Sprint(i.(map[string]interface{})["dns"])) + fmt.Println(zbxHostIP, zbxHostFQDN) + } + // Проверяем если флаг инвентаризации не равен -1 то получаем инвентарные данные + if zbxHostHasInventory != "-1" { + zbxHostOS = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["os"]) + zbxHostSerial = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["serialno_a"]) + zbxHostOtherSerial = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["serialno_b"]) + zbxHostUseDate = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["date_hw_install"]) + zbxHostManufacturer = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["vendor"]) + zbxHostComputerModel = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["model"]) + + fmt.Println(zbxHostOS, zbxHostSerial, zbxHostOtherSerial, zbxHostUseDate, zbxHostManufacturer, zbxHostComputerModel) + + } + + // получаем id модели оборудования. Если не найдено добавляем в glpi + glpiModelID := glpiAPI.SearchItem("ComputerModel", zbxHostComputerModel) + if glpiModelID == 0 { + requestData := glpi.GlpiComputerModel{ + Name: zbxHostComputerModel, + } + glpiModelID = glpiAPI.ItemOperation("add", "ComputerModel", requestData) + } + + // получаем id производителя из glpiAPI. если нету добавляем + glpiManufacturerID := glpiAPI.SearchItem("Manufacturer", zbxHostManufacturer) + if glpiManufacturerID == 0 { + requestData := glpi.GlpiManufacturer{ + Name: zbxHostManufacturer, + } + glpiManufacturerID = glpiAPI.ItemOperation("add", "Manufacturer", requestData) + } + + // добавляем железку + // проверяем статус + if zbxHostStatus == "0" { + glpiItemStatusID = glpiAPI.SearchItem("State", "В работе") + } + if zbxHostStatus == "1" { + glpiItemStatusID = glpiAPI.SearchItem("State", "Выключено") + } + + requestDataComp := glpi.GlpiComputer{ + Name: strings.ToLower(zbxHostName), + Serial: zbxHostSerial, + Otherserial: zbxHostOtherSerial, + Locations_id: glpiLocationID, + Computermodels_id: glpiModelID, + Computertypes_id: typeID, + Manufacturers_id: glpiManufacturerID, + States_id: glpiItemStatusID, + } + glpiCompID = glpiAPI.ItemOperation("add", "Computer", requestDataComp) + fmt.Println("Добавлен хост", glpiCompID) + + // Если выставлена дата установки то включаем фин. информаци. + // к году прибвавляем месяц и день + if len(zbxHostUseDate) <= 4 { + zbxHostUseDate = zbxHostUseDate + "-01-01" + } + if zbxHostUseDate != "" { + requestDataInfocom := glpi.GlpiInfocom{ + Items_id: glpiCompID, + Itemtype: itemType, + Use_date: zbxHostUseDate, + } + // fmt.Println("--->", requestDataInfocom) + glpiAPI.ItemOperation("add", "InfoCom", requestDataInfocom) + fmt.Println("Добавлена фин. информация ", glpiCompID) + } + + // Добавляем сетевой порт, адрес, FQDN, e.t.c + if zbxHostIP != "" { + glpiNetworkPortData := glpi.GlpiNetworkPort{ + Items_id: glpiCompID, + Itemtype: itemType, + Name: "Eth", + Instantiation_type: "NetworkPortEthernet", + } + glpiPortID := glpiAPI.ItemOperation("add", "NetworkPort", glpiNetworkPortData) + fmt.Println("Добавлен port", glpiPortID) + + // Отделяем имя узла от домена + zbxHostFQDN_short := strings.Split(zbxHostFQDN, ".")[0] + prefix := zbxHostFQDN_short + "." + zbxHostDomain := strings.TrimLeft(zbxHostFQDN, prefix) + fmt.Println(zbxHostFQDN, zbxHostFQDN_short, zbxHostDomain) + // Определяем ID домена в GLPI если он там есть + glpiFqdnID := glpiAPI.SearchItem("FQDN", zbxHostDomain) + fmt.Println("Домен - ", zbxHostDomain, glpiFqdnID) + + glpiNetworkData := glpi.GlpiNetworkName{ + Items_id: glpiPortID, + Itemtype: "NetworkPort", + Name: zbxHostFQDN_short, + Fqdns_id: glpiFqdnID, + } + glpiNetworkID := glpiAPI.ItemOperation("add", "NetworkName", glpiNetworkData) + fmt.Println("Добавлена сеть", glpiNetworkID) + + glpiIPAdressData := glpi.GlpiIPAddress{ + Items_id: glpiNetworkID, + Itemtype: "NetworkName", + Name: zbxHostIP, + } + glpiIpAddressID := glpiAPI.ItemOperation("add", "IPAddress", glpiIPAdressData) + fmt.Println("Добавлен IP", glpiIpAddressID) + } + // Проверяем что в заббикс для узла есть запись об ОС + if zbxHostOS != "" { + // получаем id ОС из glpiAPI. если нет добавляем + glpiOSID := glpiAPI.SearchItem("OperatingSystem", zbxHostOS) + fmt.Println("Добавлена ОС", glpiOSID) + if glpiOSID == 0 { + // request_data_os := glpi.GlpiOperatingSystem{ + // Name: zbxHostOS, + // } + glpiOSID = glpiAPI.ItemOperation("add", "OperatingSystem", glpi.GlpiOperatingSystem{Name: zbxHostOS}) + fmt.Println("Добавлена ОС", glpiOSID) + } + // Привязываем ОС к узлу в GLPI + requestDataOSItem := glpi.GlpiOSItem{ + Items_id: glpiCompID, + Itemtype: itemType, + Operatingsystems_id: glpiOSID, + } + glpiAPI.ItemOperation("add", "Item_OperatingSystem", requestDataOSItem) + } + +} + +func UpdateHostStatus(glpiAPI *glpi.Session, zabbixAPI *zabbix.API, item interface{}) { + // Получаем имя узла, id и флаг инвентаризации + itemType := "Computer" + // typeID := glpiAPI.SearchItem("ComputerType", "Сервер") + + zbxHostName := fmt.Sprint(item.(map[string]interface{})["host"]) + + zbxHostStatus := fmt.Sprint(item.(map[string]interface{})["status"]) + glpiItemID := glpiAPI.SearchItem(itemType, strings.ToLower(zbxHostName)) + res := glpiAPI.GetItem(itemType, glpiItemID, "") + + var statusInfo map[string]interface{} + err := json.Unmarshal(res, &statusInfo) + + if err != nil { + fmt.Println(err) + } + + glpiItemStatusID := statusInfo["states_id"] + + fmt.Println(">>>>>>> ", zbxHostName, zbxHostStatus, "glp id:", glpiItemID, "glpi status", glpiItemStatusID) + + var glpiStatusID int + + if zbxHostStatus == "0" { + glpiStatusID = glpiAPI.SearchItem("State", "В работе") + } + if zbxHostStatus == "1" { + glpiStatusID = glpiAPI.SearchItem("State", "Выключено") + } + fmt.Println(glpiItemStatusID, glpiStatusID) + if glpiItemStatusID != glpiStatusID { + fmt.Println("Update") + glpiAPI.UpdateItemStatus(itemType, glpiItemID, glpiStatusID) + } +} + +func main() { + var ( + zabbixServerAPI string + zabbixUser string + zabbixPassword string + zabbixHost string + zabbixHostGroups string + operation string + outputFormat string + glpiServerAPI string + glpiUserToken string + glpiAppToken string + glpiLocationID int + ) + + flag.StringVar(&zabbixServerAPI, "zabbix-server-api", "", "zabbix server API URL. ZABBIX_SERVER_API") + flag.StringVar(&zabbixUser, "zabbix-user", "", "Zabbix user name. ZABBIX_USER") + flag.StringVar(&zabbixPassword, "zabbix-password", "", "Zabbix password. ZABBIX_PASSWORD") + flag.StringVar(&zabbixHost, "zabbix-host", "", "Zabbix host name") + flag.StringVar(&zabbixHostGroups, "zabbix-host-groups", "", "Zabbix host groups, can be comma-separated list") + + flag.StringVar(&glpiServerAPI, "glpi-server-api", "", "Glpi instance API URL. GLPI_SERVER_URL") + flag.StringVar(&glpiUserToken, "glpi-user-token", "", "Glpi user API token. GLPI_USER_TOKEN") + flag.StringVar(&glpiAppToken, "glpi-app-token", "", "Glpi aplication API token. GLPI_APP_TOKEN") + flag.IntVar(&glpiLocationID, "glpi-location-id", 0, "Glpi location id for migration hosts") + + flag.StringVar(&operation, "operation", "zabbix-version", "Opertation type, must be:\n\tzabbix-version\n\tglpi-version\n\tget-host - getting zabbix host information\n\tget-hostgroup - getting zabbix hosts group\n\tget-hosts-from-group - getting zabbix group members hosts\n\tmigrate-host - migrate host from Zabbix to GLPI\n\tmigrate-hosts-from-group - migrate all zabbix groups members hosts to GLPI\n\tupdate-host-status - get host status from zabbix and update them into zabbix\n\tupdate-hosts-status-from-group - get group members hosts status from zabbix and update into glpi\n\t") + + flag.StringVar(&outputFormat, "output-format", "go", "Output format: 'go' - go map, 'json' - json string") + + flag.Parse() + + if zabbixServerAPI == "" && os.Getenv("ZABBIX_SERVER_API") == "" { + fmt.Println("Send error: make sure environment variables `ZABBIX_SERVER_API`, or used with '-zabbix-server-api' argument") + os.Exit(1) + } else if zabbixServerAPI == "" && os.Getenv("ZABBIX_SERVER_API") != "" { + zabbixServerAPI = os.Getenv("ZABBIX_SERVER_API") + } + // fmt.Println(zabbixServerAPI) + + if zabbixUser == "" && os.Getenv("ZABBIX_USER") == "" { + fmt.Println("Send error: make sure environment variables `ZABBIX_USER`, or used with '-zabbix-user' argument") + os.Exit(1) + } else if zabbixUser == "" && os.Getenv("ZABBIX_USER") != "" { + zabbixUser = os.Getenv("ZABBIX_USER") + } + // fmt.Println(zabbixUser ) + + if zabbixPassword == "" && os.Getenv("ZABBIX_PASSWORD") == "" { + fmt.Println("Send error: make sure environment variables `ZABBIX_PASSWORD`, or used with '-zabbix-password' argument") + os.Exit(1) + } else if zabbixPassword == "" && os.Getenv("ZABBIX_PASSWORD") != "" { + zabbixPassword = os.Getenv("ZABBIX_PASSWORD") + } + // fmt.Println(zabbixPassword) + + //----------------------------------------------------------- + if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_SERVER_API`, or used with '-glpi-server-api' argument") + os.Exit(1) + } else if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") != "" { + glpiServerAPI = os.Getenv("GLPI_SERVER_API") + } + + if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_USER_TOKEN`, or used with '-glpi-user-token' argument") + os.Exit(1) + } else if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") != "" { + glpiUserToken = os.Getenv("GLPI_USER_TOKEN") + } + + if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") == "" { + fmt.Println("Send error: make sure environment variables `GLPI_APP_TOKEN`, or used with '-glpi-app-token' argument") + os.Exit(1) + } else if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") != "" { + glpiAppToken = os.Getenv("GLPI_APP_TOKEN") + } + + // ------- Connected to zabbix API ---------- + zabbixAPI, err := zabbix.NewAPI(zabbixServerAPI, zabbixUser, zabbixPassword) + if err != nil { + fmt.Println(err) + return + } + + if operation != "zabbix-version" { + _, err = zabbixAPI.Login() + if err != nil { + fmt.Println(err) + return + } + // fmt.Println("Connected to API: OK") + } + + // ------- Connected to GLPI API ----------- + glpiAPI, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken) + if err != nil { + fmt.Println(err) + return + } + _, err = glpiAPI.InitSession() + if err != nil { + fmt.Println(err) + return + } + + switch operation { + case "zabbix-version": + zabbixVersion, err := zabbixAPI.Version() + if err != nil { + fmt.Println(err) + } + fmt.Println("Zabbix version:", zabbixVersion) + case "glpi-version": + glpiVersion := glpiAPI.Version() + fmt.Println("GLPI version:", glpiVersion) + case "get-host": + if zabbixHost == "" { + fmt.Println("Zabbix host not setting, using '-zabbix-host' command line argument") + os.Exit(1) + } else { + res, err := GetHost(zabbixAPI, zabbixHost) + if err != nil { + fmt.Println(err) + } + if outputFormat == "json" { + result, err := json.Marshal(res) + if err != nil { + fmt.Println(err) + } + fmt.Println(string(result)) + } else { + fmt.Println(res) + } + } + case "get-hostgroup": + if zabbixHostGroups == "" { + fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument") + os.Exit(1) + } else { + groupList := strings.Split(zabbixHostGroups, ",") + for _, item := range groupList { + fmt.Println(GetHostGroup(zabbixAPI, strings.TrimSpace(item), "no_host")) + } + } + case "get-hosts-from-group": + if zabbixHostGroups == "" { + fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute") + os.Exit(1) + } else { + groupList := strings.Split(zabbixHostGroups, ",") + for _, item := range groupList { + res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts") + // println(strings.TrimSpace(item)) + if err1 != nil { + fmt.Println(err1) + } + if outputFormat == "json" { + result, err := json.Marshal(res) + if err != nil { + fmt.Println(err) + } + // если "inventory_mode": "-1" то инвентаризация отключена + fmt.Println(string(result)) + } else { + fmt.Println(res) + } + } + } + case "migrate-host": + fmt.Println("Function not implemented yet") + case "migrate-hosts-from-group": + if zabbixHostGroups == "" { + fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute") + os.Exit(1) + } else { + groupList := strings.Split(zabbixHostGroups, ",") + for _, item := range groupList { + res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts") + println(strings.TrimSpace(item)) + if err1 != nil { + fmt.Println(err1) + } + // Пробегаемся по массиву узлов из забикса и выдергиваем интерфейсы и инвентарные данные + for _, item := range res["hosts"].([]interface{}) { + MigrateHost(glpiAPI, zabbixAPI, item, glpiLocationID) + } + } + } + case "update-host-status": + fmt.Println("Function not implemented yet") + case "update-hosts-status-from-group": + if zabbixHostGroups == "" { + fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute") + os.Exit(1) + } else { + groupList := strings.Split(zabbixHostGroups, ",") + for _, item := range groupList { + res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts") + println(strings.TrimSpace(item)) + if err1 != nil { + fmt.Println(err1) + } + // Пробегаемся по массиву узлов из забикса и выдергиваем статус + for _, item := range res["hosts"].([]interface{}) { + fmt.Println(item) + UpdateHostStatus(glpiAPI, zabbixAPI, item) + } + } + } + + } + +}